"""Implements a class for conveniently and efficiently storing sets of Pathway-basedobjects which share entries/reactions."""from__future__importannotationsfromfunctoolsimportcached_propertyfromtypingimportTYPE_CHECKINGfrommonty.jsonimportMSONablefromrxn_network.pathways.balancedimportBalancedPathwayfromrxn_network.pathways.basicimportBasicPathwayfromrxn_network.reactions.reaction_setimportReactionSetifTYPE_CHECKING:importnumpyasnpfromrxn_network.pathways.baseimportPathway
[docs]classPathwaySet(MSONable):"""A lightweight class for storing large sets of Pathway objects. Automatically represents a set of pathways as a (non-rectangular) 2D array of indices corresponding to reactions within a reaction set. This is useful for dumping reaction pathway data to a database. This object can easily be initialized through the from_paths() constructor. """def__init__(self,reaction_set:ReactionSet,indices:np.ndarray|list[list[int]],coefficients:np.ndarray|list[list[float]|None],costs:np.ndarray|list[list[float]],):""" Args: reaction_set: The reaction set containing all reactions in the pathways. indices: A list of lists of indices corresponding to reactions in the reaction set. coefficients: An array or list of coefficients representing the multiplicities (i.e., how much of) each reaction in the pathway. costs: An array or list of costs for each pathway. """self.reaction_set=reaction_setself.indices=indicesself.coefficients=coefficientsself.costs=costs@cached_propertydefpaths(self)->list[Pathway]:"""Returns list of Pathway objects represented by the PathwaySet. Cached for efficiency. """returnself._get_paths()def_get_paths(self,)->list[Pathway]:"""Returns list of Pathway objects represented by the PathwaySet."""paths=[]rxns=list(self.reaction_set.get_rxns())forindices,coefficients,costsinzip(self.indices,self.coefficients,self.costs,):reactions=[rxns[i]foriinindices]ifcoefficientsisnotNone:path=BalancedPathway(reactions=reactions,coefficients=coefficients,costs=costs)else:path=BasicPathway(reactions=reactions,costs=costs)paths.append(path)returnpaths
[docs]@classmethoddeffrom_paths(cls,paths:list[Pathway],)->PathwaySet:"""Initialize a PathwaySet object from a list of paths. Args: paths: List of Pathway objects """indices,coefficients,costs=[],[],[]reaction_set=cls._get_reaction_set(paths)rxns=list(reaction_set.get_rxns())forpathinpaths:indices.append([rxns.index(r)forrinpath.reactions])coefficients.append(getattr(path,"coefficients",None))costs.append(path.costs)returncls(reaction_set=reaction_set,indices=indices,coefficients=coefficients,costs=costs,)
@staticmethoddef_get_reaction_set(paths:list[Pathway],)->ReactionSet:"""Returns a reaction set built from a list of paths."""returnReactionSet.from_rxns([rxnforpathinpathsforrxninpath.reactions])def__iter__(self):"""Iterates over the PathwaySet."""returniter(self.paths)def__len__(self)->int:"""Returns the number of pathways in the PathwaySet."""returnlen(self.indices)