コード例 #1
0
  def ExportSequence(self, sRemoteUser, nSequenceID, sFilename):
    """Exports the specified sequence from the database"""
    log.debug("ExportSequence(user:%s,seqid:%d,filename:%s)" 
            % (sRemoteUser, nSequenceID, sFilename))
    # Load the sequence
    pDBSequence = self.GetSequence(sRemoteUser, nSequenceID, False)

    # Get the system configuration
    pConfiguration = self.database.GetConfiguration(sRemoteUser)

    # Create the sequence
    pSequence = {}
    pSequence["type"] ="sequence"
    pSequence["name"] = pDBSequence["metadata"]["name"]
    pSequence["description"] = pDBSequence["metadata"]["comment"]
    pSequence["reactors"] = pConfiguration["reactors"]
    pSequence["reagentsperreactor"] = pConfiguration["reagentsperreactor"]
    pSequence["reagents"] = []
    pSequence["components"] = []

    # Add the reagents from each cassette
    nCassette = 1
    for pComponent in pDBSequence["components"]:
        if pComponent["componenttype"] == "CASSETTE":
            pCassette = UnitOperations.createFromComponent(nSequenceID, pComponent, sRemoteUser, self.database)
            pCassette.addComponentDetails()
            for pReagent in pCassette.component["reagents"]:
                if pReagent["name"] != "":
                    pSequence["reagents"].append({"type":"reagent",
                        "cassette":nCassette,
                        "position":pReagent["position"],
                        "name":pReagent["name"],
                        "description":pReagent["description"]})
            nCassette += 1

    # Add each component
    for pComponent in pDBSequence["components"]:
        # Skip the cassettes
        if pComponent["componenttype"] == "CASSETTE":
            continue

        # Minimalize the component
        pUnitOperation = UnitOperations.createFromComponent(nSequenceID, 
                pComponent, sRemoteUser, self.database)
        pMinimalComponent = {}
        pUnitOperation.updateComponentDetails(pMinimalComponent)

        # Replace any reagent ID with a name
        if pComponent.has_key("reagent"):
            pMinimalComponent["reagent"] = pComponent["reagent"]["name"]

        # Append the component
        pSequence["components"].append(pMinimalComponent)

    # Save the sequence to the file
    pSequenceFile = open(sFilename, "w")
    sSequenceJSON = json.dumps(pSequence)
    pSequenceFile.write(sSequenceJSON)
コード例 #2
0
  def UpdateComponent(self, sRemoteUser, nSequenceID, nComponentID, nInsertionID, pComponent):
    """ Updates an existing component """
    # Why is nInsertionID None?
    nid =  nInsertionID if isinstance(nInsertionID,int) else 0 # This is a silly patch till i figure it out
    log.debug("UpdateComponent(user:%s,seqid:%d,cpmid:%d,insid:%d,pcomp:%s)" 
            % (sRemoteUser, nSequenceID, nComponentID, nid, pComponent.__class__.__name__))
    # Do we have an input component?
    if pComponent != None:
      # Yes, so pull the original from the database
      # and update it with the fields we want to save

      pUnitOperation = UnitOperations.createFromComponent(nSequenceID, 
              pComponent, sRemoteUser, self.database)
      pDBComponent = self.database.GetComponent(sRemoteUser, nComponentID)
      pUnitOperation.updateComponentDetails(pDBComponent)

      # Update the component
      self.database.UpdateComponent(sRemoteUser, nComponentID, 
              pDBComponent["componenttype"], pDBComponent["note"], json.dumps(pDBComponent))

    # Do a quick validation of the component
    self.ValidateComponent(sRemoteUser, nSequenceID, nComponentID)

    # Move the component as needed
    if nInsertionID != None:
      self.database.MoveComponent(sRemoteUser, nComponentID, nInsertionID)
コード例 #3
0
  def ValidateSequenceFull(self, sRemoteUser, nSequenceID):
    """Performs a full validation of the sequence"""
    # Load the sequence and all of the reagents
    vlog.debug("ValidateSequenceFull(user:%s,seqid:%d)" 
            % (sRemoteUser, nSequenceID)) 
    pSequence = self.GetSequence(sRemoteUser, nSequenceID)
    pAllReagents = self.database.GetReagentsBySequence(sRemoteUser, nSequenceID)

    # Filter reagents to keep only those that have a name
    pAvailableReagents = []
    for pReagent in pAllReagents:
      if pReagent["name"] != "":
        pAvailableReagents.append(pReagent)

    # Do a full validation of each component
    bValid = True
    for pComponent in pSequence["components"]:
      pUnitOperation = UnitOperations.createFromComponent(nSequenceID, pComponent, sRemoteUser, self.database)
      if not pUnitOperation.validateFull(pAvailableReagents):
        bValid = False
      pUnitOperation.saveValidation()

    # Update the valid flag in the database and return
    self.database.UpdateSequence(sRemoteUser, nSequenceID, 
            pSequence["metadata"]["name"], pSequence["metadata"]["comment"], bValid)
    self.database.UpdateSequenceDirtyFlag(sRemoteUser, nSequenceID, False)
    return bValid
