0 | module Text.Smiles.Parser
  1 |
  2 | import Chem
  3 | import Data.Finite
  4 | import Data.SnocVect
  5 | import Derive.Prelude
  6 | import Syntax.T1
  7 | import Text.ILex
  8 | import Text.ILex.State.Derive
  9 | import Text.Smiles.Types
 10 |
 11 | %default total
 12 | %language ElabReflection
 13 |
 14 | --------------------------------------------------------------------------------
 15 | -- Utilities
 16 | --------------------------------------------------------------------------------
 17 |
 18 | %inline
 19 | drop : List a -> List a
 20 | drop (_::t) = t
 21 | drop []     = []
 22 |
 23 | %inline
 24 | doubleHead : List a -> List a
 25 | doubleHead l@(h::_) = h::l
 26 | doubleHead []       = []
 27 |
 28 | public export
 29 | data SmilesErr : Type where
 30 |   RingBondMismatch   : SmilesErr
 31 |   UnclosedRing       : SmilesErr
 32 |   ManyEntries        : SmilesErr
 33 |
 34 | export
 35 | Interpolation SmilesErr where
 36 |   interpolate RingBondMismatch = "Ring bonds do not match"
 37 |   interpolate UnclosedRing     = "Unclosed ring"
 38 |   interpolate ManyEntries      = "More than one molecule"
 39 |
 40 | %runElab derive "SmilesErr" [Eq,Show]
 41 |
 42 | public export
 43 | 0 SmilesParseErr : Type
 44 | SmilesParseErr = ParseError SmilesErr
 45 |
 46 | data DOB : Type where
 47 |   No  : DOB
 48 |   Dot : DOB
 49 |   Bnd : SmilesBondOrder -> DOB
 50 |
 51 | record RingInfo n where
 52 |   constructor R
 53 |   start : Fin n
 54 |   rix   : RingIdx
 55 |   nr    : RingNr
 56 |   atom  : SmilesAtom
 57 |   bond  : Maybe SmilesBondOrder
 58 |   pos   : BytePos
 59 |
 60 | record AtomInfo n where
 61 |   constructor A
 62 |   node  : Fin n
 63 |   atom  : SmilesAtom
 64 |
 65 | record ST where
 66 |   constructor S
 67 |   cnt    : Nat
 68 |   rix    : RingIdx
 69 |   stck   : List (AtomInfo cnt)
 70 |   atoms  : SnocVect cnt SmilesAtom
 71 |   bonds  : List (Edge cnt SmilesBond)
 72 |   rings  : List (RingInfo cnt)
 73 |
 74 | empty : ST
 75 | empty = S 0 zero [] [<] [] []
 76 |
 77 | smilesBond : (xa,ya : Bool) -> BondTag -> SmilesBond
 78 | smilesBond True True bt = SB bt Arom
 79 | smilesBond _    _    bt = SB bt Sngl
 80 |
 81 | ringBond : (b,c : Maybe SmilesBondOrder) -> (x,y : SmilesAtom) -> BondTag -> Maybe SmilesBond
 82 | ringBond Nothing Nothing   x y bt = Just $ smilesBond (isArom x) (isArom y) bt
 83 | ringBond Nothing (Just x)  _ _ bt = Just (SB bt x)
 84 | ringBond (Just x) Nothing  _ _ bt = Just (SB bt x)
 85 | ringBond (Just x) (Just y) _ _ bt = if x == y then Just (SB bt x) else Nothing
 86 |
 87 | lookupRing : RingNr -> List (RingInfo n) -> Maybe (RingInfo n)
 88 | lookupRing r []      = Nothing
 89 | lookupRing r (x::xs) = case compare r (nr x) of
 90 |   LT => Nothing
 91 |   EQ => Just x
 92 |   GT => lookupRing r xs
 93 |
 94 | insert : RingInfo n -> List (RingInfo n) -> List (RingInfo n)
 95 | insert r []      = [r]
 96 | insert r (x::xs) = if r.nr < x.nr then r::x::xs else x::insert r xs
 97 |
 98 | delete : RingNr -> List (RingInfo n) -> List (RingInfo n)
 99 | delete r []      = []
