encoder.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
  5. */
  6. import { StringBuilder } from '../../../mol-util';
  7. import Writer from '../writer';
  8. import { Encoder, Category, Field } from '../cif/encoder';
  9. import { getCategoryInstanceData } from '../cif/encoder/util';
  10. import { ComponentBond } from '../../../mol-model-formats/structure/property/bonds/comp';
  11. // specification: http://c4.cabrillo.edu/404/ctfile.pdf
  12. export class SdfEncoder implements Encoder<string> {
  13. private builder: StringBuilder;
  14. private meta: StringBuilder;
  15. private encoded = false;
  16. private error = false;
  17. private componentData: ComponentBond;
  18. readonly isBinary = false;
  19. binaryEncodingProvider = void 0;
  20. setComponentBondData(componentData: ComponentBond) {
  21. this.componentData = componentData;
  22. }
  23. writeTo(stream: Writer) {
  24. const chunks = StringBuilder.getChunks(this.builder);
  25. for (let i = 0, _i = chunks.length; i < _i; i++) {
  26. stream.writeString(chunks[i]);
  27. }
  28. }
  29. getSize() {
  30. return StringBuilder.getSize(this.builder);
  31. }
  32. getData() {
  33. return StringBuilder.getString(this.builder);
  34. }
  35. startDataBlock() {
  36. }
  37. writeCategory<Ctx>(category: Category<Ctx>, context?: Ctx) {
  38. if (this.encoded) {
  39. throw new Error('The writer contents have already been encoded, no more writing.');
  40. }
  41. if (this.metaInformation && (category.name === 'model_server_result' || category.name === 'model_server_params' || category.name === 'model_server_stats')) {
  42. this.writeFullCategory(this.meta, category, context);
  43. return;
  44. }
  45. // if error: force writing of meta information
  46. if (category.name === 'model_server_error') {
  47. this.writeFullCategory(this.meta, category, context);
  48. this.error = true;
  49. return;
  50. }
  51. // only care about atom_site category when writing SDF
  52. if (category.name !== 'atom_site') {
  53. return;
  54. }
  55. // use separate builder because we still need to write Counts and Bonds line
  56. const ctab = StringBuilder.create();
  57. const bonds = StringBuilder.create();
  58. const charges = StringBuilder.create();
  59. // write Atom block and gather data for Bonds and Charges
  60. // 'Specifies the atomic symbol and any mass difference, charge, stereochemistry, and associated hydrogens for each atom.'
  61. const { instance, source } = getCategoryInstanceData(category, context);
  62. const sortedFields = this.getSortedFields(instance);
  63. const label_atom_id = this.getField(instance, 'label_atom_id');
  64. const label_comp_id = this.getField(instance, 'label_comp_id');
  65. // write header
  66. const name = label_comp_id.value(source[0].keys().move(), source[0].data, 0) as string;
  67. StringBuilder.write(this.builder, `${name}\nCreated by ${this.encoder}\n\n`);
  68. const bondMap = this.componentData.entries.get(name)!;
  69. let bondCount = 0;
  70. // traverse once to determine all actually present atoms
  71. const atoms = this.getAtoms(source, sortedFields, label_atom_id, ctab);
  72. for (let i1 = 0, il = atoms.length; i1 < il; i1++) {
  73. const name1 = atoms[i1];
  74. bondMap.map.get(name1)!.forEach((bv, bk) => {
  75. const i2 = atoms.indexOf(bk);
  76. const label2 = this.getLabel(bk);
  77. if (i1 < i2 && atoms.indexOf(bk) > -1 && !this.skipHydrogen(label2)) {
  78. const { order } = bv;
  79. StringBuilder.writeIntegerPadLeft(bonds, i1 + 1, 3);
  80. StringBuilder.writeIntegerPadLeft(bonds, i2 + 1, 3);
  81. StringBuilder.writeIntegerPadLeft(bonds, order, 3);
  82. StringBuilder.writeSafe(bonds, ' 0 0 0 0\n');
  83. // TODO 2nd value: Single bonds: 0 = not stereo, 1 = Up, 4 = Either, 6 = Down,
  84. // Double bonds: 0 = Use x-, y-, z-coords from atom block to determine cis or trans, 3 = Cis or trans (either) double bond
  85. bondCount++;
  86. }
  87. });
  88. }
  89. // write counts line
  90. // 'Important specifications here relate to the number of atoms, bonds, and atom lists, the chiral flag setting, and the Ctab version.'
  91. StringBuilder.writeIntegerPadLeft(this.builder, atoms.length, 3);
  92. StringBuilder.writeIntegerPadLeft(this.builder, bondCount, 3);
  93. StringBuilder.write(this.builder, ' 0 0 0 0 0 0 0999 V2000\n'); // TODO 2nd value: chiral flag: 0=not chiral, 1=chiral
  94. StringBuilder.writeSafe(this.builder, StringBuilder.getString(ctab));
  95. StringBuilder.writeSafe(this.builder, StringBuilder.getString(bonds));
  96. StringBuilder.writeSafe(this.builder, StringBuilder.getString(charges)); // TODO charges
  97. StringBuilder.writeSafe(this.builder, 'M END\n');
  98. }
  99. private getAtoms(source: any, fields: Field<any, any>[], label_atom_id: Field<any, any>, ctab: StringBuilder): string[] {
  100. const atoms = [];
  101. let index = 0;
  102. for (let _c = 0; _c < source.length; _c++) {
  103. const src = source[_c];
  104. const data = src.data;
  105. if (src.rowCount === 0) continue;
  106. const it = src.keys();
  107. while (it.hasNext) {
  108. const key = it.move();
  109. const lai = label_atom_id.value(key, data, index) as string;
  110. const label = this.getLabel(lai);
  111. if (this.skipHydrogen(label)) {
  112. index++;
  113. continue;
  114. }
  115. atoms.push(lai);
  116. for (let _f = 0, _fl = fields.length; _f < _fl; _f++) {
  117. const f: Field<any, any> = fields[_f]!;
  118. const v = f.value(key, data, index);
  119. this.writeValue(ctab, v, f.type);
  120. }
  121. StringBuilder.writeSafe(ctab, ' 0 0 0 0 0 0 0 0 0 0 0 0\n');
  122. index++;
  123. }
  124. }
  125. return atoms;
  126. }
  127. private skipHydrogen(label: string) {
  128. if (this.hydrogens) {
  129. return false;
  130. }
  131. return label.startsWith('H');
  132. }
  133. private getLabel(s: string) {
  134. return s.replace(/[^A-Z]+/g, '');
  135. }
  136. private writeFullCategory<Ctx>(sb: StringBuilder, category: Category<Ctx>, context?: Ctx) {
  137. const { instance, source } = getCategoryInstanceData(category, context);
  138. const fields = instance.fields;
  139. const src = source[0];
  140. const data = src.data;
  141. const it = src.keys();
  142. const key = it.move();
  143. for (let _f = 0; _f < fields.length; _f++) {
  144. const f = fields[_f]!;
  145. StringBuilder.writeSafe(sb, `> <${category.name}.${f.name}>\n`);
  146. const val = f.value(key, data, 0);
  147. StringBuilder.writeSafe(sb, val as string);
  148. StringBuilder.writeSafe(sb, '\n\n');
  149. }
  150. }
  151. private writeValue(sb: StringBuilder, val: string | number, t: Field.Type, floatPrecision: number = 4) {
  152. if (t === Field.Type.Str) {
  153. // type_symbol is the only string field - width 2, right-padded
  154. StringBuilder.whitespace1(sb);
  155. StringBuilder.writePadRight(sb, val as string, 2);
  156. } else if (t === Field.Type.Int) {
  157. StringBuilder.writeInteger(sb, val as number);
  158. } else {
  159. // coordinates have width 10 and are left-padded
  160. StringBuilder.writePadLeft(sb, (val as number).toFixed(floatPrecision), 10);
  161. }
  162. }
  163. private getSortedFields<Ctx>(instance: Category.Instance<Ctx>) {
  164. return ['Cartn_x', 'Cartn_y', 'Cartn_z', 'type_symbol']
  165. .map(n => this.getField(instance, n));
  166. }
  167. private getField<Ctx>(instance: Category.Instance<Ctx>, name: string) {
  168. return instance.fields.find(f => f.name === name)!;
  169. }
  170. encode() {
  171. // write meta-information, do so after ctab
  172. if (this.error || this.metaInformation) {
  173. StringBuilder.writeSafe(this.builder, StringBuilder.getString(this.meta));
  174. }
  175. // terminate file
  176. StringBuilder.writeSafe(this.builder, '$$$$\n');
  177. this.encoded = true;
  178. }
  179. setFilter(filter?: Category.Filter) {}
  180. setFormatter(formatter?: Category.Formatter) {}
  181. isCategoryIncluded(name: string) {
  182. return true;
  183. }
  184. constructor(readonly encoder: string, readonly metaInformation: boolean, readonly hydrogens: boolean) {
  185. this.builder = StringBuilder.create();
  186. this.meta = StringBuilder.create();
  187. }
  188. }