Skip to content

Validator Module

validator.parser_manager

ParserException dataclass

Bases: Exception

Exception for parser errors.

Parameters:

Name Type Description Default
rule str

The rule that caused the error.

required
parameter str

The parameter that caused the error.

required
message str

The error message.

required
Source code in src/validator/parser_manager.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@dataclass
class ParserException(Exception):
    """
    Exception for parser errors.

    Args:
        rule: The rule that caused the error.
        parameter: The parameter that caused the error.
        message: The error message.
    """

    rule: str
    parameter: str
    message: str

ParserManager

Parser manager to parse the SMILES strings.

Attributes:

Name Type Description
current_open_rnum

The current open ring numbers.

current_closed_rnum

The current closed ring numbers.

current_chain list[Atom]

The current chain.

Source code in src/validator/parser_manager.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
class ParserManager:
    """
    Parser manager to parse the SMILES strings.

    Attributes:
        current_open_rnum: The current open ring numbers.
        current_closed_rnum: The current closed ring numbers.
        current_chain: The current chain.
    """

    current_open_rnum = list()
    current_closed_rnum = list()
    current_chain: list[Atom] = list()

    def __enter__(self):
        """
        Initializes the parser manager.
        """
        self._reset()
        return self

    def __exit__(self):
        self._reset()

    def _reset(self):
        """
        Resets the parser manager to its initial state.
        """
        self.current_open_rnum = list()
        self.current_closed_rnum = list()
        self.current_chain = list()

    def chain(self, bond=None, atom=None, rnum=None, dot_proxy=None):

        if bond is None:

            if atom is not None:
                return atom

            if rnum is not None:
                return rnum

            return dot_proxy

        if bond == ":" and atom and type(atom) == str and atom[0].isupper():
            raise Exception(
                f"Aromatic bond cannot be use with Uppercase and collon {atom}"
            )

        # TODO: need to check if the atom is not bracketed too

        return [atom, chem.number_of_electrons_per_bond(bond)]

    def inner_branch(self, bond_dot=None, line=None, inner_branch=None):
        """ """
        if bond_dot == ".":
            self.validate_branch()
            self._reset()

        pass

    def validate_branch(self) -> bool:
        """
        Validates based on the current state of the parser manager
        """

        if len(self.current_open_rnum) != 0:
            raise ParserException(
                rule="validate_branch",
                parameter=f"{self.current_open_rnum}",
                message="Unclosed ring numbers",
            )

        starting_aromacity = self.current_chain[0].aromatic
        for atom in self.current_chain[1:]:
            if atom.aromatic != starting_aromacity:
                raise ParserException(
                    rule="validate_branch",
                    parameter=f"{atom}",
                    message="Aromaticity mismatch",
                )

        return True

    @fill_none
    def internal_bracket(self, istope, symbol, chiral, hcount, charge, mol_map):
        """
        Parses the internal bracket and checks for valency.
        """

        br_atom = chem.BracketAtom(
            isotope=istope,
            symbol=symbol,
            chiral=chiral,
            hidrogens=hcount,
            charge=charge,
            mol_map=mol_map,
        )

        self.current_chain.append(br_atom)

        return br_atom

    @fill_none
    def listify(self, base_element, recursion):
        """
        Generic rule for dealing with rules in the following format:

        x -> y x
        x -> y
        Args:
            base_element: Base element.
            recursion: The chain element.
        Returns:
            The parsed atom or chain branch.
        """
        if recursion is None:
            return base_element

        if type(recursion) == list:
            return [base_element] + recursion

        return [base_element, recursion]

    def atom(self, symbol_or_bracket: str):
        """
        Parses the atom symbol or bracket and from this point on always returns the parser manager
        Args:
            symbol_or_bracket: The atom symbol or bracket atom.
        Returns:
            The atom
        """

        # TODO maybe I'm missing to add to the chain here?

        if type(symbol_or_bracket) != str:
            return symbol_or_bracket

        if len(symbol_or_bracket) == 1 or symbol_or_bracket in chem.organic_atoms:
            return chem.Atom(symbol_or_bracket, aromatic=symbol_or_bracket.islower())

        elem1, elem2 = symbol_or_bracket

        if elem1 in chem.organic_atoms and elem2 in chem.organic_atoms:
            return [elem1, elem2]

        raise Exception(
            f"Inorganic Atom Outside Bracket {symbol_or_bracket} not allowed"
        )

    @fill_none
    def ring_number(
        self,
        ring_number_or_symbol: str,
        ring_number1: Optional[str],
        ring_number2: Optional[str],
    ) -> int:
        """
        Parses the ring numbers provided.
        Args:
            ring_number_or_symbol: A number or the % symbol.
            ring_number1: The first digit, if any.
            ring_number2: The second digit, if any.
        Returns:
            The parsed ring number as an integer.
        """
        rnum = -1
        raiser = lambda msg: ParserException(
            rule="ring_number",
            parameter=f"{ring_number_or_symbol} {ring_number1} {ring_number2}",
            message=msg,
        )

        if ring_number_or_symbol == "%":
            if ring_number1 is None:
                raiser(msg="Ring number cannot be just '%'")

            digits = ring_number1 + (ring_number2 or "")
            if not digits.isdigit():
                raiser(msg="Ring number must be a digit or '%'")
            rnum = int(digits)
        elif ring_number_or_symbol.isdigit():
            if ring_number2 is not None:
                raiser(
                    msg="Ring number cannot have more than one digit after the first"
                )
            digits = ring_number_or_symbol + (ring_number1 or "")
            if not digits.isdigit():
                raiser(
                    msg="Ring number must be a digit or a number with a leading digit"
                )
            rnum = int(digits)
        else:
            raiser(msg="Ring number must be a digit or a number with a leading digit")

        if rnum < 1:
            raiser(msg="Ring number must be greater than 0")

        if rnum in self.current_open_rnum:
            self.current_open_rnum.remove(rnum)
            self.current_closed_rnum.append(rnum)
        elif rnum in self.current_closed_rnum:
            raiser(
                msg="Ring number already closed",
            )
        else:
            self.current_open_rnum.append(rnum)

        return rnum

    def int(self, digits: List[str]) -> int:
        """
        Parses the provided digits to an integer.
        Args:
            digits: The digits to be parsed.
        Returns:
            The parsed integer.
        """
        return int("".join(digits))

    @fill_none
    def hcount(self, _, digit: Optional[str]) -> int:
        """
        Parses the hydrogen count.
        Args:
            digit: The digit to be parsed.
        Returns:
            The parsed hydrogen count.
        """
        if not digit.isdigit():
            raise ParserException(
                rule="hcount",
                parameter=digit,
                message="Hydrogen count must be a digit",
            )

        return int(digit) if digit else 1

    @fill_none
    def charge(self, charge1: str, charge2: Union[str, None, int]) -> int:
        """
        Parsers the charge string to an integer.
        Args:
            charge1: either "+" or "-".
            charge2: either "+", "-", None or an integer.
        Returns:
            The parsed charge as an integer.
        """
        if charge2 is None:
            return 1 if charge1 == "+" else -1

        if type(charge2) == str and charge2 != charge1:
            raise ParserException(
                rule="charge",
                parameter=f"{charge1} {charge2}",
                message="Charge mismatch",
            )

        if charge2 == "-":
            return -2

        if charge2 == "+":
            return 2

        if charge1 == "-":
            return charge2 * -1

        return charge2

    @fill_none
    def chiral(self, chiral1: str, chiral2: Optional[str]) -> str:
        """
        Fixes the current chiral rotation

        Args:
            chiral1: The first chiral symbol.
            chiral2: The second chiral symbol, if any.
        Returns:
            The current chiral rotation.
        """
        return "counterclockwise" if chiral2 else "clockwise"

    @fill_none
    def fifteen(self, digit1: str, digit2: Optional[str]) -> int:
        """
        Fixes fifteen as maximum value for valency
        Args:
            digit1: The first digit to be parsed.
            digit2: The second digit to be parsed, if any.
        Returns:
            The parsed rules.
        """
        if digit2:
            x = int(digit1 + digit2)

            if x > 15:
                raise ParserException(
                    rule="fifteen",
                    parameter=f"{digit1} {digit2}",
                    message="Cannot exceed 15",
                )
            return x

        return int(digit1)