100 | delete r (x::xs) = if r == x.nr then xs else x::delete r xs
101 |
102 | ringBondMismatch : Ring -> BytePos -> BBErr SmilesErr
103 | ringBondMismatch r p =
104 |  let bs := BB p $ incLen (length "\{r}") p
105 |   in B (Custom RingBondMismatch) bs
106 |
107 | toGraph : ST -> Either (BBErr SmilesErr) SmilesGraph
108 | toGraph (S n _ _ a b [])                  = Right $ G n (mkGraph (cast a) b)
109 | toGraph (S _ _ _ _ _ (R _ x r _ b p ::_)) =
110 |  let bs := BB p $ incLen (length "\{R r b}") p
111 |   in Left $ B (Custom UnclosedRing) bs
112 |
113 | weakenST : List (AtomInfo n) -> List (AtomInfo $ S n)
114 | weakenST x = believe_me x
115 |
116 | weakenBS : List (Edge n e) -> List (Edge (S n) e)
117 | weakenBS x = believe_me x
118 |
119 | weakenRS : List (RingInfo n) -> List (RingInfo (S n))
120 | weakenRS x = believe_me x
121 |
122 | plainAtom : SmilesAtom -> ST -> ST
123 | plainAtom a1 (S c x (A n a::ss) sa bs rs) =
124 |   let bs2 := edge n (smilesBond (isArom a) (isArom a1) CHAIN) :: weakenBS bs
125 |       st2 := A last a1 :: weakenST ss
126 |    in S (S c) x st2 (sa:<a1) bs2 (weakenRS rs)
127 | plainAtom a1 st = st
128 |
129 | atomWithBond : SmilesBondOrder -> SmilesAtom -> ST -> ST
130 | atomWithBond b a1 (S c x (A n _::ss) sa bs rs) =
131 |   let bs2 := edge n (SB CHAIN b) :: weakenBS bs
132 |       st2 := A last a1 :: weakenST ss
133 |    in S (S c) x st2 (sa:<a1) bs2 (weakenRS rs)
134 | atomWithBond b a1 st = st
135 |
136 | dottedAtom : SmilesAtom -> ST -> ST
137 | dottedAtom a1 (S c x st sa bs rs) =
138 |   S (S c) x (A last a1 :: weakenST st) (sa:<a1) (weakenBS bs) (weakenRS rs)
139 |
140 | addRing : BytePos -> Ring -> ST -> Either (BBErr SmilesErr) ST
141 | addRing p (R r mb1) st =
142 |   case st.stck of
143 |     A n1 a1::_ => case lookupRing r st.rings of
144 |       Just (R n2 rix nr a2 mb2 p) => case ringBond mb1 mb2 a1 a2 (RING rix st.rix) of
145 |         Just b  => case mkEdge n1 n2 b of
146 |           Just e  => Right $ {bonds $= (e::), rings $= delete r} st
147 |           Nothing => Right st -- impossible
148 |         Nothing => Left (ringBondMismatch (R r mb1) p)
149 |       Nothing => Right $ {rings $= insert (R n1 st.rix r a1 mb1 p)} st
150 |     [] => Right st -- impossible
151 |
152 | --------------------------------------------------------------------------------
153 | --          Parser
154 | --------------------------------------------------------------------------------
155 |
156 | export
157 | record SSTCK (q : Type) where
158 |   constructor SS
159 |   bufSize_    : Nat
160 |   prev_       : ByteString
161 |   cur_        : IBuffer bufSize_
162 |   prevOffset_ : Nat
163 |   curOffset_  : Nat
164 |   from_       : Ref q (LTENat bufSize_)
165 |   till_       : Ref q (LTENat bufSize_)
166 |   positions_  : Ref q (SnocList BytePos)
167 |   st          : Ref q ST
168 |   dob         : Ref q DOB
169 |   mass        : Ref q (Maybe MassNr)
170 |   elem        : Ref q AromElem
171 |   chirality   : Ref q Chirality
172 |   hcount      : Ref q HCount
173 |   charge      : Ref q Charge
174 |   error_      : Ref q (Maybe $ BBErr SmilesErr)
175 |   stack_      : Ref q (SnocList SmilesGraph)
176 |
177 | %runElab derive "SSTCK" [HasBytes, HasBBErr, HasStack]
178 |
179 | init : (n : Nat) -> IBuffer n -> F1 q (SSTCK q)
180 | init n buf = T1.do
181 |   rf  <- ref1 (first n)
182 |   rt  <- ref1 (first n)
183 |   ps  <- ref1 [<]
184 |   s   <- ref1 empty
185 |   db  <- ref1 Dot
186 |   ms  <- ref1 Nothing
187 |   el  <- ref1 (MkAE C False)
188 |   cy  <- ref1 (the Chirality None)
189 |   hc  <- ref1 (the HCount 0)
190 |   ch  <- ref1 (the Charge 0)
191 |   er  <- ref1 Nothing
192 |   st  <- ref1 [<]
193 |   pure (SS n empty buf 0 0 rf rt ps s db ms el cy hc ch er st)
194 |
195 | %runElab deriveParserState "SSz" "SST"
196 |   [ "Chain", "NewBranch", "SRing", "Closed", "Err", "Atom"
197 |   , "BMass","BElem","BChiral","BHCount","BCharge","BEnd"
198 |   ]
199 |
200 | endGraph : SSTCK q -> F1 q (Maybe (BBErr SmilesErr))
201 | endGraph sk = T1.do
202 |   st    <- replace1 sk.st empty
203 |   write1 sk.dob Dot
204 |   let Right g := toGraph st | Left err => pure (Just err)
205 |   [<] <- replace1 sk.positions_ [<]
206 |     | _:<p => pure $ Just (B (Unclosed "(") (BB p p))
207 |   case g.order of
208 |     0 => pure Nothing
209 |     _ => push1 sk.stack_ g >> pure Nothing
210 |
211 | onAtom : SmilesAtom -> Step1 q SSz SSTCK
212 | onAtom a = \sk,t =>
213 |  let s # t := read1 sk.st t
214 |   in case read1 sk.dob t of
215 |        No    # t => writeAs sk.st (plainAtom a s) SRing t
216 |        Bnd b # t =>
217 |         let _ # t := write1 sk.dob No t
218 |          in writeAs sk.st (atomWithBond b a s) SRing t
219 |        Dot # t  =>
220 |         let _ # t := write1 sk.dob No t
221 |          in writeAs sk.st (dottedAtom a s) SRing t
222 |
223 | onRing : Ring -> Step1 q SSz SSTCK
224 | onRing r = \sk,t =>
225 |   let p # t := startPos t
226 |       s # t := read1 sk.st t
227 |    in case addRing p r $ {rix $= inc} s of
228 |         Right s2 => writeAs sk.st s2 SRing t
229 |         Left  x  => failWith x Err t
230 |
231 | bracket : (sk : SSTCK q) => F1 q SST
232 | bracket t =
233 |   let m  # t := replace1 sk.mass Nothing t
234 |       e  # t := read1 sk.elem t
235 |       cy # t := replace1 sk.chirality None t
236 |       h  # t := replace1 sk.hcount 0 t
237 |       ch # t := replace1 sk.charge 0 t
238 |    in onAtom (bracket (aromIsotope m e) cy h ch) sk t
239 |
240 | mass : (RExp True, Step q SSz SSTCK)
241 | mass = bytes (plus digit) wrt
242 |   where
243 |     %inline wrt : (sk : SSTCK q) =>  ByteString ->F1 q SST
244 |     wrt bs = writeAs sk.mass (refineMassNr $ cast $ decimal bs) BElem
245 |
246 | elem : List (RExp True, Step q SSz SSTCK)
247 | elem = writeVals interpolate elem BChiral values
248 |
249 | chirality : List (RExp True, Step q SSz SSTCK)
250 | chirality = writeVals interpolate chirality BHCount values
251 |
252 | hc : List (RExp True, Step q SSz SSTCK)
253 | hc = step "H1" (wrt 1) :: vals encodeH (\v => \sk,t => wrt v t) values
254 |   where
255 |     wrt : HCount -> (sk : SSTCK q) => F1 q SST
256 |     wrt c = writeAs sk.hcount c BCharge
257 |
258 | chrg : List (RExp True, Step q SSz SSTCK)
259 | chrg =
260 |      step "+1" (wrt 1)
261 |   :: step "-1" (wrt (-1))
262 |   :: step "++" (wrt 2)
263 |   :: step "--" (wrt (-2))
264 |   :: vals encodeCharge (\v => \sk,t => wrt v t) values
265 |   where
266 |     wrt : Charge -> (sk : SSTCK q) => F1 q SST
267 |     wrt c = writeAs sk.charge c BEnd
268 |
269 | bend : List (RExp True, Step q SSz SSTCK)
270 | bend = [close ']' bracket]
271 |
272 | atom : List (RExp True, Step q SSz SSTCK)
273 | atom = opn' '[' BMass :: vals encodeAtom onAtom subset
274 |
275 | ring : List (RExp True, Step q SSz SSTCK)
276 | ring = vals interpolate onRing values
277 |
278 | bond : List (RExp True, Step q SSz SSTCK)
279 | bond = step '.' dot :: vals interpolate wrt values
280 |   where
281 |     %inline wrt   : SmilesBondOrder -> Step1 q SSz SSTCK
282 |     wrt b = \sk,t => writeAs sk.dob (Bnd b) Atom t
283 |
284 |     dot : (k : SSTCK q) => F1 q SST
285 |     dot = writeAs k.dob Dot Atom
286 |
287 | openClose : List (RExp True, Step q SSz SSTCK)
288 | openClose = [opn '(' op, close ')' cls]
289 |   where
290 |     op,cls : (k : SSTCK q) => F1 q SST
291 |     op = read1 k.st >>= \s => writeAs k.st ({stck $= doubleHead} s) NewBranch
292 |     cls = read1 k.st >>= \s => writeAs k.st ({stck $= drop} s) Closed
293 |
294 | space : List (RExp True, Step q SSz SSTCK)
295 | space = [bytes (plus $ oneof [' ', '\t']) (const end), step nl end]
296 |   where
297 |     nl : RExp True
298 |     nl = "\r\n" <|> '\n' <|> '\r'
299 |
300 |     end : (sk : SSTCK q) => F1 q SST
301 |     end = T1.do
302 |       Nothing <- endGraph sk | Just x => failWith x Err
303 |       pure Chain
304 |
305 | smilesTrans : Lex1 q SSz SSTCK
306 | smilesTrans =
307 |   lex1
308 |     [ E Chain     $ dfa (atom ++ space)
309 |     , E Atom      $ dfa atom
310 |     , E SRing     $ dfa (atom ++ ring ++ bond ++ openClose ++ space)
311 |     , E NewBranch $ dfa (atom ++ bond)
312 |     , E Closed    $ dfa (atom ++ bond ++ openClose ++ space)
313 |     , E BMass     $ dfa (mass :: Parser.elem)
314 |     , E BElem     $ dfa Parser.elem
315 |     , E BChiral   $ dfa (Parser.chirality ++ hc ++ chrg ++ bend)
316 |     , E BHCount   $ dfa (hc ++ chrg ++ bend)
317 |     , E BCharge   $ dfa (chrg ++ bend)
318 |     , E BEnd      $ dfa bend
319 |     ]
320 |
321 | smilesErr : Arr32 SSz (SSTCK q -> F1 q (BBErr SmilesErr))
322 | smilesErr =
323 |   arr32 SSz (unexpected [])
324 |     [ E BMass   $ unclosedIfNLorEOI "[" []
325 |     , E BElem   $ unclosedIfNLorEOI "[" []
326 |     , E BChiral $ unclosedIfNLorEOI "[" []
327 |     , E BHCount $ unclosedIfNLorEOI "[" []
328 |     , E BEnd    $ unclosedIfNLorEOI "[" []
329 |     ]
330 |
331 | smilesEOI :
332 |      SST
333 |   -> SSTCK q
334 |   -> F1 q (Either (BBErr SmilesErr) (List SmilesGraph))
335 | smilesEOI st sk =
336 |   case st == Chain || st == SRing || st == Closed of
337 |     False => arrFail SSTCK smilesErr st sk
338 |     True  => endGraph sk >>= \case
339 |       Just x  => pure (Left x)
340 |       Nothing => getList sk.stack_ >>= pure . Right
341 |
342 | public export
343 | smiles : P1 q (BBErr SmilesErr) (List SmilesGraph)
344 | smiles = P Chain init smilesTrans snocChunk smilesErr smilesEOI
345 |
346 | ||| Parses a list of smiles codes separated by whitespace
347 | export %inline
348 | parseSmiles : Origin -> String -> Either SmilesParseErr (List SmilesGraph)
349 | parseSmiles = parseString smiles
350 |
351 | test : String -> IO ()
352 | test s =
353 |   case parseSmiles Virtual s of
354 |     Right x => for_ x $ \(G _ g) => putStrLn (pretty interpolate interpolate g)
355 |     Left x  => putStrLn "\{x}"
356 |
357 | export
358 | readSmilesFrom :
359 |      {auto has : Has SmilesParseErr es}
360 |   -> Origin
361 |   -> String
362 |   -> ChemRes es SmilesGraph
363 | readSmilesFrom o s =
364 |   case parseSmiles o s of
365 |     Left  x   => Left (inject x)
366 |     Right []  => Right (G 0 empty)
367 |     Right [g] => Right g
368 |     Right _   =>
369 |       Left (inject $ toParseError o s (B (Custom ManyEntries) NoBounds))
370 |
371 | export %inline
372 | readSmiles : Has SmilesParseErr es => String -> ChemRes es SmilesGraph
373 | readSmiles = readSmilesFrom Virtual
374 |
375 | ||| This is a convenience alias `readSmiles`, which can be used
376 | ||| to quickly come up with fairly complex molecular graphs.
377 | |||
378 | ||| All errors are converted to pretty printed error messages.
379 | export %inline
380 | readSmiles' : String -> Either String SmilesGraph
381 | readSmiles' =
382 |   mapFst (interpolate . project1) . readSmiles {es = [SmilesParseErr]}
383 |