cif-dic.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /**
  2. * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { Database, Column, EnumCol, StrCol, IntCol, ListCol, FloatCol, CoordCol, MatrixCol, VectorCol } from './schema';
  7. import { parseImportGet } from './helper';
  8. import * as Data from '../../../mol-io/reader/cif/data-model';
  9. import { CifFrame } from '../../../mol-io/reader/cif/data-model';
  10. export function getFieldType(type: string, description: string, values?: string[], container?: string): Column {
  11. switch (type) {
  12. // mmCIF
  13. case 'code':
  14. case 'ucode':
  15. case 'line':
  16. case 'uline':
  17. case 'text':
  18. case 'char':
  19. case 'uchar3':
  20. case 'uchar1':
  21. case 'boolean':
  22. return values && values.length ? EnumCol(values, 'str', description) : StrCol(description);
  23. case 'aliasname':
  24. case 'name':
  25. case 'idname':
  26. case 'any':
  27. case 'atcode':
  28. case 'fax':
  29. case 'phone':
  30. case 'email':
  31. case 'code30':
  32. case 'seq-one-letter-code':
  33. case 'author':
  34. case 'orcid_id':
  35. case 'sequence_dep':
  36. case 'pdb_id':
  37. case 'emd_id':
  38. // todo, consider adding specialised fields
  39. case 'yyyy-mm-dd':
  40. case 'yyyy-mm-dd:hh:mm':
  41. case 'yyyy-mm-dd:hh:mm-flex':
  42. case 'int-range':
  43. case 'float-range':
  44. case 'binary':
  45. case 'operation_expression':
  46. case 'point_symmetry':
  47. case '4x3_matrix':
  48. case '3x4_matrices':
  49. case 'point_group':
  50. case 'point_group_helical':
  51. case 'symmetry_operation':
  52. case 'date_dep':
  53. case 'url':
  54. case 'symop':
  55. case 'exp_data_doi':
  56. case 'asym_id':
  57. return StrCol(description);
  58. case 'int':
  59. case 'non_negative_int':
  60. case 'positive_int':
  61. return values && values.length ? EnumCol(values, 'int', description) : IntCol(description);
  62. case 'float':
  63. return FloatCol(description);
  64. case 'ec-type':
  65. case 'ucode-alphanum-csv':
  66. case 'id_list':
  67. return ListCol('str', ',', description);
  68. case 'id_list_spc':
  69. return ListCol('str', ' ', description);
  70. // cif
  71. case 'Text':
  72. case 'Code':
  73. case 'Complex':
  74. case 'Symop':
  75. case 'List':
  76. case 'List(Real,Real)':
  77. case 'List(Real,Real,Real,Real)':
  78. case 'Date':
  79. case 'Datetime':
  80. case 'Tag':
  81. case 'Implied':
  82. return wrapContainer('str', ',', description, container);
  83. case 'Real':
  84. return wrapContainer('float', ',', description, container);
  85. case 'Integer':
  86. return wrapContainer('int', ',', description, container);
  87. }
  88. console.log(`unknown type '${type}'`);
  89. return StrCol(description);
  90. }
  91. function ColFromType(type: 'int' | 'str' | 'float' | 'coord', description: string): Column {
  92. switch (type) {
  93. case 'int': return IntCol(description);
  94. case 'str': return StrCol(description);
  95. case 'float': return FloatCol(description);
  96. case 'coord': return CoordCol(description);
  97. }
  98. }
  99. function wrapContainer(type: 'int' | 'str' | 'float' | 'coord', separator: string, description: string, container?: string) {
  100. return container && container === 'List' ? ListCol(type, separator, description) : ColFromType(type, description);
  101. }
  102. type FrameCategories = { [category: string]: Data.CifFrame }
  103. type FrameLinks = { [k: string]: string }
  104. interface FrameData {
  105. categories: FrameCategories
  106. links: FrameLinks
  107. }
  108. type Imports = Map<string, CifFrame[]>
  109. function getImportFrames(d: Data.CifFrame, imports: Imports) {
  110. const frames: Data.CifFrame[] = [];
  111. if (!('import' in d.categories)) return frames;
  112. const importGet = parseImportGet(d.categories['import'].getField('get')!.str(0));
  113. for (const g of importGet) {
  114. const { file, save } = g;
  115. if (!file || !save) {
  116. console.warn(`missing 'save' or 'file' for import in '${d.header}'`);
  117. continue;
  118. }
  119. const importFrames = imports.get(file);
  120. if (!importFrames) {
  121. console.warn(`missing '${file}' entry in imports`);
  122. continue;
  123. }
  124. const importSave = importFrames.find(id => id.header.toLowerCase() === save.toLowerCase());
  125. if (!importSave) {
  126. console.warn(`missing '${save}' save frame in '${file}'`);
  127. continue;
  128. }
  129. frames.push(importSave);
  130. }
  131. return frames;
  132. }
  133. /** get field from given or linked category */
  134. function getField(category: string, field: string, d: Data.CifFrame, imports: Imports, ctx: FrameData): Data.CifField|undefined {
  135. const { categories, links } = ctx;
  136. const cat = d.categories[category];
  137. if (cat) {
  138. return cat.getField(field);
  139. } else if (d.header in links) {
  140. const linkName = links[d.header];
  141. if (linkName in categories) {
  142. return getField(category, field, categories[linkName], imports, ctx);
  143. } else {
  144. // console.log(`link '${linkName}' not found`)
  145. }
  146. } else {
  147. const importFrames = getImportFrames(d, imports);
  148. for (const idf of importFrames) {
  149. return getField(category, field, idf, imports, ctx);
  150. }
  151. }
  152. }
  153. function getEnums(d: Data.CifFrame, imports: Imports, ctx: FrameData) {
  154. const value = getField('item_enumeration', 'value', d, imports, ctx);
  155. const enums: string[] = [];
  156. if (value) {
  157. for (let i = 0; i < value.rowCount; ++i) {
  158. enums.push(value.str(i));
  159. // console.log(value.str(i))
  160. }
  161. return enums;
  162. } else {
  163. // console.log(`item_enumeration.value not found for '${d.header}'`)
  164. }
  165. }
  166. function getContainer(d: Data.CifFrame, imports: Imports, ctx: FrameData) {
  167. const value = getField('type', 'container', d, imports, ctx);
  168. return value ? value.str(0) : undefined;
  169. }
  170. function getCode(d: Data.CifFrame, imports: Imports, ctx: FrameData): [string, string[] | undefined, string | undefined ] | undefined {
  171. const code = getField('item_type', 'code', d, imports, ctx) || getField('type', 'contents', d, imports, ctx);
  172. if (code) {
  173. return [ code.str(0), getEnums(d, imports, ctx), getContainer(d, imports, ctx) ];
  174. } else {
  175. console.log(`item_type.code or type.contents not found for '${d.header}'`);
  176. }
  177. }
  178. function getSubCategory(d: Data.CifFrame, imports: Imports, ctx: FrameData): string | undefined {
  179. const value = getField('item_sub_category', 'id', d, imports, ctx);
  180. if (value) {
  181. return value.str(0);
  182. }
  183. }
  184. function getDescription(d: Data.CifFrame, imports: Imports, ctx: FrameData): string | undefined {
  185. const value = getField('item_description', 'description', d, imports, ctx) || getField('description', 'text', d, imports, ctx);
  186. if (value) {
  187. // trim (after newlines) and remove references to square brackets
  188. return value.str(0).trim()
  189. .replace(/(\r\n|\r|\n)([ \t]+)/g, '\n')
  190. .replace(/(\[[1-3]\])+ element/, 'elements')
  191. .replace(/(\[[1-3]\])+/, '');
  192. }
  193. }
  194. function getAliases(d: Data.CifFrame, imports: Imports, ctx: FrameData): string[] | undefined {
  195. const value = getField('item_aliases', 'alias_name', d, imports, ctx) || getField('alias', 'definition_id', d, imports, ctx);
  196. return value ? value.toStringArray().map(v => v.substr(1)) : undefined;
  197. }
  198. const reMatrixField = /\[[1-3]\]\[[1-3]\]/;
  199. const reVectorField = /\[[1-3]\]/;
  200. const FORCE_INT_FIELDS = [
  201. '_atom_site.id',
  202. '_atom_site.auth_seq_id',
  203. '_atom_site_anisotrop.id',
  204. '_pdbx_struct_mod_residue.auth_seq_id',
  205. '_struct_conf.beg_auth_seq_id',
  206. '_struct_conf.end_auth_seq_id',
  207. '_struct_conn.ptnr1_auth_seq_id',
  208. '_struct_conn.ptnr2_auth_seq_id',
  209. '_struct_sheet_range.beg_auth_seq_id',
  210. '_struct_sheet_range.end_auth_seq_id',
  211. ];
  212. const FORCE_MATRIX_FIELDS_MAP: { [k: string]: string } = {
  213. 'atom_site_aniso.U_11': 'U',
  214. 'atom_site_aniso.U_22': 'U',
  215. 'atom_site_aniso.U_33': 'U',
  216. 'atom_site_aniso.U_23': 'U',
  217. 'atom_site_aniso.U_13': 'U',
  218. 'atom_site_aniso.U_12': 'U',
  219. 'atom_site_aniso.U_11_su': 'U_su',
  220. 'atom_site_aniso.U_22_su': 'U_su',
  221. 'atom_site_aniso.U_33_su': 'U_su',
  222. 'atom_site_aniso.U_23_su': 'U_su',
  223. 'atom_site_aniso.U_13_su': 'U_su',
  224. 'atom_site_aniso.U_12_su': 'U_su',
  225. };
  226. const FORCE_MATRIX_FIELDS = Object.keys(FORCE_MATRIX_FIELDS_MAP);
  227. const EXTRA_ALIASES: Database['aliases'] = {
  228. 'atom_site_aniso.U': [
  229. 'atom_site_anisotrop_U'
  230. ],
  231. 'atom_site_aniso.U_su': [
  232. 'atom_site_aniso_U_esd',
  233. 'atom_site_anisotrop_U_esd',
  234. ],
  235. };
  236. const COMMA_SEPARATED_LIST_FIELDS = [
  237. '_atom_site.pdbx_struct_group_id',
  238. '_chem_comp.mon_nstd_parent_comp_id',
  239. '_diffrn_radiation.pdbx_wavelength_list',
  240. '_diffrn_source.pdbx_wavelength_list',
  241. '_em_diffraction.tilt_angle_list', // 20,40,50,55
  242. '_em_entity_assembly.entity_id_list',
  243. '_entity.pdbx_description', // Endolysin,Beta-2 adrenergic receptor
  244. '_entity.pdbx_ec',
  245. '_entity_poly.pdbx_strand_id', // A,B
  246. '_entity_src_gen.pdbx_gene_src_gene', // ADRB2, ADRB2R, B2AR
  247. '_pdbx_depui_entry_details.experimental_methods',
  248. '_pdbx_depui_entry_details.requested_accession_types',
  249. '_pdbx_soln_scatter_model.software_list', // INSIGHT II, HOMOLOGY, DISCOVERY, BIOPOLYMER, DELPHI
  250. '_pdbx_soln_scatter_model.software_author_list', // MSI
  251. '_pdbx_soln_scatter_model.entry_fitting_list', // Odd example: 'PDB CODE 1HFI, 1HCC, 1HFH, 1VCC'
  252. '_pdbx_struct_assembly_gen.entity_inst_id',
  253. '_pdbx_struct_assembly_gen.asym_id_list',
  254. '_pdbx_struct_assembly_gen.auth_asym_id_list',
  255. '_pdbx_struct_assembly_gen_depositor_info.asym_id_list',
  256. '_pdbx_struct_assembly_gen_depositor_info.chain_id_list',
  257. '_pdbx_struct_group_list.group_enumeration_type',
  258. '_reflns.pdbx_diffrn_id',
  259. '_refine.pdbx_diffrn_id',
  260. '_reflns_shell.pdbx_diffrn_id',
  261. '_struct_keywords.text',
  262. ];
  263. const SPACE_SEPARATED_LIST_FIELDS = [
  264. '_chem_comp.pdbx_subcomponent_list', // TSM DPH HIS CHF EMR
  265. '_pdbx_soln_scatter.data_reduction_software_list', // OTOKO
  266. '_pdbx_soln_scatter.data_analysis_software_list', // SCTPL5 GNOM
  267. ];
  268. const SEMICOLON_SEPARATED_LIST_FIELDS = [
  269. '_chem_comp.pdbx_synonyms' // GLYCERIN; PROPANE-1,2,3-TRIOL
  270. ];
  271. /**
  272. * Useful when a dictionary extension will add enum values to an existing dictionary.
  273. * By adding them here, the dictionary extension can be tested before the added enum
  274. * values are available in the existing dictionary.
  275. */
  276. const EXTRA_ENUM_VALUES: { [k: string]: string[] } = {
  277. };
  278. export function generateSchema(frames: CifFrame[], imports: Imports = new Map()): Database {
  279. const tables: Database['tables'] = {};
  280. const aliases: Database['aliases'] = { ...EXTRA_ALIASES };
  281. const categories: FrameCategories = {};
  282. const links: FrameLinks = {};
  283. const ctx = { categories, links };
  284. // get category metadata
  285. frames.forEach(d => {
  286. // category definitions in mmCIF start with '_' and don't include a '.'
  287. // category definitions in cifCore don't include a '.'
  288. if (d.header[0] === '_' || d.header.includes('.')) return;
  289. const categoryName = d.header.toLowerCase();
  290. // console.log(d.header, d.categoryNames, d.categories)
  291. let descriptionField: Data.CifField | undefined;
  292. const categoryKeyNames = new Set<string>();
  293. if ('category' in d.categories && 'category_key' in d.categories) {
  294. const category = d.categories['category'];
  295. const categoryKey = d.categories['category_key'];
  296. if (categoryKey) {
  297. const categoryKey_names = categoryKey.getField('name');
  298. if (categoryKey_names) {
  299. for (let i = 0, il = categoryKey_names.rowCount; i < il; ++i) {
  300. categoryKeyNames.add(categoryKey_names.str(i));
  301. }
  302. }
  303. }
  304. descriptionField = category.getField('description');
  305. if (categoryKeyNames.size === 0) {
  306. console.log(`no key given for category '${categoryName}'`);
  307. }
  308. }
  309. if ('description' in d.categories) {
  310. descriptionField = d.categories['description'].getField('text');
  311. }
  312. let description = '';
  313. if (descriptionField) {
  314. description = descriptionField.str(0).trim()
  315. .replace(/(\r\n|\r|\n)([ \t]+)/g, '\n'); // remove padding after newlines
  316. } else {
  317. console.log(`no description given for category '${categoryName}'`);
  318. }
  319. tables[categoryName] = { description, key: categoryKeyNames, columns: {} };
  320. // console.log('++++++++++++++++++++++++++++++++++++++++++')
  321. // console.log('name', categoryName)
  322. // console.log('desc', description)
  323. // console.log('key', categoryKeyNames)
  324. });
  325. // build list of links between categories
  326. frames.forEach(d => {
  327. if (d.header[0] !== '_' && !d.header.includes('.')) return;
  328. categories[d.header] = d;
  329. const item_linked = d.categories['item_linked'];
  330. if (item_linked) {
  331. const child_name = item_linked.getField('child_name');
  332. const parent_name = item_linked.getField('parent_name');
  333. if (child_name && parent_name) {
  334. for (let i = 0; i < item_linked.rowCount; ++i) {
  335. const childName = child_name.str(i);
  336. const parentName = parent_name.str(i);
  337. if (childName in links && links[childName] !== parentName) {
  338. console.log(`${childName} linked to ${links[childName]}, ignoring link to ${parentName}`);
  339. }
  340. links[childName] = parentName;
  341. }
  342. }
  343. }
  344. });
  345. // get field data
  346. Object.keys(categories).forEach(fullName => {
  347. const d = categories[fullName];
  348. if (!d) {
  349. console.log(`'${fullName}' not found, moving on`);
  350. return;
  351. }
  352. const categoryName = d.header.substring(d.header[0] === '_' ? 1 : 0, d.header.indexOf('.'));
  353. const itemName = d.header.substring(d.header.indexOf('.') + 1);
  354. let fields: { [k: string]: Column };
  355. if (categoryName in tables) {
  356. fields = tables[categoryName].columns;
  357. tables[categoryName].key.add(itemName);
  358. } else if (categoryName.toLowerCase() in tables) {
  359. // take case from category name in 'field' data as it is better if data is from cif dictionaries
  360. tables[categoryName] = tables[categoryName.toLowerCase()];
  361. fields = tables[categoryName].columns;
  362. } else {
  363. console.log(`category '${categoryName}' has no metadata`);
  364. fields = {};
  365. tables[categoryName] = {
  366. description: '',
  367. key: new Set(),
  368. columns: fields
  369. };
  370. }
  371. const itemAliases = getAliases(d, imports, ctx);
  372. if (itemAliases) aliases[`${categoryName}.${itemName}`] = itemAliases;
  373. const description = getDescription(d, imports, ctx) || '';
  374. // need to use regex to check for matrix or vector items
  375. // as sub_category assignment is missing for some entries
  376. const subCategory = getSubCategory(d, imports, ctx);
  377. if (subCategory === 'cartesian_coordinate' || subCategory === 'fractional_coordinate') {
  378. fields[itemName] = CoordCol(description);
  379. } else if (FORCE_INT_FIELDS.includes(d.header)) {
  380. fields[itemName] = IntCol(description);
  381. console.log(`forcing int: ${d.header}`);
  382. } else if (FORCE_MATRIX_FIELDS.includes(d.header)) {
  383. fields[itemName] = FloatCol(description);
  384. fields[FORCE_MATRIX_FIELDS_MAP[d.header]] = MatrixCol(3, 3, description);
  385. console.log(`forcing matrix: ${d.header}`);
  386. } else if (subCategory === 'matrix') {
  387. fields[itemName.replace(reMatrixField, '')] = MatrixCol(3, 3, description);
  388. } else if (subCategory === 'vector') {
  389. fields[itemName.replace(reVectorField, '')] = VectorCol(3, description);
  390. } else {
  391. if (itemName.match(reMatrixField)) {
  392. fields[itemName.replace(reMatrixField, '')] = MatrixCol(3, 3, description);
  393. console.log(`${d.header} should have 'matrix' _item_sub_category.id`);
  394. } else if (itemName.match(reVectorField)) {
  395. fields[itemName.replace(reVectorField, '')] = VectorCol(3, description);
  396. console.log(`${d.header} should have 'vector' _item_sub_category.id`);
  397. } else {
  398. const code = getCode(d, imports, ctx);
  399. if (code) {
  400. let fieldType = getFieldType(code[0], description, code[1], code[2]);
  401. if (fieldType.type === 'str') {
  402. if (COMMA_SEPARATED_LIST_FIELDS.includes(d.header)) {
  403. fieldType = ListCol('str', ',', description);
  404. console.log(`forcing comma separated: ${d.header}`);
  405. } else if (SPACE_SEPARATED_LIST_FIELDS.includes(d.header)) {
  406. fieldType = ListCol('str', ' ', description);
  407. console.log(`forcing space separated: ${d.header}`);
  408. } else if (SEMICOLON_SEPARATED_LIST_FIELDS.includes(d.header)) {
  409. fieldType = ListCol('str', ';', description);
  410. console.log(`forcing space separated: ${d.header}`);
  411. }
  412. }
  413. if (d.header in EXTRA_ENUM_VALUES) {
  414. if (fieldType.type === 'enum') {
  415. fieldType.values.push(...EXTRA_ENUM_VALUES[d.header]);
  416. } else {
  417. console.warn(`expected enum: ${d.header}`);
  418. }
  419. }
  420. fields[itemName] = fieldType;
  421. } else {
  422. fields[itemName] = StrCol(description);
  423. // console.log(`could not determine code for '${d.header}'`)
  424. }
  425. }
  426. }
  427. });
  428. return { tables, aliases };
  429. }