コード例 #4
0
    def ValidateSequenceFull(self, sRemoteUser, nSequenceID):
        """Performs a full validation of the sequence"""
        # Load the sequence and all of the reagents
        vlog.debug("ValidateSequenceFull(user:%s,seqid:%d)" %
                   (sRemoteUser, nSequenceID))
        pSequence = self.GetSequence(sRemoteUser, nSequenceID)
        pAllReagents = self.database.GetReagentsBySequence(
            sRemoteUser, nSequenceID)

        # Filter reagents to keep only those that have a name
        pAvailableReagents = []
        for pReagent in pAllReagents:
            if pReagent["name"] != "":
                pAvailableReagents.append(pReagent)

        # Do a full validation of each component
        bValid = True
        for pComponent in pSequence["components"]:
            pUnitOperation = UnitOperations.createFromComponent(
                nSequenceID, pComponent, sRemoteUser, self.database)
            if not pUnitOperation.validateFull(pAvailableReagents):
                bValid = False
            pUnitOperation.saveValidation()

        # Update the valid flag in the database and return
        self.database.UpdateSequence(sRemoteUser, nSequenceID,
                                     pSequence["metadata"]["name"],
                                     pSequence["metadata"]["comment"], bValid)
        self.database.UpdateSequenceDirtyFlag(sRemoteUser, nSequenceID, False)
        return bValid
コード例 #5
0
    def UpdateComponent(self, sRemoteUser, nSequenceID, nComponentID,
                        nInsertionID, pComponent):
        """ Updates an existing component """
        # Why is nInsertionID None?
        nid = nInsertionID if isinstance(
            nInsertionID,
            int) else 0  # This is a silly patch till i figure it out
        log.debug(
            "UpdateComponent(user:%s,seqid:%d,cpmid:%d,insid:%d,pcomp:%s)" %
            (sRemoteUser, nSequenceID, nComponentID, nid,
             pComponent.__class__.__name__))
        # Do we have an input component?
        if pComponent != None:
            # Yes, so pull the original from the database
            # and update it with the fields we want to save

            pUnitOperation = UnitOperations.createFromComponent(
                nSequenceID, pComponent, sRemoteUser, self.database)
            pDBComponent = self.database.GetComponent(sRemoteUser,
                                                      nComponentID)
            pUnitOperation.updateComponentDetails(pDBComponent)

            # Update the component
            self.database.UpdateComponent(sRemoteUser, nComponentID,
                                          pDBComponent["componenttype"],
                                          pDBComponent["note"],
                                          json.dumps(pDBComponent))

        # Do a quick validation of the component
        self.ValidateComponent(sRemoteUser, nSequenceID, nComponentID)

        # Move the component as needed
        if nInsertionID != None:
            self.database.MoveComponent(sRemoteUser, nComponentID,
                                        nInsertionID)
コード例 #6
0
    def __init__(self, sRemoteUser, nSourceSequenceID, pSystemModel):
        """Constructor"""

        # Call base class init
        Thread.__init__(self)

        # Initialize variables
        self.username = sRemoteUser
        self.sourceSequenceID = nSourceSequenceID
        self.sourceComponentID = 0
        self.runSequenceID = 0
        self.runComponentID = 0
        self.systemModel = pSystemModel
        self.initializing = True
        self.running = False
        self.startComponentID = 0
        self.userSourceIDs = True
        self.runWillPause = False
        self.runIsPaused = False
        self.runAborted = False
        self.showAbortPrompt = False

        # Create database connection and sequence manager
        self.database = DBComm()
        self.database.Connect()
        self.sequenceManager = SequenceManager(self.database)

        # Create messaging object
        self.messaging = Messaging(self.username, self.database)

        # Fetch the sequence from the database and make sure it is valid
        self.sourceSequence = self.sequenceManager.GetSequence(
            self.username, self.sourceSequenceID)
        if not self.sourceSequence["metadata"]["valid"]:
            raise Exceptions("Cannot run an invalid sequence (" +
                             self.sourceSequenceID + ")")

        # Create a new sequence in the run history
        log.debug("Starting run of sequence " + str(self.sourceSequenceID) +
                  " (" + self.sourceSequence["metadata"]["name"] + ")")
        pConfiguration = self.database.GetConfiguration(self.username)
        self.runSequenceID = self.database.CreateSequence(
            self.username, self.sourceSequence["metadata"]["name"],
            self.sourceSequence["metadata"]["comment"], "History",
            pConfiguration["reactors"], pConfiguration["reagentsperreactor"])

        # Copy the cassettes
        for pComponent in self.sourceSequence["components"]:
            if pComponent["componenttype"] == Cassette.componentType:
                pUnitOperation = UnitOperations.createFromComponent(
                    self.sourceSequenceID, pComponent, self.username,
                    self.database)
                pUnitOperation.copyComponent(self.sourceSequenceID,
                                             self.runSequenceID)
コード例 #7
0
    def GetComponent(self, sRemoteUser, nComponentID, nSequenceID):
        """ Fetches a component from the database """
        log.debug("GetComponent(user:%s,compid:%d,seqid:%d)" %
                  (sRemoteUser, nComponentID, nSequenceID))
        # Fetch the component from the database
        pComponent = self.database.GetComponent(sRemoteUser, nComponentID)

        # Add details to the component and return
        pUnitOperation = UnitOperations.createFromComponent(
            nSequenceID, pComponent, sRemoteUser, self.database)
        pUnitOperation.addComponentDetails()
        return pUnitOperation.component
コード例 #8
0
  def GetComponent(self, sRemoteUser, nComponentID, nSequenceID):
    """ Fetches a component from the database """
    log.debug("GetComponent(user:%s,compid:%d,seqid:%d)" 
            % (sRemoteUser,nComponentID,nSequenceID))
    # Fetch the component from the database
    pComponent = self.database.GetComponent(sRemoteUser, nComponentID)

    # Add details to the component and return
    pUnitOperation = UnitOperations.createFromComponent(nSequenceID, 
            pComponent, sRemoteUser, self.database)
    pUnitOperation.addComponentDetails()
    return pUnitOperation.component