__enter__

__enter__()

Initializes the parser manager.

Source code in src/validator/parser_manager.py
52
53
54
55
56
57
def __enter__(self):
    """
    Initializes the parser manager.
    """
    self._reset()
    return self

atom

atom(symbol_or_bracket: str)

Parses the atom symbol or bracket and from this point on always returns the parser manager Args: symbol_or_bracket: The atom symbol or bracket atom. Returns: The atom

Source code in src/validator/parser_manager.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def atom(self, symbol_or_bracket: str):
    """
    Parses the atom symbol or bracket and from this point on always returns the parser manager
    Args:
        symbol_or_bracket: The atom symbol or bracket atom.
    Returns:
        The atom
    """

    # TODO maybe I'm missing to add to the chain here?

    if type(symbol_or_bracket) != str:
        return symbol_or_bracket

    if len(symbol_or_bracket) == 1 or symbol_or_bracket in chem.organic_atoms:
        return chem.Atom(symbol_or_bracket, aromatic=symbol_or_bracket.islower())

    elem1, elem2 = symbol_or_bracket

    if elem1 in chem.organic_atoms and elem2 in chem.organic_atoms:
        return [elem1, elem2]

    raise Exception(
        f"Inorganic Atom Outside Bracket {symbol_or_bracket} not allowed"
    )

