-
Notifications
You must be signed in to change notification settings - Fork 54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refactor and improve Molecule API's SMILES endpoint for better maintainability and performance #2246
Draft
adambasha0
wants to merge
5
commits into
main
Choose a base branch
from
prevent-creation-of-faulty-molecules
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Refactor and improve Molecule API's SMILES endpoint for better maintainability and performance #2246
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a84bf4b
feat: Refactor and improve Molecule API's SMILES endpoint for better …
adambasha0 71a02f6
fix: refactor spec tests for Molecule api
adambasha0 ab9722a
feat: add spec tests for SmilesProcessor class
adambasha0 d8f2c96
feat: add spec tests for MoleculeFetcher model
adambasha0 9b4ac96
test: WIP molecule creation
PiTrem File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -30,59 +30,11 @@ class MoleculeAPI < Grape::API | |
optional :editor, type: String, desc: 'SVGProcessor', default: 'ketcher' | ||
end | ||
post do | ||
smiles = params[:smiles] | ||
svg = params[:svg_file] | ||
result = Chemotion::SmilesProcessor.new(params).process | ||
molecule = result[:molecule] | ||
return {} unless molecule | ||
|
||
babel_info = OpenBabelService.molecule_info_from_structure(smiles, 'smi') | ||
inchikey = babel_info[:inchikey] | ||
return {} if inchikey.blank? | ||
|
||
molecule = Molecule.find_by(inchikey: inchikey, is_partial: false) | ||
unless molecule | ||
molfile = babel_info[:molfile] if babel_info | ||
begin | ||
rw_mol = RDKitChem::RWMol.mol_from_smiles(smiles) | ||
rd_mol = rw_mol.mol_to_mol_block unless rw_mol.nil? | ||
rescue StandardError => e | ||
Rails.logger.error ["with smiles: #{smiles}", e.message, *e.backtrace].join($INPUT_RECORD_SEPARATOR) | ||
rd_mol = rw_mol.mol_to_mol_block(true, -1, false) unless rw_mol.nil? | ||
end | ||
if rd_mol.nil? | ||
begin | ||
pc_mol = Chemotion::PubchemService.molfile_from_smiles(smiles) | ||
pc_mol = Chemotion::OpenBabelService.molfile_clear_hydrogens(pc_mol) unless pc_mol.nil? | ||
molfile = pc_mol unless pc_mol.nil? | ||
rescue StandardError => e | ||
Rails.logger.error ["with smiles: #{smiles}", e.message, *e.backtrace].join($INPUT_RECORD_SEPARATOR) | ||
end | ||
else | ||
molfile = rd_mol | ||
end | ||
return {} unless molfile | ||
molecule = Molecule.find_or_create_by_molfile(molfile, babel_info) | ||
molecule = Molecule.find_or_create_dummy if molecule.blank? | ||
end | ||
return unless molecule | ||
|
||
svg_digest = "#{molecule.inchikey}#{Time.now}" | ||
if svg.present? | ||
svg_process = SVG::Processor.new.structure_svg(params[:editor], svg, svg_digest) | ||
else | ||
svg_process = SVG::Processor.new.generate_svg_info('samples', svg_digest) | ||
svg_file_src = Rails.public_path.join('images', 'molecules', molecule.molecule_svg_file) | ||
if File.exist?(svg_file_src) | ||
mol = molecule.molfile.lines[0..1] | ||
if svg.nil? || svg&.include?('Open Babel') | ||
svg = Molecule.svg_reprocess(svg, molecule.molfile) | ||
svg_process = SVG::Processor.new.structure_svg('ketcher', svg, svg_digest, true) | ||
else | ||
FileUtils.cp(svg_file_src, svg_process[:svg_file_path]) | ||
end | ||
end | ||
end | ||
molecule.attributes.merge(temp_svg: File.exist?(svg_process[:svg_file_path]) && svg_process[:svg_file_name], ob_log: babel_info[:ob_log]) | ||
|
||
present molecule, with: Entities::MoleculeEntity | ||
Entities::MoleculeEntity.represent(molecule, temp_svg: result[:temp_svg], ob_log: result[:ob_log]) | ||
end | ||
end | ||
|
||
|
@@ -185,23 +137,21 @@ class MoleculeAPI < Grape::API | |
svg = params[:svg_file] | ||
molfile = params[:molfile] | ||
decoupled = params[:decoupled] | ||
molecule = decoupled ? Molecule.find_or_create_dummy : Molecule.find_or_create_by_molfile(molfile) | ||
molecule = Molecule.find_or_create_dummy if molecule.blank? | ||
molecule = if decoupled | ||
Molecule.find_or_create_dummy | ||
else | ||
Molecule.find_or_create_by_molfile(molfile) || Molecule.find_or_create_dummy | ||
end | ||
if molfile.present? | ||
molecule.molfile = molfile | ||
molecule.save! if molecule.changed? | ||
end | ||
ob = molecule&.ob_log | ||
if svg.present? | ||
svg_process = SVG::Processor.new.structure_svg(params[:editor], svg, molfile) | ||
mol = molecule.molfile.lines.first(2) | ||
if mol[1]&.strip&.match?('OpenBabel') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Style/ConditionalAssignment: Use the return of the conditional for variable assignment and comparison. |
||
svg_process = SVG::Processor.new(svg, 'openbabel', molecule).process | ||
else | ||
svg_file_src = Rails.public_path.join('images', 'molecules', molecule.molecule_svg_file) | ||
if File.exist?(svg_file_src) | ||
mol = molecule.molfile.lines.first(2) | ||
if mol[1]&.strip&.match?('OpenBabel') | ||
svg = File.read(svg_file_src) | ||
svg_process = SVG::Processor.new.structure_svg('openbabel', svg, molfile) | ||
else | ||
svg_process = SVG::Processor.new.generate_svg_info('samples', molfile) | ||
FileUtils.cp(svg_file_src, svg_process[:svg_file_path]) | ||
end | ||
end | ||
svg_process = SVG::Processor.new(svg, params[:editor], molecule).process | ||
end | ||
molecule&.attributes&.merge(temp_svg: svg_process[:svg_file_name], ob_log: ob) | ||
Entities::MoleculeEntity.represent(molecule, temp_svg: svg_process[:svg_file_name], ob_log: ob) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
# frozen_string_literal: true | ||
|
||
module Chemotion | ||
class MoleculeFetcher | ||
def initialize(smiles, babel_info) | ||
@smiles = smiles | ||
@babel_info = babel_info | ||
end | ||
|
||
def fetch_or_create | ||
find_existing || create_molecule | ||
end | ||
|
||
private | ||
|
||
def find_existing | ||
Molecule.find_by(inchikey: molecule_inchikey, is_partial: false) | ||
end | ||
|
||
def create_molecule | ||
molfile = fetch_molfile | ||
return unless molfile | ||
|
||
Molecule.find_or_create_by_molfile(molfile, @babel_info) || Molecule.find_or_create_dummy | ||
end | ||
|
||
def fetch_molfile | ||
@babel_info&.dig(:molfile) || rdkit_molfile || pubchem_molfile | ||
end | ||
|
||
def rdkit_molfile | ||
rw_mol = RDKitChem::RWMol.mol_from_smiles(@smiles) | ||
begin | ||
rw_mol&.mol_to_mol_block | ||
rescue StandardError => e | ||
handle_rdkit_error(e, rw_mol) | ||
end | ||
end | ||
|
||
def handle_rdkit_error(error, rw_mol) | ||
log_error(error) | ||
rw_mol&.mol_to_mol_block(true, -1, false) | ||
end | ||
|
||
def pubchem_molfile | ||
pc_mol = Chemotion::PubchemService.molfile_from_smiles(@smiles) | ||
validate_and_clear_molfile(pc_mol) | ||
rescue StandardError => e | ||
log_error(e) | ||
nil | ||
end | ||
|
||
def validate_and_clear_molfile(pc_mol) | ||
return unless validate_molfile(pc_mol) | ||
|
||
Chemotion::OpenBabelService.molfile_clear_hydrogens(pc_mol) | ||
end | ||
|
||
def validate_molfile(molfile) | ||
parsed = parse_to_hash(molfile) | ||
parsed['Status'] != '400' | ||
end | ||
|
||
def parse_to_hash(input) | ||
# Split the string into key-value pairs based on known patterns | ||
input.each_line.with_object({}) do |line, hash| | ||
next unless line =~ /^(.*?):\s*(.*)$/ | ||
|
||
key = Regexp.last_match(1).strip | ||
value = Regexp.last_match(2).strip | ||
hash[key] = value | ||
end | ||
end | ||
|
||
def molecule_inchikey | ||
@babel_info[:inchikey] | ||
end | ||
|
||
def log_error(error) | ||
Rails.logger.error ["with smiles: #{@smiles}", error.message, *error.backtrace].join($INPUT_RECORD_SEPARATOR) | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# frozen_string_literal: true | ||
|
||
module Chemotion | ||
class SmilesProcessor | ||
def initialize(params) | ||
@smiles = params[:smiles] | ||
@svg = params[:svg_file] | ||
@editor = params[:editor] | ||
end | ||
|
||
def process | ||
return unless valid_smiles? && babel_info.present? | ||
|
||
molecule = Chemotion::MoleculeFetcher.new(@smiles, babel_info).fetch_or_create | ||
return unless molecule | ||
|
||
svg_result = SVG::Processor.new(@svg, @editor, molecule).process | ||
build_result(molecule, svg_result) | ||
end | ||
|
||
private | ||
|
||
def valid_smiles? | ||
@smiles.present? | ||
end | ||
|
||
def babel_info | ||
@babel_info ||= Chemotion::OpenBabelService.molecule_info_from_structure(@smiles, 'smi') | ||
end | ||
|
||
def build_result(molecule, svg_result) | ||
{ molecule: molecule, temp_svg: svg_result[:svg_file_name], ob_log: babel_info[:ob_log] } | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Metrics/ClassLength: Class has too many lines. [243/200]