コード例 #9
0
  def InitializeComponent(self, sRemoteUser, nSequenceID, nComponentID):
    """Initializes the validation fields of a newly added component"""
    # Initialize the validation fields of the raw component
    vlog.debug("InitializeComponent(user:%s,seqid:%d,comid:%d)" 
            %(sRemoteUser, nSequenceID, nComponentID)) 
    pComponent = self.database.GetComponent(sRemoteUser, nComponentID)
    pUnitOperation = UnitOperations.createFromComponent(nSequenceID, pComponent, sRemoteUser, self.database)
    self.database.UpdateComponent(sRemoteUser, nComponentID, 
            pComponent["componenttype"], pUnitOperation.component["note"], 
            json.dumps(pUnitOperation.component))

    # Flag the sequence validation as dirty
    self.database.UpdateSequenceDirtyFlag(sRemoteUser, nSequenceID, True)
コード例 #10
0
    def InitializeComponent(self, sRemoteUser, nSequenceID, nComponentID):
        """Initializes the validation fields of a newly added component"""
        # Initialize the validation fields of the raw component
        vlog.debug("InitializeComponent(user:%s,seqid:%d,comid:%d)" %
                   (sRemoteUser, nSequenceID, nComponentID))
        pComponent = self.database.GetComponent(sRemoteUser, nComponentID)
        pUnitOperation = UnitOperations.createFromComponent(
            nSequenceID, pComponent, sRemoteUser, self.database)
        self.database.UpdateComponent(sRemoteUser, nComponentID,
                                      pComponent["componenttype"],
                                      pUnitOperation.component["note"],
                                      json.dumps(pUnitOperation.component))

        # Flag the sequence validation as dirty
        self.database.UpdateSequenceDirtyFlag(sRemoteUser, nSequenceID, True)
コード例 #11
0
  def GetSequence(self, sRemoteUser, nSequenceID, bFullLoad = True):
    """ Load the sequence and component metadata from the database """
    log.debug("GetSequence(user:%s,seqid:%d)" % (sRemoteUser, nSequenceID))
    # Load the sequence
    pSequence = self.database.GetSequence(sRemoteUser, nSequenceID)

    # Add details to each component if we're doing a full load
    if bFullLoad:
        for pComponent in pSequence["components"]:
          pUnitOperation = UnitOperations.createFromComponent(nSequenceID, pComponent, 
                  sRemoteUser, self.database)
          pUnitOperation.addComponentDetails()

    log.debug("Found Sequence: %s" % pSequence)
    # Return
    return pSequence
コード例 #12
0
    def GetSequence(self, sRemoteUser, nSequenceID, bFullLoad=True):
        """ Load the sequence and component metadata from the database """
        log.debug("GetSequence(user:%s,seqid:%d)" % (sRemoteUser, nSequenceID))
        # Load the sequence
        pSequence = self.database.GetSequence(sRemoteUser, nSequenceID)

        # Add details to each component if we're doing a full load
        if bFullLoad:
            for pComponent in pSequence["components"]:
                pUnitOperation = UnitOperations.createFromComponent(
                    nSequenceID, pComponent, sRemoteUser, self.database)
                pUnitOperation.addComponentDetails()

        log.debug("Found Sequence: %s" % pSequence)
        # Return
        return pSequence
コード例 #13
0
ファイル: EquiliReactor.py プロジェクト: shao130/sim42
    def Clone(self):
        clone = self.__class__(None)

        dontClone = ['myUnknowns', 'mySolver', '_parent']
        for attrName in self.__dict__:
            if attrName in dontClone:
                continue
            attr = self.__dict__[attrName]

            attrClone = None
            if hasattr(attr, 'Clone'):
                attrClone = attr.Clone()
            else:
                attrClone = UnitOperations._SafeClone(attr)

            clone.__dict__[attrName] = attrClone
        return clone
コード例 #14
0
ファイル: Sequences.py プロジェクト: henryeherman/elixys
  def __init__(self, sRemoteUser, nSourceSequenceID, pSystemModel):
    """Constructor"""

    # Call base class init
    Thread.__init__(self)

    # Initialize variables
    self.username = sRemoteUser
    self.sourceSequenceID = nSourceSequenceID
    self.sourceComponentID = 0
    self.runSequenceID = 0
    self.runComponentID = 0
    self.systemModel = pSystemModel
    self.initializing = True
    self.running = False
    self.startComponentID = 0
    self.userSourceIDs = True
    self.runWillPause = False
    self.runIsPaused = False
    self.runAborted = False
    self.showAbortPrompt = False

    # Create database connection and sequence manager
    self.database = DBComm()
    self.database.Connect()
    self.sequenceManager = SequenceManager(self.database)

    # Create messaging object
    self.messaging = Messaging(self.username, self.database)

    # Fetch the sequence from the database and make sure it is valid
    self.sourceSequence = self.sequenceManager.GetSequence(self.username, self.sourceSequenceID)
    if not self.sourceSequence["metadata"]["valid"]:
      raise Exceptions("Cannot run an invalid sequence (" + self.sourceSequenceID + ")")

    # Create a new sequence in the run history
    log.debug("Starting run of sequence " + str(self.sourceSequenceID) + " (" + self.sourceSequence["metadata"]["name"] + ")")
    pConfiguration = self.database.GetConfiguration(self.username)
    self.runSequenceID = self.database.CreateSequence(self.username, self.sourceSequence["metadata"]["name"], self.sourceSequence["metadata"]["comment"], "History", 
      pConfiguration["reactors"], pConfiguration["reagentsperreactor"])

    # Copy the cassettes
    for pComponent in self.sourceSequence["components"]:
      if pComponent["componenttype"] == Cassette.componentType:
        pUnitOperation = UnitOperations.createFromComponent(self.sourceSequenceID, pComponent, self.username, self.database)
        pUnitOperation.copyComponent(self.sourceSequenceID, self.runSequenceID)
