class SimilarityMapTool(BaseTool):
name: str = Field(default="Generate Similarity Map")
description: str = Field(default="Generates a similarity map between two molecules.")
def _run(self, smiles1: str, smiles2: str) -> str:
try:
mol1 = Chem.MolFromSmiles(smiles1)
mol2 = Chem.MolFromSmiles(smiles2)
if mol1 is None or mol2 is None:
return "Invalid SMILES string(s)"
# Generate the similarity map
fig, maxweight = SimilarityMaps.GetSimilarityMapForFingerprint(mol1, mol2, SimilarityMaps.GetMorganFingerprint)
# Convert figure to image
buf = BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
img_str = base64.b64encode(buf.getvalue()).decode()
# Display image in Streamlit
html_img = f'<img src="data:image/png;base64,{img_str}" alt="Similarity Map"/>'
st.markdown(html_img, unsafe_allow_html=True)
return "Similarity map displayed."
except Exception as e:
print(f"Error generating similarity map: {str(e)}")
return f"Error generating similarity map: {str(e)}"
class Config:
arbitrary_types_allowed = True
extra = "allow"
class SimilarityMapTool(BaseTool):
name: str = Field(default="Generate Similarity Map")
description: str = Field(default="Generates a similarity map between two molecules.")
def _run(self, smiles1: str, smiles2: str) -> str:
try:
mol1 = Chem.MolFromSmiles(smiles1)
mol2 = Chem.MolFromSmiles(smiles2)
if mol1 is None or mol2 is None:
return "Invalid SMILES string(s)"
# Generate the similarity map
fig, maxweight = SimilarityMaps.GetSimilarityMapForFingerprint(mol1, mol2, SimilarityMaps.GetMorganFingerprint)
# Convert figure to image
buf = BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
img_str = base64.b64encode(buf.getvalue()).decode()
# Display image in Streamlit
html_img = f'<img src="data:image/png;base64,{img_str}" alt="Similarity Map"/>'
st.markdown(html_img, unsafe_allow_html=True)
return "Similarity map displayed."
except Exception as e:
print(f"Error generating similarity map: {str(e)}")
return f"Error generating similarity map: {str(e)}"
class Config:
arbitrary_types_allowed = True
extra = "allow"
still i am not getting the similarity map as an image instread i am images of the two molecules for the prompt
Ensure the OpenAI API key is set
if "OPENAI_API_KEY" not in os.environ or os.environ["OPENAI_API_KEY"] == "your_openai_api_key_here":
st.error("Please set your OpenAI API key as an environment variable.")
st.stop()
st.markdown("🧪 Molecule Design Assistant", unsafe_allow_html=True)
st.markdown("Interact with AI agents to design and optimize molecules.", unsafe_allow_html=True)
Initialize session state variables
if "generated" not in st.session_state:
st.session_state["generated"] = []
if "past" not in st.session_state:
st.session_state["past"] = []
if "input_text" not in st.session_state:
st.session_state["input_text"] = ""
if "results" not in st.session_state:
st.session_state["results"] = []
from crewai import Agent
from tools.text_to_molecule_tool import TextToMoleculeTool
from tools.molecule_to_text_tool import MoleculeToTextTool
from tools.valid_molecule_tool import ValidMoleculeTool
from tools.molecule_optimizer_tool import MoleculeOptimizerTool
from tools.visualization_tool import VisualizationTool
from tools.rdkit_tools import CalculateLogPTool, CalculateMolWtTool, LipinskiRuleOfFiveTool, SimilarityMapTool
def create_agents(verbose=False):
# Agent 1: Chemistry Expert with RDKit tools
chemistry_expert = Agent(
role="Chemistry Expert",
goal="Provide detailed chemical analysis, calculate properties, and ensure molecule visualization.",
backstory="""You are a senior chemist with expertise in molecule analysis, property calculation, and visualization. Your goal is to:
1. Validate the input molecule structure.
2. Calculate properties like LogP, molecular weight, and Lipinski's rule.
3. Generate a high-quality visualization of the molecule.
4. If asked generate the similarity map and visualize it
Ensure all outputs are in a consistent format for downstream use. If any step fails, provide a detailed error message for debugging.
""",
tools=[
ValidMoleculeTool(),
VisualizationTool(),
CalculateLogPTool(),
CalculateMolWtTool(),
LipinskiRuleOfFiveTool(),
SimilarityMapTool(),
],
allow_delegation=True,
verbose=verbose,
)
# Agent 2: Molecule Generator and Descriptor
molecule_generator = Agent(
role="Molecule Generator",
goal="Generate valid molecular structures from text descriptions and convert molecules to textual descriptions",
backstory="""You are a molecule design expert specializing in:
1. Converting textual descriptions into valid molecular structures.
2. Translating molecular structures (e.g., SMILES) into human-readable descriptions.
### Instructions:
- For textual input:
- Generate a valid molecular structure that matches the description.
- Validate the generated molecule to ensure it is chemically sound.
- Provide the following outputs:
- **Molecule Name**: [Generated Name or 'N/A']
- **SMILES**: [SMILES String]
- **Description**: [Short textual description of the molecule]
- For SMILES input:
- Convert the given SMILES string into a human-readable textual description.
- Ensure the description is concise and accurate.
### Error Handling:
- If the text description is unclear or cannot be translated into a valid molecule, provide an error message and suggest improvements or clarifications.
- If the SMILES string is invalid, notify the user and suggest corrections or alternatives.
### Output Format:
Always present your outputs in the following structured format:
- **Input Type**: [Text Description or SMILES]
- **Input**: [User-provided input]
- **Generated Output**:
- **Molecule Name**: [Generated Name or 'N/A']
- **SMILES**: [SMILES String]
- **Description**: [Human-readable description of the molecule]
""",
tools=[TextToMoleculeTool(), MoleculeToTextTool(),VisualizationTool()],
allow_delegation=True,
verbose=verbose,
)
# Agent 3: Molecule Editor
molecule_editor = Agent(
role="Molecule Editor",
goal="Refine and optimize molecular structures based on user-defined criteria",
backstory="""You specialize in editing and optimizing molecular structures to achieve desired properties.
- When given a molecule, suggest alternatives or optimizations that improve its target properties (e.g., molecular weight, solubility, stability).
- Always provide the rationale behind each suggestion.
Ensure outputs are in the following format:
- **Original Molecule**:
- **Name**: [Original Name or 'N/A']
- **SMILES**: [Original SMILES]
- **Optimized Molecule**:
- **Name**: [Optimized Name or 'N/A']
- **SMILES**: [Optimized SMILES]
- **Reason for Optimization**: [Explanation of changes and benefits]
""",
tools=[MoleculeOptimizerTool(),ValidMoleculeTool(),VisualizationTool(),CalculateLogPTool(),CalculateMolWtTool()],
allow_delegation=True,
verbose=verbose,
)
# Additional agents (Agent 4 and Agent 5) can be added similarly when their tools are implemented
return [chemistry_expert, molecule_generator, molecule_editor]
docs
To use the new drawing code, we create a Draw2D object and pass that to SimilarityMaps.GetSimilarityMapForFingerprint:
def show_png(data):
bio = io.BytesIO(data)
img = Image.open(bio)
return img
d = Draw.MolDraw2DCairo(400, 400)
_, maxWeight = SimilarityMaps.GetSimilarityMapForFingerprint(atorvastatin, rosuvastatin,
lambda m, i: SimilarityMaps.GetMorganFingerprint(m, i, radius=2, fpType='bv'),
draw2d=d)
d.FinishDrawing()
show_png(d.GetDrawingText())
what should i need to do to show up the visulaization of the similarity map
It looks like the issue lies in how the similarity map is being generated and displayed. In your current code, you're using Matplotlib to create the figure, but instead, you should use RDKit's drawing utilities to generate the similarity map image.
Here's how you can modify your code to display the similarity map correctly in your Streamlit app:
Import the Necessary Modules:
Make sure you have the following imports at the beginning of your code:
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem.Draw import SimilarityMaps
import base64
from io import BytesIO
import streamlit as st
Modify the _run Method:
Update your SimilarityMapTool class's _run method to use MolDraw2DCairo instead of Matplotlib:
class SimilarityMapTool(BaseTool):
name: str = Field(default="Generate Similarity Map")
description: str = Field(default="Generates a similarity map between two molecules.")
def _run(self, smiles1: str, smiles2: str) -> str:
try:
mol1 = Chem.MolFromSmiles(smiles1)
mol2 = Chem.MolFromSmiles(smiles2)
if mol1 is None or mol2 is None:
return "Invalid SMILES string(s)"
# Create a drawing object
drawer = rdMolDraw2D.MolDraw2DCairo(400, 400)
# Generate the similarity map
SimilarityMaps.GetSimilarityMapForFingerprint(
mol1, mol2, SimilarityMaps.GetMorganFingerprint, draw2d=drawer
)
# Finish drawing and get the image data
drawer.FinishDrawing()
image = drawer.GetDrawingText()
# Convert image data to base64 string
img_str = base64.b64encode(image).decode()
# Display image in Streamlit
html_img = f'<img src="data:image/png;base64,{img_str}" alt="Similarity Map"/>'
st.markdown(html_img, unsafe_allow_html=True)
return "Similarity map displayed."
except Exception as e:
print(f"Error generating similarity map: {str(e)}")
return f"Error generating similarity map: {str(e)}"
class Config:
arbitrary_types_allowed = True
extra = "allow"
Explanation:
Drawing Object: Instead of using Matplotlib's fig, we create a MolDraw2DCairo object, which is RDKit's drawing class for creating images in memory.
Generating the Similarity Map: We pass the drawer object to SimilarityMaps.GetSimilarityMapForFingerprint, which draws the similarity map directly onto the drawer.
Retrieving Image Data: After finishing the drawing with drawer.FinishDrawing(), we get the image data using drawer.GetDrawingText().
Displaying in Streamlit: The image data is then encoded in base64 and displayed in Streamlit using an HTML img tag.
Ensure Correct Import Statements:
Double-check that you have all the necessary imports, specifically rdMolDraw2D and SimilarityMaps:
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import SimilarityMaps
from rdkit.Chem.Draw import rdMolDraw2D
import base64
from io import BytesIO
import streamlit as st
Update Your Streamlit App if Necessary:
If you're integrating this tool into a larger Streamlit app, ensure that the function that calls _run is passing the correct SMILES strings and that there are no conflicts with the Streamlit session state.
Example Usage:
Here's how you might call the SimilarityMapTool in your Streamlit app:
# Assume you have two SMILES strings
smiles1 = 'CC(=O)OC1=CC=CC=C1C(=O)O' # Example SMILES for Aspirin
smiles2 = 'CCOC(=O)C1=CC=CC=C1' # Example SMILES for Acetylsalicylic acid
# Create an instance of the tool
similarity_tool = SimilarityMapTool()
# Run the tool
result = similarity_tool._run(smiles1, smiles2)
# The image should now be displayed in your Streamlit app
st.write(result)
Additional Notes:
Ensure RDKit is Up-to-Date: The function GetSimilarityMapForFingerprint and its usage with MolDraw2DCairo require a relatively recent version of RDKit. Make sure your RDKit installation is up-to-date.
Error Handling: If you run into errors, print them out or display them using st.error() to get more insight.
Full Working Example:
Here's the complete SimilarityMapTool with all the necessary imports and configurations:
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import SimilarityMaps
from rdkit.Chem.Draw import rdMolDraw2D
import base64
from io import BytesIO
import streamlit as st
from pydantic import Field
class SimilarityMapTool(BaseTool):
name: str = Field(default="Generate Similarity Map")
description: str = Field(default="Generates a similarity map between two molecules.")
def _run(self, smiles1: str, smiles2: str) -> str:
try:
mol1 = Chem.MolFromSmiles(smiles1)
mol2 = Chem.MolFromSmiles(smiles2)
if mol1 is None or mol2 is None:
return "Invalid SMILES string(s)"
# Create a drawing object
drawer = rdMolDraw2D.MolDraw2DCairo(400, 400)
# Generate the similarity map
SimilarityMaps.GetSimilarityMapForFingerprint(
mol1, mol2, SimilarityMaps.GetMorganFingerprint, draw2d=drawer
)
# Finish drawing and get the image data
drawer.FinishDrawing()
image = drawer.GetDrawingText()
# Convert image data to base64 string
img_str = base64.b64encode(image).decode()
# Display image in Streamlit
html_img = f'<img src="data:image/png;base64,{img_str}" alt="Similarity Map"/>'
st.markdown(html_img, unsafe_allow_html=True)
return "Similarity map displayed."
except Exception as e:
st.error(f"Error generating similarity map: {str(e)}")
return f"Error generating similarity map: {str(e)}"
class Config:
arbitrary_types_allowed = True
extra = "allow"
Usage in Streamlit:
# Get SMILES input from the user
smiles1 = st.text_input("Enter the first SMILES string:")
smiles2 = st.text_input("Enter the second SMILES string:")
if st.button("Generate Similarity Map"):
if smiles1 and smiles2:
similarity_tool = SimilarityMapTool()
result = similarity_tool._run(smiles1, smiles2)
st.write(result)
else:
st.warning("Please enter both SMILES strings.")
By making these changes, your Streamlit app should display the similarity map image instead of just the individual molecule images. The key changes involve using MolDraw2DCairo and passing the drawing object to GetSimilarityMapForFingerprint, then retrieving and displaying the image data.
Let me know if you have any questions or need further assistance!