converter.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import Iterator from 'mol-data/iterator'
  7. import CIF, { Category } from 'mol-io/reader/cif'
  8. import * as Encoder from 'mol-io/writer/cif'
  9. import * as fs from 'fs'
  10. import classify from './field-classifier'
  11. async function getCIF(path: string) {
  12. const str = fs.readFileSync(path, 'utf8');
  13. const parsed = await CIF.parseText(str)();
  14. if (parsed.isError) {
  15. throw new Error(parsed.toString());
  16. }
  17. return parsed.result;
  18. }
  19. function createDefinition(cat: Category): Encoder.CategoryDefinition {
  20. return {
  21. name: cat.name,
  22. fields: cat.fieldNames.map(n => classify(n, cat.getField(n)!))
  23. }
  24. }
  25. function getCategoryInstanceProvider(cat: Category): Encoder.CategoryProvider {
  26. return function (ctx: any) {
  27. return {
  28. data: cat,
  29. definition: createDefinition(cat),
  30. keys: () => Iterator.Range(0, cat.rowCount - 1),
  31. rowCount: cat.rowCount
  32. };
  33. }
  34. }
  35. export default async function convert(path: string, asText = false) {
  36. const cif = await getCIF(path);
  37. const encoder = Encoder.create({ binary: !asText, encoderName: 'mol* cif2bcif' });
  38. for (const b of cif.blocks) {
  39. encoder.startDataBlock(b.header);
  40. for (const c of b.categoryNames) {
  41. encoder.writeCategory(getCategoryInstanceProvider(b.categories[c]));
  42. }
  43. }
  44. return encoder.getData();
  45. }