コード例 #15
0
  def ValidateComponent(self, sRemoteUser, nSequenceID, nComponentID):
    """Performs a quick validation of the given component"""
    vlog.debug("ValidateComponent(user:%s,seqid:%d,comid:%d)" 
            %(sRemoteUser, nSequenceID, nComponentID)) 
    # Load the component and do a quick validation
    pComponent = self.GetComponent(sRemoteUser, nComponentID, nSequenceID)
    pUnitOperation = UnitOperations.createFromComponent(nSequenceID, pComponent, sRemoteUser, self.database)
    pUnitOperation.validateQuick()

    # Load the raw component and update just the validation field
    pDBComponent = self.database.GetComponent(sRemoteUser, nComponentID)
    pDBComponent["validationerror"] = pUnitOperation.component["validationerror"]
    self.database.UpdateComponent(sRemoteUser, nComponentID, 
            pDBComponent["componenttype"], pDBComponent["note"], json.dumps(pDBComponent))

    # Flag the sequence validation as dirty
    self.database.UpdateSequenceDirtyFlag(sRemoteUser, nSequenceID, True)
コード例 #16
0
ファイル: EquiliReactor.py プロジェクト: chemscobra/sim42
 def Clone(self):
     clone = self.__class__(None)
     
     dontClone = ['myUnknowns', 'mySolver', '_parent']
     for attrName in self.__dict__:
         if attrName in dontClone:
             continue
         attr = self.__dict__[attrName]
         
         attrClone = None
         if hasattr(attr, 'Clone'):
             attrClone = attr.Clone()
         else:
             attrClone = UnitOperations._SafeClone(attr)
         
         clone.__dict__[attrName] = attrClone
     return clone
コード例 #17
0
  def AddComponent(self, sRemoteUser, nSequenceID, nInsertionID, pComponent):
    """ Adds a new component to the database """
    log.debug("AddComponent(user:%s,seqid:%d,insid:%d,comclass:%s)" 
            % (sRemoteUser,nSequenceID,nInsertionID,pComponent.__class__.__name__))
    # Update the component fields we want to save
    pUnitOperation = UnitOperations.createFromComponent(nSequenceID, 
            pComponent, sRemoteUser, self.database)
    pDBComponent = {}
    pUnitOperation.updateComponentDetails(pDBComponent)

    # Insert the new component
    nComponentID = self.database.InsertComponent(sRemoteUser, 
            nSequenceID, pDBComponent["componenttype"], pDBComponent["note"], 
      json.dumps(pDBComponent), nInsertionID)

    # Initialize the new component's validation fields
    self.InitializeComponent(sRemoteUser, nSequenceID, nComponentID)
    self.ValidateComponent(sRemoteUser, nSequenceID, nComponentID)
    return nComponentID
コード例 #18
0
    def AddComponent(self, sRemoteUser, nSequenceID, nInsertionID, pComponent):
        """ Adds a new component to the database """
        log.debug("AddComponent(user:%s,seqid:%d,insid:%d,comclass:%s)" %
                  (sRemoteUser, nSequenceID, nInsertionID,
                   pComponent.__class__.__name__))
        # Update the component fields we want to save
        pUnitOperation = UnitOperations.createFromComponent(
            nSequenceID, pComponent, sRemoteUser, self.database)
        pDBComponent = {}
        pUnitOperation.updateComponentDetails(pDBComponent)

        # Insert the new component
        nComponentID = self.database.InsertComponent(
            sRemoteUser, nSequenceID, pDBComponent["componenttype"],
            pDBComponent["note"], json.dumps(pDBComponent), nInsertionID)

        # Initialize the new component's validation fields
        self.InitializeComponent(sRemoteUser, nSequenceID, nComponentID)
        self.ValidateComponent(sRemoteUser, nSequenceID, nComponentID)
        return nComponentID
コード例 #19
0
  def CopySequence(self, sRemoteUser, nSequenceID, sName, sComment):
    """ Creates a copy of an existing sequence in the database """
    log.debug("CopySequence(user:%s,seqid:%d,name:%s,comment:%s)" 
            % (sRemoteUser, nSequenceID, sName, sComment))
    # Create the new saved sequence
    pConfiguration = self.database.GetConfiguration(sRemoteUser)
    nNewSequenceID = self.database.CreateSequence(sRemoteUser, sName, sComment, "Saved", 
            pConfiguration["reactors"], pConfiguration["reagentsperreactor"])

    # Copy each component of the sequence
    pSequence = self.GetSequence(sRemoteUser, nSequenceID)
    for pComponent in pSequence["components"]:
      pUnitOperation = UnitOperations.createFromComponent(nSequenceID, 
              pComponent, sRemoteUser, self.database)
      pUnitOperation.copyComponent(nSequenceID, nNewSequenceID)

    # Validate the sequence
    self.ValidateSequenceFull(sRemoteUser, nNewSequenceID)

    # Return the ID of the new sequence
    return nNewSequenceID  
