Ejemplo n.º 1
0
def loadModels(filename):
    """ load models into moose if file, if moosepath itself it passes back the path and 
    delete solver if exist """

    modelpath = '/'
    loaded = False

    if os.path.isfile(filename):
        modelpath = filename[filename.rfind('/'):filename.rfind('.')]
        ext = os.path.splitext(filename)[1]
        filename = filename.strip()
        modeltype = mtypes.getType(filename)
        subtype = mtypes.getSubtype(filename, modeltype)
        if subtype == 'kkit' or modeltype == "cspace":
            moose.loadModel(filename, modelpath)
            loaded = True

        elif subtype == 'sbml':
            #moose.ReadSBML()
            pass
        else:
            print("This file is not supported for mergering")
            modelpath = moose.Shell('/')
    elif moose.exists(filename):
        modelpath = filename
        loaded = True
    ## default is 'ee' solver while loading the model using moose.loadModel,
    ## yet deleteSolver is called just to be assured
    if loaded:
        deleteSolver(modelpath)

    return modelpath, loaded
Ejemplo n.º 2
0
def loadModels(filepath):
    """ load models into moose if file, if moosepath itself it passes back the path and 
    delete solver if exist """

    modelpath = '/'
    loaded = False

    if os.path.isfile(filepath):
        fpath, filename = os.path.split(filepath)
        # print " head and tail ",head,  " ",tail
        # modelpath = filename[filename.rfind('/'): filename.rfind('.')]
        # print "modelpath ",modelpath
        # ext = os.path.splitext(filename)[1]
        # filename = filename.strip()
        modelpath = '/' + filename[:filename.rfind('.')]
        modeltype = mtypes.getType(filepath)
        subtype = mtypes.getSubtype(filepath, modeltype)

        if subtype == 'kkit' or modeltype == "cspace":
            moose.loadModel(filepath, modelpath)
            loaded = True

        elif subtype == 'sbml':
            #moose.mooseReadSBML(filename,modelpath)
            #loaded = True
            pass
        else:
            print("This file is not supported for mergering")
            modelpath = moose.Shell('/')

    elif moose.exists(filepath):
        modelpath = filepath
        loaded = True

    return modelpath, loaded
Ejemplo n.º 3
0
def mergeChemModel(A, B):
    """ Merges two model or the path """

    modelA, loadedA = loadModels(A)
    modelB, loadedB = loadModels(B)
    if not loadedA or not loadedB:
        if not loadedA:
            modelB = moose.Shell('/')
        if not loadedB:
            modelA = moose.Shell('/')
    else:
        directory, bfname = os.path.split(B)
        global grpNotcopiedyet, poolListina
        poolListina = {}
        grpNotcopiedyet = []
        dictComptA = dict([
            (i.name, i)
            for i in moose.wildcardFind(modelA + '/##[ISA=ChemCompt]')
        ])
        dictComptB = dict([
            (i.name, i)
            for i in moose.wildcardFind(modelB + '/##[ISA=ChemCompt]')
        ])

        poolNotcopiedyet = []

        for key in list(dictComptB.keys()):
            if key not in dictComptA:
                # if compartmentname from modelB does not exist in modelA, then copy
                copy = moose.copy(dictComptB[key], moose.element(modelA))
            else:
                #if compartmentname from modelB exist in modelA,
                #volume is not same, then change volume of ModelB same as ModelA
                if abs(dictComptA[key].volume - dictComptB[key].volume):
                    #hack for now
                    while (abs(dictComptA[key].volume - dictComptB[key].volume)
                           != 0.0):
                        dictComptB[key].volume = float(dictComptA[key].volume)
                dictComptA = dict([
                    (i.name, i)
                    for i in moose.wildcardFind(modelA + '/##[ISA=ChemCompt]')
                ])

                #Mergering pool
                poolMerge(dictComptA[key], dictComptB[key], poolNotcopiedyet)

        if grpNotcopiedyet:
            # objA = moose.element(comptA).parent.name
            # if not moose.exists(objA+'/'+comptB.name+'/'+bpath.name):
            #   print bpath
            #   moose.copy(bpath,moose.element(objA+'/'+comptB.name))
            pass

        comptAdict = comptList(modelA)
        poolListina = {}
        poolListina = updatePoolList(comptAdict)
        funcNotallowed = []
        R_Duplicated, R_Notcopiedyet, R_Daggling = [], [], []
        E_Duplicated, E_Notcopiedyet, E_Daggling = [], [], []
        for key in list(dictComptB.keys()):
            funcNotallowed = []
            funcNotallowed = functionMerge(dictComptA, dictComptB, key)

            poolListina = updatePoolList(dictComptA)
            R_Duplicated, R_Notcopiedyet, R_Daggling = reacMerge(
                dictComptA, dictComptB, key, poolListina)

            poolListina = updatePoolList(dictComptA)
            E_Duplicated, E_Notcopiedyet, E_Daggling = enzymeMerge(
                dictComptA, dictComptB, key, poolListina)

        print("\n Model is merged to %s" % modelA)

        if funcNotallowed:
            print(
                "\nPool already connected to a function, this function is not to connect to same pool, since no two function are allowed to connect to same pool:"
            )
            for fl in list(funcNotallowed):
                print("\t [Pool]:  %s [Function]:  %s \n" %
                      (str(fl.parent.name), str(fl.path)))

        if R_Duplicated or E_Duplicated:
            print(
                "Reaction / Enzyme are Duplicate"
                "\n 1. The once whoes substrate / product names are different for a give reaction name "
                "\n 2. its compartment to which it belongs to may be is different"
                "\n Models have to decide to keep or delete these reaction/enzyme"
            )
            if E_Duplicated:
                print("Reaction: ")
            for rd in list(R_Duplicated):
                print("%s " % str(rd.name))

            if E_Duplicated:
                print("Enzyme:")
                for ed in list(E_Duplicated):
                    print("%s " % str(ed.name))

        if R_Notcopiedyet or E_Notcopiedyet:

            print(
                "\nThese Reaction/Enzyme in model are not dagging but while copying the associated substrate or product is missing"
            )
            if R_Notcopiedyet:
                print("Reaction: ")
            for rd in list(R_Notcopiedyet):
                print("%s " % str(rd.name))
            if E_Notcopiedyet:
                print("Enzyme:")
                for ed in list(E_Notcopiedyet):
                    print("%s " % str(ed.name))

        if R_Daggling or E_Daggling:
            print(
                "\n Daggling reaction/enzyme are not not allowed in moose, these are not merged"
            )
            if R_Daggling:
                print("Reaction: ")
                for rd in list(R_Daggling):
                    print("%s " % str(rd.name))
            if E_Daggling:
                print("Enzyme:")
                for ed in list(E_Daggling):
                    print("%s " % str(ed.name))