charge

charge(charge1: str, charge2: Union[str, None, int]) -> int

Parsers the charge string to an integer. Args: charge1: either "+" or "-". charge2: either "+", "-", None or an integer. Returns: The parsed charge as an integer.

Source code in src/validator/parser_manager.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
@fill_none
def charge(self, charge1: str, charge2: Union[str, None, int]) -> int:
    """
    Parsers the charge string to an integer.
    Args:
        charge1: either "+" or "-".
        charge2: either "+", "-", None or an integer.
    Returns:
        The parsed charge as an integer.
    """
    if charge2 is None:
        return 1 if charge1 == "+" else -1

    if type(charge2) == str and charge2 != charge1:
        raise ParserException(
            rule="charge",
            parameter=f"{charge1} {charge2}",
            message="Charge mismatch",
        )

    if charge2 == "-":
        return -2

    if charge2 == "+":
        return 2

    if charge1 == "-":
        return charge2 * -1

    return charge2

chiral

chiral(chiral1: str, chiral2: Optional[str]) -> str

Fixes the current chiral rotation

Parameters:

Name Type Description Default
chiral1 str

The first chiral symbol.

required
chiral2 Optional[str]

The second chiral symbol, if any.

required

Returns: The current chiral rotation.

Source code in src/validator/parser_manager.py
307
308
309
310
311
312
313
314
315
316
317
318
@fill_none
def chiral(self, chiral1: str, chiral2: Optional[str]) -> str:
    """
    Fixes the current chiral rotation

    Args:
        chiral1: The first chiral symbol.
        chiral2: The second chiral symbol, if any.
    Returns:
        The current chiral rotation.
    """
    return "counterclockwise" if chiral2 else "clockwise"

fifteen

fifteen(digit1: str, digit2: Optional[str]) -> int

Fixes fifteen as maximum value for valency Args: digit1: The first digit to be parsed. digit2: The second digit to be parsed, if any. Returns: The parsed rules.

Source code in src/validator/parser_manager.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
@fill_none
def fifteen(self, digit1: str, digit2: Optional[str]) -> int:
    """
    Fixes fifteen as maximum value for valency
    Args:
        digit1: The first digit to be parsed.
        digit2: The second digit to be parsed, if any.
    Returns:
        The parsed rules.
    """
    if digit2:
        x = int(digit1 + digit2)

        if x > 15:
            raise ParserException(
                rule="fifteen",
                parameter=f"{digit1} {digit2}",
                message="Cannot exceed 15",
            )
        return x

    return int(digit1)

hcount

hcount(_, digit: Optional[str]) -> int

Parses the hydrogen count. Args: digit: The digit to be parsed. Returns: The parsed hydrogen count.

Source code in src/validator/parser_manager.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
@fill_none
def hcount(self, _, digit: Optional[str]) -> int:
    """
    Parses the hydrogen count.
    Args:
        digit: The digit to be parsed.
    Returns:
        The parsed hydrogen count.
    """
    if not digit.isdigit():
        raise ParserException(
            rule="hcount",
            parameter=digit,
            message="Hydrogen count must be a digit",
        )

    return int(digit) if digit else 1

inner_branch

inner_branch(bond_dot=None, line=None, inner_branch=None)
Source code in src/validator/parser_manager.py
91
92
93
94
95
96
97
def inner_branch(self, bond_dot=None, line=None, inner_branch=None):
    """ """
    if bond_dot == ".":
        self.validate_branch()
        self._reset()

    pass

int

int(digits: List[str]) -> int

Parses the provided digits to an integer. Args: digits: The digits to be parsed. Returns: The parsed integer.

Source code in src/validator/parser_manager.py
248
249
250
251
252
253
254
255
256
def int(self, digits: List[str]) -> int:
    """
    Parses the provided digits to an integer.
    Args:
        digits: The digits to be parsed.
    Returns:
        The parsed integer.
    """
    return int("".join(digits))