コード例 #20
0
    def ValidateComponent(self, sRemoteUser, nSequenceID, nComponentID):
        """Performs a quick validation of the given component"""
        vlog.debug("ValidateComponent(user:%s,seqid:%d,comid:%d)" %
                   (sRemoteUser, nSequenceID, nComponentID))
        # Load the component and do a quick validation
        pComponent = self.GetComponent(sRemoteUser, nComponentID, nSequenceID)
        pUnitOperation = UnitOperations.createFromComponent(
            nSequenceID, pComponent, sRemoteUser, self.database)
        pUnitOperation.validateQuick()

        # Load the raw component and update just the validation field
        pDBComponent = self.database.GetComponent(sRemoteUser, nComponentID)
        pDBComponent["validationerror"] = pUnitOperation.component[
            "validationerror"]
        self.database.UpdateComponent(sRemoteUser, nComponentID,
                                      pDBComponent["componenttype"],
                                      pDBComponent["note"],
                                      json.dumps(pDBComponent))

        # Flag the sequence validation as dirty
        self.database.UpdateSequenceDirtyFlag(sRemoteUser, nSequenceID, True)
コード例 #21
0
    def CopySequence(self, sRemoteUser, nSequenceID, sName, sComment):
        """ Creates a copy of an existing sequence in the database """
        log.debug("CopySequence(user:%s,seqid:%d,name:%s,comment:%s)" %
                  (sRemoteUser, nSequenceID, sName, sComment))
        # Create the new saved sequence
        pConfiguration = self.database.GetConfiguration(sRemoteUser)
        nNewSequenceID = self.database.CreateSequence(
            sRemoteUser, sName, sComment, "Saved", pConfiguration["reactors"],
            pConfiguration["reagentsperreactor"])

        # Copy each component of the sequence
        pSequence = self.GetSequence(sRemoteUser, nSequenceID)
        for pComponent in pSequence["components"]:
            pUnitOperation = UnitOperations.createFromComponent(
                nSequenceID, pComponent, sRemoteUser, self.database)
            pUnitOperation.copyComponent(nSequenceID, nNewSequenceID)

        # Validate the sequence
        self.ValidateSequenceFull(sRemoteUser, nNewSequenceID)

        # Return the ID of the new sequence
        return nNewSequenceID
コード例 #22
0
    def ExportSequence(self, sRemoteUser, nSequenceID, sFilename):
        """Exports the specified sequence from the database"""
        log.debug("ExportSequence(user:%s,seqid:%d,filename:%s)" %
                  (sRemoteUser, nSequenceID, sFilename))
        # Load the sequence
        pDBSequence = self.GetSequence(sRemoteUser, nSequenceID, False)

        # Get the system configuration
        pConfiguration = self.database.GetConfiguration(sRemoteUser)

        # Create the sequence
        pSequence = {}
        pSequence["type"] = "sequence"
        pSequence["name"] = pDBSequence["metadata"]["name"]
        pSequence["description"] = pDBSequence["metadata"]["comment"]
        pSequence["reactors"] = pConfiguration["reactors"]
        pSequence["reagentsperreactor"] = pConfiguration["reagentsperreactor"]
        pSequence["reagents"] = []
        pSequence["components"] = []

        # Add the reagents from each cassette
        nCassette = 1
        for pComponent in pDBSequence["components"]:
            if pComponent["componenttype"] == "CASSETTE":
                pCassette = UnitOperations.createFromComponent(
                    nSequenceID, pComponent, sRemoteUser, self.database)
                pCassette.addComponentDetails()
                for pReagent in pCassette.component["reagents"]:
                    if pReagent["name"] != "":
                        pSequence["reagents"].append({
                            "type":
                            "reagent",
                            "cassette":
                            nCassette,
                            "position":
                            pReagent["position"],
                            "name":
                            pReagent["name"],
                            "description":
                            pReagent["description"]
                        })
                nCassette += 1

        # Add each component
        for pComponent in pDBSequence["components"]:
            # Skip the cassettes
            if pComponent["componenttype"] == "CASSETTE":
                continue

            # Minimalize the component
            pUnitOperation = UnitOperations.createFromComponent(
                nSequenceID, pComponent, sRemoteUser, self.database)
            pMinimalComponent = {}
            pUnitOperation.updateComponentDetails(pMinimalComponent)

            # Replace any reagent ID with a name
            if pComponent.has_key("reagent"):
                pMinimalComponent["reagent"] = pComponent["reagent"]["name"]

            # Append the component
            pSequence["components"].append(pMinimalComponent)

        # Save the sequence to the file
        pSequenceFile = open(sFilename, "w")
        sSequenceJSON = json.dumps(pSequence)
        pSequenceFile.write(sSequenceJSON)
