index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #!/usr/bin/env node
  2. /**
  3. * Copyright (c) 2017-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  4. *
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import * as argparse from 'argparse';
  8. import * as fs from 'fs';
  9. import * as path from 'path';
  10. import fetch from 'node-fetch';
  11. import { parseCsv } from '../../mol-io/reader/csv/parser';
  12. import { CifFrame, CifBlock } from '../../mol-io/reader/cif';
  13. import { parseCifText } from '../../mol-io/reader/cif/text/parser';
  14. import { generateSchema } from './util/cif-dic';
  15. import { generate } from './util/generate';
  16. import { Filter, Database } from './util/schema';
  17. import { parseImportGet } from './util/helper';
  18. function getDicVersion(block: CifBlock) {
  19. return block.categories.dictionary.getField('version')!.str(0);
  20. }
  21. function getDicNamespace(block: CifBlock) {
  22. return block.categories.dictionary.getField('namespace')!.str(0);
  23. }
  24. async function runGenerateSchemaMmcif(name: string, fieldNamesPath: string, typescript = false, out: string, moldbImportPath: string, addAliases: boolean) {
  25. await ensureMmcifDicAvailable();
  26. const mmcifDic = await parseCifText(fs.readFileSync(MMCIF_DIC_PATH, 'utf8')).run();
  27. if (mmcifDic.isError) throw mmcifDic;
  28. await ensureIhmDicAvailable();
  29. const ihmDic = await parseCifText(fs.readFileSync(IHM_DIC_PATH, 'utf8')).run();
  30. if (ihmDic.isError) throw ihmDic;
  31. await ensureMaDicAvailable();
  32. const maDic = await parseCifText(fs.readFileSync(MA_DIC_PATH, 'utf8')).run();
  33. if (maDic.isError) throw maDic;
  34. const mmcifDicVersion = getDicVersion(mmcifDic.result.blocks[0]);
  35. const ihmDicVersion = getDicVersion(ihmDic.result.blocks[0]);
  36. const maDicVersion = getDicVersion(maDic.result.blocks[0]);
  37. const version = `Dictionary versions: mmCIF ${mmcifDicVersion}, IHM ${ihmDicVersion}, MA ${maDicVersion}.`;
  38. const frames: CifFrame[] = [...mmcifDic.result.blocks[0].saveFrames, ...ihmDic.result.blocks[0].saveFrames, ...maDic.result.blocks[0].saveFrames];
  39. const schema = generateSchema(frames);
  40. await runGenerateSchema(name, version, schema, fieldNamesPath, typescript, out, moldbImportPath, addAliases);
  41. }
  42. async function runGenerateSchemaCifCore(name: string, fieldNamesPath: string, typescript = false, out: string, moldbImportPath: string, addAliases: boolean) {
  43. await ensureCifCoreDicAvailable();
  44. const cifCoreDic = await parseCifText(fs.readFileSync(CIF_CORE_DIC_PATH, 'utf8')).run();
  45. if (cifCoreDic.isError) throw cifCoreDic;
  46. const cifCoreDicVersion = getDicVersion(cifCoreDic.result.blocks[0]);
  47. const version = `Dictionary versions: CifCore ${cifCoreDicVersion}.`;
  48. const frames: CifFrame[] = [...cifCoreDic.result.blocks[0].saveFrames];
  49. const imports = await resolveImports(frames, DIC_DIR);
  50. const schema = generateSchema(frames, imports);
  51. await runGenerateSchema(name, version, schema, fieldNamesPath, typescript, out, moldbImportPath, addAliases);
  52. }
  53. async function resolveImports(frames: CifFrame[], baseDir: string): Promise<Map<string, CifFrame[]>> {
  54. const imports = new Map<string, CifFrame[]>();
  55. for (const d of frames) {
  56. if ('import' in d.categories) {
  57. const importGet = parseImportGet(d.categories['import'].getField('get')!.str(0));
  58. for (const g of importGet) {
  59. const { file } = g;
  60. if (!file) continue;
  61. if (imports.has(file)) continue;
  62. const dic = await parseCifText(fs.readFileSync(path.join(baseDir, file), 'utf8')).run();
  63. if (dic.isError) throw dic;
  64. imports.set(file, [...dic.result.blocks[0].saveFrames]);
  65. }
  66. }
  67. }
  68. return imports;
  69. }
  70. async function runGenerateSchemaDic(name: string, dicPath: string, fieldNamesPath: string, typescript = false, out: string, moldbImportPath: string, addAliases: boolean) {
  71. const dic = await parseCifText(fs.readFileSync(dicPath, 'utf8')).run();
  72. if (dic.isError) throw dic;
  73. const dicVersion = getDicVersion(dic.result.blocks[0]);
  74. const dicName = getDicNamespace(dic.result.blocks[0]);
  75. const version = `Dictionary versions: ${dicName} ${dicVersion}.`;
  76. const frames: CifFrame[] = [...dic.result.blocks[0].saveFrames];
  77. const imports = await resolveImports(frames, path.dirname(dicPath));
  78. const schema = generateSchema(frames, imports);
  79. await runGenerateSchema(name, version, schema, fieldNamesPath, typescript, out, moldbImportPath, addAliases);
  80. }
  81. async function runGenerateSchema(name: string, version: string, schema: Database, fieldNamesPath: string, typescript = false, out: string, moldbImportPath: string, addAliases: boolean) {
  82. const filter = fieldNamesPath ? await getFieldNamesFilter(fieldNamesPath) : undefined;
  83. const output = typescript ? generate(name, version, schema, filter, moldbImportPath, addAliases) : JSON.stringify(schema, undefined, 4);
  84. if (out) {
  85. fs.writeFileSync(out, output);
  86. } else {
  87. console.log(output);
  88. }
  89. }
  90. async function getFieldNamesFilter(fieldNamesPath: string): Promise<Filter> {
  91. const fieldNamesStr = fs.readFileSync(fieldNamesPath, 'utf8');
  92. const parsed = await parseCsv(fieldNamesStr, { noColumnNames: true }).run();
  93. if (parsed.isError) throw parser.error;
  94. const csvFile = parsed.result;
  95. const fieldNamesCol = csvFile.table.getColumn('0');
  96. if (!fieldNamesCol) throw new Error('error getting fields columns');
  97. const fieldNames = fieldNamesCol.toStringArray();
  98. const filter: Filter = {};
  99. fieldNames.forEach((name, i) => {
  100. const [category, field] = name.split('.');
  101. // console.log(category, field)
  102. if (!filter[category]) filter[category] = {};
  103. filter[category][field] = true;
  104. });
  105. return filter;
  106. }
  107. async function ensureMmcifDicAvailable() { await ensureDicAvailable(MMCIF_DIC_PATH, MMCIF_DIC_URL); }
  108. async function ensureIhmDicAvailable() { await ensureDicAvailable(IHM_DIC_PATH, IHM_DIC_URL); }
  109. async function ensureMaDicAvailable() { await ensureDicAvailable(MA_DIC_PATH, MA_DIC_URL); }
  110. async function ensureCifCoreDicAvailable() {
  111. await ensureDicAvailable(CIF_CORE_DIC_PATH, CIF_CORE_DIC_URL);
  112. await ensureDicAvailable(CIF_CORE_ENUM_PATH, CIF_CORE_ENUM_URL);
  113. await ensureDicAvailable(CIF_CORE_ATTR_PATH, CIF_CORE_ATTR_URL);
  114. }
  115. async function ensureDicAvailable(dicPath: string, dicUrl: string) {
  116. if (FORCE_DIC_DOWNLOAD || !fs.existsSync(dicPath)) {
  117. const name = dicUrl.substr(dicUrl.lastIndexOf('/') + 1);
  118. console.log(`downloading ${name}...`);
  119. const data = await fetch(dicUrl);
  120. if (!fs.existsSync(DIC_DIR)) {
  121. fs.mkdirSync(DIC_DIR);
  122. }
  123. fs.writeFileSync(dicPath, await data.text());
  124. console.log(`done downloading ${name}`);
  125. }
  126. }
  127. const DIC_DIR = path.resolve(__dirname, '../../../../build/dics/');
  128. const MMCIF_DIC_PATH = `${DIC_DIR}/mmcif_pdbx_v50.dic`;
  129. const MMCIF_DIC_URL = 'http://mmcif.wwpdb.org/dictionaries/ascii/mmcif_pdbx_v50.dic';
  130. const IHM_DIC_PATH = `${DIC_DIR}/mmcif_ihm_ext.dic`;
  131. const IHM_DIC_URL = 'https://raw.githubusercontent.com/ihmwg/IHMCIF/master/dist/mmcif_ihm_ext.dic';
  132. const MA_DIC_PATH = `${DIC_DIR}/ma-extension.dic`;
  133. const MA_DIC_URL = 'https://raw.githubusercontent.com/ihmwg/ModelCIF/master/dist/mmcif_ma.dic';
  134. const CIF_CORE_DIC_PATH = `${DIC_DIR}/cif_core.dic`;
  135. const CIF_CORE_DIC_URL = 'https://raw.githubusercontent.com/COMCIFS/cif_core/master/cif_core.dic';
  136. const CIF_CORE_ENUM_PATH = `${DIC_DIR}/templ_enum.cif`;
  137. const CIF_CORE_ENUM_URL = 'https://raw.githubusercontent.com/COMCIFS/cif_core/master/templ_enum.cif';
  138. const CIF_CORE_ATTR_PATH = `${DIC_DIR}/templ_attr.cif`;
  139. const CIF_CORE_ATTR_URL = 'https://raw.githubusercontent.com/COMCIFS/cif_core/master/templ_attr.cif';
  140. const parser = new argparse.ArgumentParser({
  141. add_help: true,
  142. description: 'Create schema from mmcif dictionary (v50 plus IHM and entity_branch extensions, downloaded from wwPDB)'
  143. });
  144. parser.add_argument('--preset', '-p', {
  145. default: '',
  146. choices: ['', 'mmCIF', 'CCD', 'BIRD', 'CifCore'],
  147. help: 'Preset name'
  148. });
  149. parser.add_argument('--name', '-n', {
  150. default: '',
  151. help: 'Schema name'
  152. });
  153. parser.add_argument('--out', '-o', {
  154. help: 'Generated schema output path, if not given printed to stdout'
  155. });
  156. parser.add_argument('--targetFormat', '-tf', {
  157. default: 'typescript-molstar',
  158. choices: ['typescript-molstar', 'json-internal'],
  159. help: 'Target format'
  160. });
  161. parser.add_argument('--dicPath', '-d', {
  162. default: '',
  163. help: 'Path to dictionary'
  164. });
  165. parser.add_argument('--fieldNamesPath', '-fn', {
  166. default: '',
  167. help: 'Field names to include'
  168. });
  169. parser.add_argument('--forceDicDownload', '-f', {
  170. action: 'store_true',
  171. help: 'Force download of dictionaries'
  172. });
  173. parser.add_argument('--moldataImportPath', '-mip', {
  174. default: 'molstar/lib/mol-data',
  175. help: 'mol-data import path (for typescript target only)'
  176. });
  177. parser.add_argument('--addAliases', '-aa', {
  178. action: 'store_true',
  179. help: 'Add field name/path aliases'
  180. });
  181. interface Args {
  182. name: string
  183. preset: '' | 'mmCIF' | 'CCD' | 'BIRD' | 'CifCore'
  184. forceDicDownload: boolean
  185. dic: '' | 'mmCIF' | 'CifCore'
  186. dicPath: string,
  187. fieldNamesPath: string
  188. targetFormat: 'typescript-molstar' | 'json-internal'
  189. out: string,
  190. moldataImportPath: string
  191. addAliases: boolean
  192. }
  193. const args: Args = parser.parse_args();
  194. const FORCE_DIC_DOWNLOAD = args.forceDicDownload;
  195. switch (args.preset) {
  196. case 'mmCIF':
  197. args.name = 'mmCIF';
  198. args.dic = 'mmCIF';
  199. args.fieldNamesPath = path.resolve(__dirname, '../../../../data/cif-field-names/mmcif-field-names.csv');
  200. break;
  201. case 'CCD':
  202. args.name = 'CCD';
  203. args.dic = 'mmCIF';
  204. args.fieldNamesPath = path.resolve(__dirname, '../../../../data/cif-field-names/ccd-field-names.csv');
  205. break;
  206. case 'BIRD':
  207. args.name = 'BIRD';
  208. args.dic = 'mmCIF';
  209. args.fieldNamesPath = path.resolve(__dirname, '../../../../data/cif-field-names/bird-field-names.csv');
  210. break;
  211. case 'CifCore':
  212. args.name = 'CifCore';
  213. args.dic = 'CifCore';
  214. args.fieldNamesPath = path.resolve(__dirname, '../../../../data/cif-field-names/cif-core-field-names.csv');
  215. break;
  216. }
  217. if (args.name) {
  218. const typescript = args.targetFormat === 'typescript-molstar';
  219. if (args.dicPath) {
  220. runGenerateSchemaDic(args.name, args.dicPath, args.fieldNamesPath, typescript, args.out, args.moldataImportPath, args.addAliases).catch(e => {
  221. console.error(e);
  222. });
  223. } else if (args.dic === 'mmCIF') {
  224. runGenerateSchemaMmcif(args.name, args.fieldNamesPath, typescript, args.out, args.moldataImportPath, args.addAliases).catch(e => {
  225. console.error(e);
  226. });
  227. } else if (args.dic === 'CifCore') {
  228. runGenerateSchemaCifCore(args.name, args.fieldNamesPath, typescript, args.out, args.moldataImportPath, args.addAliases).catch(e => {
  229. console.error(e);
  230. });
  231. }
  232. }