internal_bracket

internal_bracket(istope, symbol, chiral, hcount, charge, mol_map)

Parses the internal bracket and checks for valency.

Source code in src/validator/parser_manager.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
@fill_none
def internal_bracket(self, istope, symbol, chiral, hcount, charge, mol_map):
    """
    Parses the internal bracket and checks for valency.
    """

    br_atom = chem.BracketAtom(
        isotope=istope,
        symbol=symbol,
        chiral=chiral,
        hidrogens=hcount,
        charge=charge,
        mol_map=mol_map,
    )

    self.current_chain.append(br_atom)

    return br_atom

listify

listify(base_element, recursion)

Generic rule for dealing with rules in the following format:

x -> y x x -> y Args: base_element: Base element. recursion: The chain element. Returns: The parsed atom or chain branch.

Source code in src/validator/parser_manager.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
@fill_none
def listify(self, base_element, recursion):
    """
    Generic rule for dealing with rules in the following format:

    x -> y x
    x -> y
    Args:
        base_element: Base element.
        recursion: The chain element.
    Returns:
        The parsed atom or chain branch.
    """
    if recursion is None:
        return base_element

    if type(recursion) == list:
        return [base_element] + recursion

    return [base_element, recursion]

ring_number

ring_number(ring_number_or_symbol: str, ring_number1: Optional[str], ring_number2: Optional[str]) -> int

Parses the ring numbers provided. Args: ring_number_or_symbol: A number or the % symbol. ring_number1: The first digit, if any. ring_number2: The second digit, if any. Returns: The parsed ring number as an integer.

Source code in src/validator/parser_manager.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
@fill_none
def ring_number(
    self,
    ring_number_or_symbol: str,
    ring_number1: Optional[str],
    ring_number2: Optional[str],
) -> int:
    """
    Parses the ring numbers provided.
    Args:
        ring_number_or_symbol: A number or the % symbol.
        ring_number1: The first digit, if any.
        ring_number2: The second digit, if any.
    Returns:
        The parsed ring number as an integer.
    """
    rnum = -1
    raiser = lambda msg: ParserException(
        rule="ring_number",
        parameter=f"{ring_number_or_symbol} {ring_number1} {ring_number2}",
        message=msg,
    )

    if ring_number_or_symbol == "%":
        if ring_number1 is None:
            raiser(msg="Ring number cannot be just '%'")

        digits = ring_number1 + (ring_number2 or "")
        if not digits.isdigit():
            raiser(msg="Ring number must be a digit or '%'")
        rnum = int(digits)
    elif ring_number_or_symbol.isdigit():
        if ring_number2 is not None:
            raiser(
                msg="Ring number cannot have more than one digit after the first"
            )
        digits = ring_number_or_symbol + (ring_number1 or "")
        if not digits.isdigit():
            raiser(
                msg="Ring number must be a digit or a number with a leading digit"
            )
        rnum = int(digits)
    else:
        raiser(msg="Ring number must be a digit or a number with a leading digit")

    if rnum < 1:
        raiser(msg="Ring number must be greater than 0")

    if rnum in self.current_open_rnum:
        self.current_open_rnum.remove(rnum)
        self.current_closed_rnum.append(rnum)
    elif rnum in self.current_closed_rnum:
        raiser(
            msg="Ring number already closed",
        )
    else:
        self.current_open_rnum.append(rnum)

    return rnum

validate_branch

validate_branch() -> bool

Validates based on the current state of the parser manager

Source code in src/validator/parser_manager.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def validate_branch(self) -> bool:
    """
    Validates based on the current state of the parser manager
    """

    if len(self.current_open_rnum) != 0:
        raise ParserException(
            rule="validate_branch",
            parameter=f"{self.current_open_rnum}",
            message="Unclosed ring numbers",
        )

    starting_aromacity = self.current_chain[0].aromatic
    for atom in self.current_chain[1:]:
        if atom.aromatic != starting_aromacity:
            raise ParserException(
                rule="validate_branch",
                parameter=f"{atom}",
                message="Aromaticity mismatch",
            )

    return True

fill_none

fill_none(func)

Decorator to fill None values in the function arguments

Source code in src/validator/parser_manager.py
 8
 9
10
11
12
13
14
15
16
17
18
19
def fill_none(func):
    """
    Decorator to fill None values in the function arguments
    """

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        needed = func.__code__.co_argcount - 1  # minus self
        padded = (list(args) + [None] * needed)[:needed]
        return func(self, *padded, **kwargs)

    return wrapper