コード例 #23
0
ファイル: Sequences.py プロジェクト: henryeherman/elixys
  def run(self):
    """Thread entry point"""
    sRunError = ""
    self.userSourceIDs = True
    log.debug("Running Sequence")
    try:
      # Main sequence run loop
      log.debug("sourceSequence -> %s" % str(self.sourceSequence))
      sMessage = "Run of sequence \"" + self.sourceSequence["metadata"]["name"] + "\" started."
      log.debug(sMessage)
      self.messaging.broadcastMessage(sMessage)

      nComponentCount = len(self.sourceSequence["components"])
      nCurrentComponent = 0
      while nCurrentComponent < nComponentCount:
        # Get the next component
        pSourceComponent = self.sourceSequence["components"][nCurrentComponent]

        # Skip components until we find our start component
        self.sourceComponentID = pSourceComponent["id"]
        if self.initializing and (self.startComponentID != 0) and (self.sourceComponentID != self.startComponentID):
          log.debug("Skipping unit operation (" + pSourceComponent["componenttype"] + ")")
          nCurrentComponent += 1
          continue

        # Update our initializing and running flags
        self.initializing = False
        self.running = True

        # Ignore any previous summary component
        if pSourceComponent["componenttype"] == Summary.componentType:
          log.debug("Skipping unit operation (" + pSourceComponent["componenttype"] + ")")
          nCurrentComponent += 1
          continue

        # Create and run the next unit operation
        log.debug("Starting unit operation " + str(self.sourceComponentID) + " (" + 
          pSourceComponent["componenttype"] + ")")
        pSourceUnitOperation = UnitOperations.createFromComponent(self.sourceSequenceID, pSourceComponent, self.username, self.sequenceManager.database, self.systemModel)
        self.runComponentID = pSourceUnitOperation.copyComponent(self.sourceSequenceID, self.runSequenceID)
        pRunComponent = self.sequenceManager.GetComponent(self.username, self.runComponentID, self.runSequenceID)
        pRunUnitOperation = UnitOperations.createFromComponent(self.runSequenceID, pRunComponent, self.username, self.sequenceManager.database, self.systemModel)
        pRunUnitOperation.setDaemon(True)
        pRunUnitOperation.start()
         
        self.systemModel.SetUnitOperation(pRunUnitOperation)
        
        log.debug( "Unit Op is alive")
        # Wait until the operation completes or we receive an abort signal
        while pRunUnitOperation.is_alive() and not self.runAborted:
          log.debug( "Unit Op check alive")
          time.sleep(0.25)
        self.systemModel.SetUnitOperation(None)
        if self.runAborted:
          log.error( "Unit Op ABORTED!")
          pRunUnitOperation.setAbort()
          raise Exception("Run aborted")

        # Check for unit operation error
        log.debug( "Unit check for error")
        sError = pRunUnitOperation.getError()
        if sError != "":
          log.error("UnitOperation: %s" % pRunUnitOperation.__class__.__name__)
          log.error( "Unit operation failed: " + sError)
          raise Exception(sError)
        log.debug("Prepare to update operation details")
        # Update the unit operation details in the database
        UnitOperations.updateToComponent(pRunUnitOperation, self.runSequenceID, pRunComponent, self.username, self.sequenceManager.database, self.systemModel)
        log.debug("After updateToComponent")
        self.sequenceManager.UpdateComponent(self.username, self.runSequenceID, self.runComponentID, None, pRunComponent)
        log.debug("After updateComponent")
        log.debug("Completed unit operation (" + pRunComponent["componenttype"] + ")")
        self.sourceComponentID = 0
        self.runComponentID = 0

        # Check if the user paused the sequence for editing
        if self.runWillPause:
          # Pause until editing is complete
          log.debug("Pausing run for editing")
          self.runWillPause = False
          self.runIsPaused = True
          while self.runIsPaused and not self.runAborted:
            time.sleep(0.25)
          if self.runAborted:
            raise Exception("Sequence aborted")
          log.debug("Continuing paused run")

          # Reload the sequence and make sure it is still valid
          self.sourceSequence = self.sequenceManager.GetSequence(self.username, self.sourceSequenceID)
          if not self.sourceSequence["metadata"]["valid"]:
            raise Exceptions("Edited sequence is no longer valid (" + self.sourceSequenceID + ")")

          # Scan until we find the unit operation we just executed
          nComponentCount = len(self.sourceSequence["components"])
          nCurrentComponent = 0
          while nCurrentComponent < nComponentCount:
            if self.sourceSequence["components"][nCurrentComponent]["id"] == pSourceComponent["id"]:
              break
            nCurrentComponent += 1
          if nCurrentComponent == nComponentCount:
            raise Exception("Failed to find previous component in edited sequence")

        # Advance to the next component
        nCurrentComponent += 1
    except Exception as ex:
      log.error("Sequence run failed: " + str(ex))
      log.error("Trace Back %s" % traceback.format_exc()) 
      sRunError = str(ex)

    # Add the Summary unit operation to the sequence
    pSummaryComponent = Summary.createNewComponent(sRunError)
    self.runComponentID = self.database.CreateComponent(self.username, self.runSequenceID, pSummaryComponent["type"], pSummaryComponent["note"], json.dumps(pSummaryComponent))

    # Fully validate the run sequence
    self.sequenceManager.ValidateSequenceFull(self.username, self.runSequenceID)

    # Switch to using the run IDs rather than the source because the summary unit operation only exists in the run sequence
    self.userSourceIDs = False

    # Instantiate and start the summary unit operation
    log.info("Starting summary unit operation")
    pSummaryComponent = self.sequenceManager.GetComponent(self.username, self.runComponentID, self.runSequenceID)
    pSummaryUnitOperation = UnitOperations.createFromComponent(self.runSequenceID, pSummaryComponent, self.username, self.sequenceManager.database, self.systemModel)
    pSummaryUnitOperation.setDaemon(True)
    pSummaryUnitOperation.start()
    self.systemModel.SetUnitOperation(pSummaryUnitOperation)

    # Broadcast the summary unit operation message
    self.messaging.broadcastMessage(pSummaryComponent["message"])

    # Wait until the operation completes
    while pSummaryUnitOperation.is_alive():
      time.sleep(0.25)
      log.info("Summary unit operation complete")
    self.runComponentID = 0

    # Run complete
    log.debug("Run stopped")
    self.running = False
