encoder.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /**
  2. * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import Iterator from 'mol-data/iterator'
  8. import { Column, Table, Database, DatabaseCollection } from 'mol-data/db'
  9. import { Tensor } from 'mol-math/linear-algebra'
  10. import Encoder from '../encoder'
  11. import { ArrayEncoder, ArrayEncoding } from '../../common/binary-cif';
  12. // TODO: support for "coordinate fields", make "coordinate precision" a parameter of the encoder
  13. // TODO: automatically detect "precision" of floating point arrays.
  14. // TODO: automatically detect "best encoding" for integer arrays. This could be used for "fixed-point" as well.
  15. // TODO: add "repeat encoding"? [[1, 2], [1, 2], [1, 2]] --- Repeat ---> [[1, 2], 3]
  16. // TODO: Add "higher level fields"? (i.e. generalization of repeat)
  17. // TODO: align "data blocks" to 8 byte offsets for fast typed array windows? (prolly needs some testing if this is actually the case too)
  18. export interface CIFField<Key = any, Data = any> {
  19. name: string,
  20. type: CIFField.Type,
  21. valueKind?: (key: Key, data: Data) => Column.ValueKind,
  22. defaultFormat?: CIFField.Format,
  23. value(key: Key, data: Data): string | number
  24. }
  25. export namespace CIFField {
  26. export const enum Type { Str, Int, Float }
  27. export interface Format {
  28. digitCount?: number,
  29. encoder?: ArrayEncoder,
  30. typedArray?: ArrayEncoding.TypedArrayCtor
  31. }
  32. export function getDigitCount(field: CIFField) {
  33. if (field.defaultFormat && typeof field.defaultFormat.digitCount !== 'undefined') return field.defaultFormat.digitCount;
  34. return 6;
  35. }
  36. export function str<K, D = any>(name: string, value: (k: K, d: D) => string, params?: { valueKind?: (k: K, d: D) => Column.ValueKind, encoder?: ArrayEncoder }): CIFField<K, D> {
  37. return { name, type: Type.Str, value, valueKind: params && params.valueKind, defaultFormat: params && params.encoder ? { encoder: params.encoder } : void 0 };
  38. }
  39. export function int<K, D = any>(name: string, value: (k: K, d: D) => number, params?: { valueKind?: (k: K, d: D) => Column.ValueKind, encoder?: ArrayEncoder, typedArray?: ArrayEncoding.TypedArrayCtor }): CIFField<K, D> {
  40. return {
  41. name,
  42. type: Type.Int,
  43. value,
  44. valueKind: params && params.valueKind,
  45. defaultFormat: params ? { encoder: params.encoder, typedArray: params.typedArray } : void 0 };
  46. }
  47. export function float<K, D = any>(name: string, value: (k: K, d: D) => number, params?: { valueKind?: (k: K, d: D) => Column.ValueKind, encoder?: ArrayEncoder, typedArray?: ArrayEncoding.TypedArrayCtor, digitCount?: number }): CIFField<K, D> {
  48. return {
  49. name,
  50. type: Type.Float,
  51. value,
  52. valueKind: params && params.valueKind,
  53. defaultFormat: params ? { encoder: params.encoder, typedArray: params.typedArray, digitCount: typeof params.digitCount !== 'undefined' ? params.digitCount : void 0 } : void 0
  54. };
  55. }
  56. }
  57. export interface CIFCategory<Key = any, Data = any> {
  58. name: string,
  59. fields: CIFField<Key, Data>[],
  60. data?: Data,
  61. rowCount: number,
  62. keys?: () => Iterator<Key>
  63. }
  64. export namespace CIFCategory {
  65. export interface Provider<Ctx = any> {
  66. (ctx: Ctx): CIFCategory
  67. }
  68. export function ofTable(name: string, table: Table<Table.Schema>): CIFCategory<number, Table<Table.Schema>> {
  69. return { name, fields: cifFieldsFromTableSchema(table._schema), data: table, rowCount: table._rowCount };
  70. }
  71. }
  72. export interface CIFEncoder<T = string | Uint8Array> extends Encoder {
  73. // setFormatter(): void,
  74. startDataBlock(header: string): void,
  75. writeCategory<Ctx>(category: CIFCategory.Provider<Ctx>, contexts?: Ctx[]): void,
  76. getData(): T
  77. }
  78. export namespace CIFEncoder {
  79. export function writeDatabase(encoder: CIFEncoder, name: string, database: Database<Database.Schema>) {
  80. encoder.startDataBlock(name);
  81. for (const table of database._tableNames) {
  82. encoder.writeCategory(() => CIFCategory.ofTable(table, database[table]));
  83. }
  84. }
  85. export function writeDatabaseCollection(encoder: CIFEncoder, collection: DatabaseCollection<Database.Schema>) {
  86. for (const name of Object.keys(collection)) {
  87. writeDatabase(encoder, name, collection[name])
  88. }
  89. }
  90. }
  91. function columnValue(k: string) {
  92. return (i: number, d: any) => d[k].value(i);
  93. }
  94. function columnListValue(k: string) {
  95. return (i: number, d: any) => d[k].value(i).join(d[k].schema.separator);
  96. }
  97. function columnTensorValue(k: string, ...coords: number[]) {
  98. return (i: number, d: any) => d[k].schema.space.get(d[k].value(i), ...coords);
  99. }
  100. function columnValueKind(k: string) {
  101. return (i: number, d: any) => d[k].valueKind(i);
  102. }
  103. function getTensorDefinitions(field: string, space: Tensor.Space) {
  104. const fieldDefinitions: CIFField[] = []
  105. const type = CIFField.Type.Float
  106. const valueKind = columnValueKind(field)
  107. if (space.rank === 1) {
  108. const rows = space.dimensions[0]
  109. for (let i = 0; i < rows; i++) {
  110. const name = `${field}[${i + 1}]`
  111. fieldDefinitions.push({ name, type, value: columnTensorValue(field, i), valueKind })
  112. }
  113. } else if (space.rank === 2) {
  114. const rows = space.dimensions[0], cols = space.dimensions[1]
  115. for (let i = 0; i < rows; i++) {
  116. for (let j = 0; j < cols; j++) {
  117. const name = `${field}[${i + 1}][${j + 1}]`
  118. fieldDefinitions.push({ name, type, value: columnTensorValue(field, i, j), valueKind })
  119. }
  120. }
  121. } else if (space.rank === 3) {
  122. const d0 = space.dimensions[0], d1 = space.dimensions[1], d2 = space.dimensions[2]
  123. for (let i = 0; i < d0; i++) {
  124. for (let j = 0; j < d1; j++) {
  125. for (let k = 0; k < d2; k++) {
  126. const name = `${field}[${i + 1}][${j + 1}][${k + 1}]`
  127. fieldDefinitions.push({ name, type, value: columnTensorValue(field, i, j, k), valueKind })
  128. }
  129. }
  130. }
  131. } else {
  132. throw new Error('Tensors with rank > 3 or rank 0 are currently not supported.')
  133. }
  134. return fieldDefinitions
  135. }
  136. function cifFieldsFromTableSchema(schema: Table.Schema) {
  137. const fields: CIFField[] = [];
  138. for (const k of Object.keys(schema)) {
  139. const t = schema[k];
  140. if (t.valueType === 'int') {
  141. fields.push({ name: k, type: CIFField.Type.Int, value: columnValue(k), valueKind: columnValueKind(k) });
  142. } else if (t.valueType === 'float') {
  143. fields.push({ name: k, type: CIFField.Type.Float, value: columnValue(k), valueKind: columnValueKind(k) });
  144. } else if (t.valueType === 'str') {
  145. fields.push({ name: k, type: CIFField.Type.Str, value: columnValue(k), valueKind: columnValueKind(k) });
  146. } else if (t.valueType === 'list') {
  147. fields.push({ name: k, type: CIFField.Type.Str, value: columnListValue(k), valueKind: columnValueKind(k) })
  148. } else if (t.valueType === 'tensor') {
  149. fields.push(...getTensorDefinitions(k, t.space))
  150. } else {
  151. throw new Error(`Unknown valueType ${t.valueType}`);
  152. }
  153. }
  154. return fields;
  155. }