encoder.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 EncoderBase 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 Field<Key = any, Data = any> {
  19. name: string,
  20. type: Field.Type,
  21. value(key: Key, data: Data): string | number
  22. valueKind?: (key: Key, data: Data) => Column.ValueKind,
  23. defaultFormat?: Field.Format,
  24. shouldInclude?: (data: Data) => boolean
  25. }
  26. export namespace Field {
  27. export const enum Type { Str, Int, Float }
  28. export interface Format {
  29. digitCount?: number,
  30. encoder?: ArrayEncoder,
  31. typedArray?: ArrayEncoding.TypedArrayCtor
  32. }
  33. export type ParamsBase<K, D> = { valueKind?: (k: K, d: D) => Column.ValueKind, encoder?: ArrayEncoder, shouldInclude?: (data: D) => boolean }
  34. export function str<K, D = any>(name: string, value: (k: K, d: D) => string, params?: ParamsBase<K, D>): Field<K, D> {
  35. return { name, type: Type.Str, value, valueKind: params && params.valueKind, defaultFormat: params && params.encoder ? { encoder: params.encoder } : void 0, shouldInclude: params && params.shouldInclude };
  36. }
  37. export function int<K, D = any>(name: string, value: (k: K, d: D) => number, params?: ParamsBase<K, D> & { typedArray?: ArrayEncoding.TypedArrayCtor }): Field<K, D> {
  38. return {
  39. name,
  40. type: Type.Int,
  41. value,
  42. valueKind: params && params.valueKind,
  43. defaultFormat: params ? { encoder: params.encoder, typedArray: params.typedArray } : void 0,
  44. shouldInclude: params && params.shouldInclude
  45. };
  46. }
  47. export function float<K, D = any>(name: string, value: (k: K, d: D) => number, params?: ParamsBase<K, D> & { typedArray?: ArrayEncoding.TypedArrayCtor, digitCount?: number }): Field<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. shouldInclude: params && params.shouldInclude
  55. };
  56. }
  57. }
  58. export interface Category<Key = any, Data = any> {
  59. name: string,
  60. fields: Field<Key, Data>[],
  61. data?: Data,
  62. rowCount: number,
  63. keys?: () => Iterator<Key>
  64. }
  65. export namespace Category {
  66. export const Empty: Category = { name: 'empty', rowCount: 0, fields: [] };
  67. export interface Provider<Ctx = any> {
  68. (ctx: Ctx): Category
  69. }
  70. export interface Filter {
  71. includeCategory(categoryName: string): boolean,
  72. includeField(categoryName: string, fieldName: string): boolean,
  73. }
  74. export const DefaultFilter: Filter = {
  75. includeCategory(cat) { return true; },
  76. includeField(cat, field) { return true; }
  77. }
  78. export interface Formatter {
  79. getFormat(categoryName: string, fieldName: string): Field.Format | undefined
  80. }
  81. export const DefaultFormatter: Formatter = {
  82. getFormat(cat, field) { return void 0; }
  83. }
  84. export function ofTable(name: string, table: Table<Table.Schema>, indices?: ArrayLike<number>): Category<number, Table<Table.Schema>> {
  85. if (indices) {
  86. return { name, fields: cifFieldsFromTableSchema(table._schema), data: table, rowCount: indices.length, keys: () => Iterator.Array(indices) };
  87. }
  88. return { name, fields: cifFieldsFromTableSchema(table._schema), data: table, rowCount: table._rowCount };
  89. }
  90. }
  91. export interface Encoder<T = string | Uint8Array> extends EncoderBase {
  92. setFilter(filter?: Category.Filter): void,
  93. setFormatter(formatter?: Category.Formatter): void,
  94. startDataBlock(header: string): void,
  95. writeCategory<Ctx>(category: Category.Provider<Ctx>, contexts?: Ctx[]): void,
  96. getData(): T
  97. }
  98. export namespace Encoder {
  99. export function writeDatabase(encoder: Encoder, name: string, database: Database<Database.Schema>) {
  100. encoder.startDataBlock(name);
  101. for (const table of database._tableNames) {
  102. encoder.writeCategory(() => Category.ofTable(table, database[table]));
  103. }
  104. }
  105. export function writeDatabaseCollection(encoder: Encoder, collection: DatabaseCollection<Database.Schema>) {
  106. for (const name of Object.keys(collection)) {
  107. writeDatabase(encoder, name, collection[name])
  108. }
  109. }
  110. }
  111. function columnValue(k: string) {
  112. return (i: number, d: any) => d[k].value(i);
  113. }
  114. function columnListValue(k: string) {
  115. return (i: number, d: any) => d[k].value(i).join(d[k].schema.separator);
  116. }
  117. function columnTensorValue(k: string, ...coords: number[]) {
  118. return (i: number, d: any) => d[k].schema.space.get(d[k].value(i), ...coords);
  119. }
  120. function columnValueKind(k: string) {
  121. return (i: number, d: any) => d[k].valueKind(i);
  122. }
  123. function getTensorDefinitions(field: string, space: Tensor.Space) {
  124. const fieldDefinitions: Field[] = []
  125. const type = Field.Type.Float
  126. const valueKind = columnValueKind(field)
  127. if (space.rank === 1) {
  128. const rows = space.dimensions[0]
  129. for (let i = 0; i < rows; i++) {
  130. const name = `${field}[${i + 1}]`
  131. fieldDefinitions.push({ name, type, value: columnTensorValue(field, i), valueKind })
  132. }
  133. } else if (space.rank === 2) {
  134. const rows = space.dimensions[0], cols = space.dimensions[1]
  135. for (let i = 0; i < rows; i++) {
  136. for (let j = 0; j < cols; j++) {
  137. const name = `${field}[${i + 1}][${j + 1}]`
  138. fieldDefinitions.push({ name, type, value: columnTensorValue(field, i, j), valueKind })
  139. }
  140. }
  141. } else if (space.rank === 3) {
  142. const d0 = space.dimensions[0], d1 = space.dimensions[1], d2 = space.dimensions[2]
  143. for (let i = 0; i < d0; i++) {
  144. for (let j = 0; j < d1; j++) {
  145. for (let k = 0; k < d2; k++) {
  146. const name = `${field}[${i + 1}][${j + 1}][${k + 1}]`
  147. fieldDefinitions.push({ name, type, value: columnTensorValue(field, i, j, k), valueKind })
  148. }
  149. }
  150. }
  151. } else {
  152. throw new Error('Tensors with rank > 3 or rank 0 are currently not supported.')
  153. }
  154. return fieldDefinitions
  155. }
  156. function cifFieldsFromTableSchema(schema: Table.Schema) {
  157. const fields: Field[] = [];
  158. for (const k of Object.keys(schema)) {
  159. const t = schema[k];
  160. if (t.valueType === 'int') {
  161. fields.push({ name: k, type: Field.Type.Int, value: columnValue(k), valueKind: columnValueKind(k) });
  162. } else if (t.valueType === 'float') {
  163. fields.push({ name: k, type: Field.Type.Float, value: columnValue(k), valueKind: columnValueKind(k) });
  164. } else if (t.valueType === 'str') {
  165. fields.push({ name: k, type: Field.Type.Str, value: columnValue(k), valueKind: columnValueKind(k) });
  166. } else if (t.valueType === 'list') {
  167. fields.push({ name: k, type: Field.Type.Str, value: columnListValue(k), valueKind: columnValueKind(k) })
  168. } else if (t.valueType === 'tensor') {
  169. fields.push(...getTensorDefinitions(k, t.space))
  170. } else {
  171. throw new Error(`Unknown valueType ${t.valueType}`);
  172. }
  173. }
  174. return fields;
  175. }