コード例 #24
0
ファイル: Pump.py プロジェクト: shao130/sim42
    def Solve(self):
        """Solve"""

        ## if not self.ValidateOk(): return None
        self.FlashAllPorts()  # make sure anything that can be flashed has been

        inport = self.GetPort(IN_PORT)
        outport = self.GetPort(OUT_PORT)

        #Only do the sharing for flows different to 0
        if inport.GetPropValue(MOLEFLOW_VAR) != 0.0 and outport.GetPropValue(
                MOLEFLOW_VAR) != 0.0:
            if self.GetParameterValue(ISENTROPIC_PAR) == 1:
                inport.SharePropWith(outport, S_VAR)
            elif self.GetParameterValue(ISENTROPIC_PAR) == -1:
                inport.SharePropWith(outport, H_VAR)

        self.balance.DoBalance()
        while self.FlashAllPorts():
            self.balance.DoBalance()

        propsIn = inport.GetProperties()
        propsOut = outport.GetProperties()

        P, T = propsOut[P_VAR], propsOut[T_VAR]
        if P.GetValue() == None and T.GetValue() == None:
            H, S, PIn, TIn = propsOut[H_VAR], propsOut[S_VAR], propsIn[
                P_VAR], propsIn[T_VAR]
            if H.GetValue() != None and S.GetValue() != None and PIn.GetValue(
            ) != None:
                unitOp, frac = self, outport.GetCompositionValues()
                knownTargetProp = (S_VAR, S.GetValue(),
                                   S.GetType().scaleFactor)
                knownFlashProp = (H_VAR, H.GetValue(), H.GetType().scaleFactor)
                iterProp = (P_VAR, PIn.GetValue(), P.GetType().scaleFactor)
                min, max = PIn.GetValue(), 10.0 * PIn.GetValue()
                converged = 0
                try:
                    val, converged = UnitOperations.CalculateNonSupportedFlash(
                        unitOp, frac, knownTargetProp, knownFlashProp,
                        iterProp, self.lastPOut, min, max)
                finally:
                    if converged:
                        self.lastPOut = val
                        P.SetValue(val, CALCULATED_V)
                        self.FlashAllPorts()
                    else:
                        self.lastPOut = None
                        self.InfoMessage('CouldNotSolveNonSuppFlash',
                                         (H_VAR, str(H.GetValue()), S_VAR,
                                          str(S.GetValue()), self.GetPath()))

        P, T = propsIn[P_VAR], propsIn[T_VAR]
        if P.GetValue() == None and T.GetValue() == None:
            H, S, POut, TOut = propsIn[H_VAR], propsIn[S_VAR], propsOut[
                P_VAR], propsOut[T_VAR]
            if H.GetValue() != None and S.GetValue() != None and POut.GetValue(
            ) != None:
                unitOp, frac = self, inport.GetCompositionValues()
                knownTargetProp = (S_VAR, S.GetValue(),
                                   S.GetType().scaleFactor)
                knownFlashProp = (H_VAR, H.GetValue(), H.GetType().scaleFactor)
                iterProp = (P_VAR, POut.GetValue(), P.GetType().scaleFactor)
                min, max = POut.GetValue() / 10.0, POut.GetValue()
                converged = 0
                try:
                    val, converged = UnitOperations.CalculateNonSupportedFlash(
                        unitOp, frac, knownTargetProp, knownFlashProp,
                        iterProp, self.lastPIn, min, max)
                finally:
                    if converged:
                        self.lastPIn = val
                        P.SetValue(val, CALCULATED_V)
                        self.FlashAllPorts()
                    else:
                        self.lastPIn = None
                        self.InfoMessage('CouldNotSolveNonSuppFlash',
                                         (H_VAR, str(H.GetValue()), S_VAR,
                                          str(S.GetValue()), self.GetPath()))

        dpPort = self.GetPort(DELTAP_PORT)
        pIn = inport.GetPropValue(P_VAR)
        pOut = outport.GetPropValue(P_VAR)
        dp = dpPort.GetValue()

        if pOut == None:
            if dp != None and pIn != None:
                outport.SetPropValue(P_VAR, pIn + dp, CALCULATED_V)
        elif pIn == None:
            if dp != None:
                inport.SetPropValue(P_VAR, pOut - dp, CALCULATED_V)
        else:
            dpPort.SetPropValue(DELTAP_VAR, pOut - pIn, CALCULATED_V)

        return 1