validator.yacc

SmilesParser

Bases: Parser

Parser using the SLY library to parse SMILES strings.

Source code in src/validator/yacc.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
class SmilesParser(Parser):
    """
    Parser using the SLY library to parse SMILES strings.
    """

    debugfile = "parser.out"
    tokens = SmilesLex.tokens
    use_only_grammar = False

    def error(self, t):
        raise Exception(f"Error on {str(t)}")

    @_("atom", "atom chain_branch")  # type: ignore
    def line(self, rules):
        return parser_manager.listify(*rules)

    @_("chains", "branch", "chains chain_branch", "branch chain_branch")  # type: ignore
    def chain_branch(self, rules):
        return parser_manager.listify(*rules)

    @_("chain", "chain chains")  # type: ignore
    def chains(self, rules):
        return parser_manager.listify(*rules)

    @_('"[" internal_bracket "]"')  # type: ignore
    def bracket_atom(self, rules):
        return rules.internal_bracket

    @_(*generate_combinations("isotope? symbol chiral? hcount? charge? mol_map?"))  # type: ignore
    def internal_bracket(self, rules):
        return parser_manager.internal_bracket(
            *getAttributes(
                rules, ["isotope", "symbol", "chiral", "hcount", "charge", "mol_map"]
            )
        )

    @_("dot_proxy", "bond atom", "bond rnum", "atom", "rnum")  # type: ignore
    def chain(self, rules):
        return parser_manager.chain(
            *getAttributes(rules, ["bond", "atom", "rnum", "dot_proxy"])
        )

    @_('"." atom')  # type: ignore
    def dot_proxy(self, rules):
        return parser_manager.dot_proxy(rules.atom)

    @_("semi_symbol", '"H"')  # type: ignore
    def symbol(self, rules):
        return rules[0]

    @_('"(" inner_branch ")"')  # type: ignore
    def branch(self, rules):
        return rules.inner_branch

    @_("bond_dot line", "line", "bond_dot line inner_branch", "line inner_branch")  # type: ignore
    def inner_branch(self, rules):
        return parser_manager.inner_branch(
            *getAttributes(rules, ["bond_dot", "line", "inner_branch"])
        )

    @_("bond", '"."')  # type: ignore
    def bond_dot(self, rules):
        return rules[0]

    @_("semi_bond_rule", '"-"')  # type: ignore
    def bond(self, rules):
        return rules[0]

    @_("semi_bond")  # type: ignore
    def semi_bond_rule(self, rules):
        return rules[0]

    @_("symbol", "bracket_atom")  # type: ignore
    def atom(self, rules):
        return parser_manager.atom(rules[0])

    @_("digit", '"%" digit digit ')  # type: ignore
    def rnum(self, rules):
        return parser_manager.ring_number(*rules)

    @_("digit digit digit", "digit digit", "digit")  # type: ignore
    def isotope(self, rules):
        return parser_manager.int(*rules)

    @_('"H" digit', '"H"')  # type: ignore
    def hcount(self, rules):
        return parser_manager.hcount(*rules)

    @_('"+"', '"+" "+"', '"-"', '"-" "-"', '"-" fifteen', '"+" fifteen')  # type: ignore
    def charge(self, rules):
        return parser_manager.charge(*rules)

    @_('":" digit digit digit', '":" digit digit', '":" digit')  # type: ignore
    def mol_map(self, rules):
        return parser_manager.int(*rules[1:])

    @_('"@"', '"@" "@"')  # type: ignore
    def chiral(self, rules):
        return parser_manager.chiral(*rules)

    @_("digit digit", "digit")  # type: ignore
    def fifteen(self, rules):
        return parser_manager.fifteen(*rules)

generate_combinations

generate_combinations(rule: str) -> list[str]

Generate all combinations of a rule with optional elements. Example: rule = "X? Y Z?" combinations = [ X Y Z, X Y, Y Z, Y ]

Parameters:

Name Type Description Default
rule str

A string with the rule to generate combinations from.

required

Returns: A list of strings with all combinations of the rule.