Ejemplo n.º 4
0
def mooseReadSBML(filepath, loadpath, solver="ee"):
    global foundLibSBML_
    if not foundLibSBML_:
        print(
            'No python-libsbml found.'
            '\nThis module can be installed by following command in terminal:'
            '\n\t easy_install python-libsbml'
            '\n\t apt-get install python-libsbml')
        return None

    if not os.path.isfile(filepath):
        print('%s is not found ' % filepath)
        return None

    with open(filepath, "r") as filep:
        filep = open(filepath, "r")
        document = libsbml.readSBML(filepath)
        tobecontinue = False
        tobecontinue = validateModel(document)
        if tobecontinue:
            level = document.getLevel()
            version = document.getVersion()
            print(("\n" + "File: " + filepath + " (Level " + str(level) +
                   ", version " + str(version) + ")"))
            model = document.getModel()
            if (model is None):
                print("No model present.")
                return moose.element('/')
            else:
                print((" model: " + str(model)))
                print(("functionDefinitions: " +
                       str(model.getNumFunctionDefinitions())))
                print(("    unitDefinitions: " +
                       str(model.getNumUnitDefinitions())))
                print(("   compartmentTypes: " +
                       str(model.getNumCompartmentTypes())))
                print(("        specieTypes: " +
                       str(model.getNumSpeciesTypes())))
                print(("       compartments: " +
                       str(model.getNumCompartments())))
                print(("            species: " + str(model.getNumSpecies())))
                print(
                    ("         parameters: " + str(model.getNumParameters())))
                print((" initialAssignments: " +
                       str(model.getNumInitialAssignments())))
                print(("              rules: " + str(model.getNumRules())))
                print(
                    ("        constraints: " + str(model.getNumConstraints())))
                print(("          reactions: " + str(model.getNumReactions())))
                print(("             events: " + str(model.getNumEvents())))
                print("\n")

                if (model.getNumCompartments() == 0):
                    return moose.element('/')
                else:
                    baseId = moose.Neutral(loadpath)
                    basePath = baseId
                    # All the model will be created under model as
                    # a thumbrule
                    basePath = moose.Neutral(baseId.path + '/model')
                    # Map Compartment's SBML id as key and value is
                    # list of[ Moose ID and SpatialDimensions ]
                    global comptSbmlidMooseIdMap
                    global warning
                    warning = " "
                    global msg
                    msg = " "
                    comptSbmlidMooseIdMap = {}
                    #print(("modelPath:" + basePath.path))
                    globparameterIdValue = {}
                    modelAnnotaInfo = {}
                    mapParameter(model, globparameterIdValue)
                    errorFlag = createCompartment(basePath, model,
                                                  comptSbmlidMooseIdMap)
                    if errorFlag:
                        specInfoMap = {}
                        errorFlag, warning = createSpecies(
                            basePath, model, comptSbmlidMooseIdMap,
                            specInfoMap, modelAnnotaInfo)
                        #print(errorFlag,warning)

                        if errorFlag:
                            errorFlag = createRules(model, specInfoMap,
                                                    globparameterIdValue)
                            if errorFlag:
                                errorFlag, msg = createReaction(
                                    model, specInfoMap, modelAnnotaInfo,
                                    globparameterIdValue)
                        getModelAnnotation(model, baseId, basePath)

                    if not errorFlag:
                        print(msg)
                        # Any time in the middle if SBML does not read then I
                        # delete everything from model level This is important
                        # as while reading in GUI the model will show up untill
                        # built which is not correct print "Deleted rest of the
                        # model"
                        moose.delete(basePath)
                        basePath = moose.Shell('/')
            return basePath
        else:
            print("Validation failed while reading the model.")
            return moose.element('/')