コード例 #25
0
    def run(self):
        """Thread entry point"""
        sRunError = ""
        self.userSourceIDs = True
        log.debug("Running Sequence")
        try:
            # Main sequence run loop
            log.debug("sourceSequence -> %s" % str(self.sourceSequence))
            sMessage = "Run of sequence \"" + self.sourceSequence["metadata"][
                "name"] + "\" started."
            log.debug(sMessage)
            self.messaging.broadcastMessage(sMessage)

            nComponentCount = len(self.sourceSequence["components"])
            nCurrentComponent = 0
            while nCurrentComponent < nComponentCount:
                # Get the next component
                pSourceComponent = self.sourceSequence["components"][
                    nCurrentComponent]

                # Skip components until we find our start component
                self.sourceComponentID = pSourceComponent["id"]
                if self.initializing and (self.startComponentID != 0) and (
                        self.sourceComponentID != self.startComponentID):
                    log.debug("Skipping unit operation (" +
                              pSourceComponent["componenttype"] + ")")
                    nCurrentComponent += 1
                    continue

                # Update our initializing and running flags
                self.initializing = False
                self.running = True

                # Ignore any previous summary component
                if pSourceComponent["componenttype"] == Summary.componentType:
                    log.debug("Skipping unit operation (" +
                              pSourceComponent["componenttype"] + ")")
                    nCurrentComponent += 1
                    continue

                # Create and run the next unit operation
                log.debug("Starting unit operation " +
                          str(self.sourceComponentID) + " (" +
                          pSourceComponent["componenttype"] + ")")
                pSourceUnitOperation = UnitOperations.createFromComponent(
                    self.sourceSequenceID, pSourceComponent, self.username,
                    self.sequenceManager.database, self.systemModel)
                self.runComponentID = pSourceUnitOperation.copyComponent(
                    self.sourceSequenceID, self.runSequenceID)
                pRunComponent = self.sequenceManager.GetComponent(
                    self.username, self.runComponentID, self.runSequenceID)
                pRunUnitOperation = UnitOperations.createFromComponent(
                    self.runSequenceID, pRunComponent, self.username,
                    self.sequenceManager.database, self.systemModel)
                pRunUnitOperation.setDaemon(True)
                pRunUnitOperation.start()

                self.systemModel.SetUnitOperation(pRunUnitOperation)

                log.debug("Unit Op is alive")
                # Wait until the operation completes or we receive an abort signal
                while pRunUnitOperation.is_alive() and not self.runAborted:
                    log.debug("Unit Op check alive")
                    time.sleep(0.25)
                self.systemModel.SetUnitOperation(None)
                if self.runAborted:
                    log.error("Unit Op ABORTED!")
                    pRunUnitOperation.setAbort()
                    raise Exception("Run aborted")

                # Check for unit operation error
                log.debug("Unit check for error")
                sError = pRunUnitOperation.getError()
                if sError != "":
                    log.error("UnitOperation: %s" %
                              pRunUnitOperation.__class__.__name__)
                    log.error("Unit operation failed: " + sError)
                    raise Exception(sError)
                log.debug("Prepare to update operation details")
                # Update the unit operation details in the database
                UnitOperations.updateToComponent(pRunUnitOperation,
                                                 self.runSequenceID,
                                                 pRunComponent, self.username,
                                                 self.sequenceManager.database,
                                                 self.systemModel)
                log.debug("After updateToComponent")
                self.sequenceManager.UpdateComponent(self.username,
                                                     self.runSequenceID,
                                                     self.runComponentID, None,
                                                     pRunComponent)
                log.debug("After updateComponent")
                log.debug("Completed unit operation (" +
                          pRunComponent["componenttype"] + ")")
                self.sourceComponentID = 0
                self.runComponentID = 0

                # Check if the user paused the sequence for editing
                if self.runWillPause:
                    # Pause until editing is complete
                    log.debug("Pausing run for editing")
                    self.runWillPause = False
                    self.runIsPaused = True
                    while self.runIsPaused and not self.runAborted:
                        time.sleep(0.25)
                    if self.runAborted:
                        raise Exception("Sequence aborted")
                    log.debug("Continuing paused run")

                    # Reload the sequence and make sure it is still valid
                    self.sourceSequence = self.sequenceManager.GetSequence(
                        self.username, self.sourceSequenceID)
                    if not self.sourceSequence["metadata"]["valid"]:
                        raise Exceptions(
                            "Edited sequence is no longer valid (" +
                            self.sourceSequenceID + ")")

                    # Scan until we find the unit operation we just executed
                    nComponentCount = len(self.sourceSequence["components"])
                    nCurrentComponent = 0
                    while nCurrentComponent < nComponentCount:
                        if self.sourceSequence["components"][
                                nCurrentComponent]["id"] == pSourceComponent[
                                    "id"]:
                            break
                        nCurrentComponent += 1
                    if nCurrentComponent == nComponentCount:
                        raise Exception(
                            "Failed to find previous component in edited sequence"
                        )

                # Advance to the next component
                nCurrentComponent += 1
        except Exception as ex:
            log.error("Sequence run failed: " + str(ex))
            log.error("Trace Back %s" % traceback.format_exc())
            sRunError = str(ex)

        # Add the Summary unit operation to the sequence
        pSummaryComponent = Summary.createNewComponent(sRunError)
        self.runComponentID = self.database.CreateComponent(
            self.username, self.runSequenceID, pSummaryComponent["type"],
            pSummaryComponent["note"], json.dumps(pSummaryComponent))

        # Fully validate the run sequence
        self.sequenceManager.ValidateSequenceFull(self.username,
                                                  self.runSequenceID)

        # Switch to using the run IDs rather than the source because the summary unit operation only exists in the run sequence
        self.userSourceIDs = False

        # Instantiate and start the summary unit operation
        log.info("Starting summary unit operation")
        pSummaryComponent = self.sequenceManager.GetComponent(
            self.username, self.runComponentID, self.runSequenceID)
        pSummaryUnitOperation = UnitOperations.createFromComponent(
            self.runSequenceID, pSummaryComponent, self.username,
            self.sequenceManager.database, self.systemModel)
        pSummaryUnitOperation.setDaemon(True)
        pSummaryUnitOperation.start()
        self.systemModel.SetUnitOperation(pSummaryUnitOperation)

        # Broadcast the summary unit operation message
        self.messaging.broadcastMessage(pSummaryComponent["message"])

        # Wait until the operation completes
        while pSummaryUnitOperation.is_alive():
            time.sleep(0.25)
            log.info("Summary unit operation complete")
        self.runComponentID = 0

        # Run complete
        log.debug("Run stopped")
        self.running = False