Source code in src/validator/yacc.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def generate_combinations(rule: str) -> list[str]:
    """
    Generate all combinations of a rule with optional elements.
    Example:
        rule = "X? Y Z?"
        combinations = [ X Y Z, X Y, Y Z, Y ]

    Args:
        rule: A string with the rule to generate combinations from.
    Returns:
        A list of strings with all combinations of the rule.
    """
    parts = rule.split()

    # Separate required and optional elements
    required = [p.rstrip("?") for p in parts if not p.endswith("?")]
    optional = [p.rstrip("?") for p in parts if p.endswith("?")]

    all_combinations = []

    for i in range(len(optional) + 1):
        for combo in combinations(optional, i):
            ordered_combo = [
                p.rstrip("?")
                for p in parts
                if p.rstrip("?") in combo or p.rstrip("?") in required
            ]
            all_combinations.append(" ".join(ordered_combo))

    return all_combinations

getAttributes

getAttributes(rules, properties)

Get the attributes of the rules. Args: rules: The rules to get the attributes from. properties: The properties to get the attributes from. Returns: The attributes of the rules.

Source code in src/validator/yacc.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def getAttributes(rules, properties):
    """
    Get the attributes of the rules.
    Args:
        rules: The rules to get the attributes from.
        properties: The properties to get the attributes from.
    Returns:
        The attributes of the rules.
    """
    if type(properties) != list:
        return getattr(rules, properties, None)

    values = []

    for prop in properties:
        values.append(getAttributes(rules, prop))

    return values

validate_smiles

validate_smiles(mol: str) -> tuple[bool, Exception | None]

Function for valdiating a SMILES molecule.

Parameters:

Name Type Description Default
mol str

Chemical formula as a string.

required
use_only_grammar

For valdiating only the Grammar

required

Returns:

Type Description
tuple[bool, Exception | None]

A Tuple containg in the first element if it is a valid SMILES and the second element a Exception.

Source code in src/validator/yacc.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def validate_smiles(mol: str) -> tuple[bool, Exception | None]:
    """
    Function for valdiating a SMILES molecule.

    Args:
        mol: Chemical formula as a string.
        use_only_grammar: For valdiating only the Grammar

    Returns:
        A Tuple containg in the first element if it is a valid SMILES and the second element a Exception.
    """
    try:
        parser.parse(lexer.tokenize(mol))
        parser_manager.validate_branch()
        parser_manager._reset()
        return True, None
    except Exception as e:
        raise e
        return False, e

validator.lex

SmilesLex

Bases: Lexer

Tokenizer for SMILES strings.

Attributes:

Name Type Description
tokens

A set of all tokens

literals

A set of all literals

semi_symbol

A regex for semi symbols

semi_bond

A regex for semi bonds

digit

A regex for digits

Source code in src/validator/lex.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class SmilesLex(Lexer):
    """
    Tokenizer for SMILES strings.

    Attributes:
        tokens: A set of all tokens
        literals: A set of all literals
        semi_symbol: A regex for semi symbols
        semi_bond: A regex for semi bonds
        digit: A regex for digits
    """

    literals = {".", "@", "-", "+", ":", "%", "H", ")", "(", "]", "[", "H"}

    tokens = {"semi_bond", "digit", "semi_symbol"}

    semi_symbol = rf"{generate_regex_from_list(generate_lower(atoms))}"
    semi_bond = rf"{generate_regex_from_list(bonds)}"
    digit = r"\d"

generate_lower

generate_lower(elem_list: list[str]) -> list[str]

Generate a list of lower case elements from a list of elements and return both the lower and upper case elements.

Parameters:

Name Type Description Default
elem_list list[str]

A list of elements to generate a lower case list from.

required

Returns: A list with all elements.

Source code in src/validator/lex.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def generate_lower(elem_list: list[str]) -> list[str]:
    """
    Generate a list of lower case elements from a list of elements and return both the lower and upper case elements.

    Args:
        elem_list: A list of elements to generate a lower case list from.
    Returns:
        A list with all elements.
    """
    re_elem = []
    for elem in elem_list:

        re_elem.append(elem.lower())

    return sorted(elem_list, reverse=True) + sorted(re_elem, reverse=True)

generate_regex_from_list

generate_regex_from_list(elem_list: list[str]) -> str

Generate a regex from a list of elements.

Parameters:

Name Type Description Default
elem_list list[str]

A list of elements to generate a regex from.

required

Returns: A regex string that matches any of the elements in the list.

Source code in src/validator/lex.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def generate_regex_from_list(elem_list: list[str]) -> str:
    """
    Generate a regex from a list of elements.

    Args:
        elem_list: A list of elements to generate a regex from.
    Returns:
        A regex string that matches any of the elements in the list.
    """
    re_elem = []
    for elem in elem_list:
        re_elem.append(re.escape(elem))

    return "|".join(re_elem)