behavior.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /**
  2. * Copyright (c) 2019-2020 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 { ParamDefinition as PD } from '../../../../mol-util/param-definition';
  8. import { PluginStateObject } from '../../../../mol-plugin-state/objects';
  9. import { Volume, Grid } from '../../../../mol-model/volume';
  10. import { createIsoValueParam } from '../../../../mol-repr/volume/isosurface';
  11. import { VolumeServerHeader, VolumeServerInfo } from './model';
  12. import { Box3D } from '../../../../mol-math/geometry';
  13. import { Vec3 } from '../../../../mol-math/linear-algebra';
  14. import { Color } from '../../../../mol-util/color';
  15. import { PluginBehavior } from '../../behavior';
  16. import { LRUCache } from '../../../../mol-util/lru-cache';
  17. import { urlCombine } from '../../../../mol-util/url';
  18. import { CIF } from '../../../../mol-io/reader/cif';
  19. import { volumeFromDensityServerData } from '../../../../mol-model-formats/volume/density-server';
  20. import { PluginCommands } from '../../../commands';
  21. import { StateSelection } from '../../../../mol-state';
  22. import { StructureElement, Structure } from '../../../../mol-model/structure';
  23. import { PluginContext } from '../../../context';
  24. import { EmptyLoci, Loci, isEmptyLoci } from '../../../../mol-model/loci';
  25. import { Asset } from '../../../../mol-util/assets';
  26. export class VolumeStreaming extends PluginStateObject.CreateBehavior<VolumeStreaming.Behavior>({ name: 'Volume Streaming' }) { }
  27. export namespace VolumeStreaming {
  28. export const RootTag = 'volume-streaming-info';
  29. export interface ChannelParams {
  30. isoValue: Volume.IsoValue,
  31. color: Color,
  32. wireframe: boolean,
  33. opacity: number
  34. }
  35. function channelParam(label: string, color: Color, defaultValue: Volume.IsoValue, stats: Grid['stats'], defaults: Partial<ChannelParams> = {}) {
  36. return PD.Group<ChannelParams>({
  37. isoValue: createIsoValueParam(typeof defaults.isoValue !== 'undefined' ? defaults.isoValue : defaultValue, stats),
  38. color: PD.Color(typeof defaults.color !== 'undefined' ? defaults.color : color),
  39. wireframe: PD.Boolean(typeof defaults.wireframe !== 'undefined' ? defaults.wireframe : false),
  40. opacity: PD.Numeric(typeof defaults.opacity !== 'undefined' ? defaults.opacity : 0.3, { min: 0, max: 1, step: 0.01 })
  41. }, { label, isExpanded: true });
  42. }
  43. const fakeSampling: VolumeServerHeader.Sampling = {
  44. byteOffset: 0,
  45. rate: 1,
  46. sampleCount: [1, 1, 1],
  47. valuesInfo: [{ mean: 0, min: -1, max: 1, sigma: 0.1 }, { mean: 0, min: -1, max: 1, sigma: 0.1 }]
  48. };
  49. export function createParams(options: { data?: VolumeServerInfo.Data, defaultView?: ViewTypes, channelParams?: DefaultChannelParams } = { }) {
  50. const { data, defaultView, channelParams } = options;
  51. const map = new Map<string, VolumeServerInfo.EntryData>();
  52. if (data) data.entries.forEach(d => map.set(d.dataId, d));
  53. const names = data ? data.entries.map(d => [d.dataId, d.dataId] as [string, string]) : [];
  54. const defaultKey = data ? data.entries[0].dataId : '';
  55. return {
  56. entry: PD.Mapped<EntryParams>(defaultKey, names, name => PD.Group(createEntryParams({ entryData: map.get(name)!, defaultView, structure: data && data.structure, channelParams }))),
  57. };
  58. }
  59. export type EntryParamDefinition = typeof createEntryParams extends (...args: any[]) => (infer T) ? T : never
  60. export type EntryParams = EntryParamDefinition extends PD.Params ? PD.Values<EntryParamDefinition> : {}
  61. export function createEntryParams(options: { entryData?: VolumeServerInfo.EntryData, defaultView?: ViewTypes, structure?: Structure, channelParams?: DefaultChannelParams }) {
  62. const { entryData, defaultView, structure, channelParams = { } } = options;
  63. // fake the info
  64. const info = entryData || { kind: 'em', header: { sampling: [fakeSampling], availablePrecisions: [{ precision: 0, maxVoxels: 0 }] }, emDefaultContourLevel: Volume.IsoValue.relative(0) };
  65. const box = (structure && structure.boundary.box) || Box3D.empty();
  66. return {
  67. view: PD.MappedStatic(defaultView || (info.kind === 'em' ? 'cell' : 'selection-box'), {
  68. 'off': PD.Group<{}>({}),
  69. 'box': PD.Group({
  70. bottomLeft: PD.Vec3(box.min),
  71. topRight: PD.Vec3(box.max),
  72. }, { description: 'Static box defined by cartesian coords.', isFlat: true }),
  73. 'selection-box': PD.Group({
  74. radius: PD.Numeric(5, { min: 0, max: 50, step: 0.5 }, { description: 'Radius in \u212B within which the volume is shown.' }),
  75. bottomLeft: PD.Vec3(Vec3.create(0, 0, 0), {}, { isHidden: true }),
  76. topRight: PD.Vec3(Vec3.create(0, 0, 0), {}, { isHidden: true }),
  77. }, { description: 'Box around focused element.', isFlat: true }),
  78. 'cell': PD.Group({}),
  79. // 'auto': PD.Group({ }), // TODO based on camera distance/active selection/whatever, show whole structure or slice.
  80. }, { options: ViewTypeOptions, description: 'Controls what of the volume is displayed. "Off" hides the volume alltogether. "Bounded box" shows the volume inside the given box. "Around Interaction" shows the volume around the focused element/atom. "Whole Structure" shows the volume for the whole structure.' }),
  81. detailLevel: PD.Select<number>(Math.min(3, info.header.availablePrecisions.length - 1),
  82. info.header.availablePrecisions.map((p, i) => [i, `${i + 1} [ ${Math.pow(p.maxVoxels, 1 / 3) | 0}^3 cells ]`] as [number, string]), { description: 'Determines the maximum number of voxels. Depending on the size of the volume options are in the range from 0 (0.52M voxels) to 6 (25.17M voxels).' }),
  83. channels: info.kind === 'em'
  84. ? PD.Group({
  85. 'em': channelParam('EM', Color(0x638F8F), info.emDefaultContourLevel || Volume.IsoValue.relative(1), info.header.sampling[0].valuesInfo[0], channelParams['em'])
  86. }, { isFlat: true })
  87. : PD.Group({
  88. '2fo-fc': channelParam('2Fo-Fc', Color(0x3362B2), Volume.IsoValue.relative(1.5), info.header.sampling[0].valuesInfo[0], channelParams['2fo-fc']),
  89. 'fo-fc(+ve)': channelParam('Fo-Fc(+ve)', Color(0x33BB33), Volume.IsoValue.relative(3), info.header.sampling[0].valuesInfo[1], channelParams['fo-fc(+ve)']),
  90. 'fo-fc(-ve)': channelParam('Fo-Fc(-ve)', Color(0xBB3333), Volume.IsoValue.relative(-3), info.header.sampling[0].valuesInfo[1], channelParams['fo-fc(-ve)']),
  91. }, { isFlat: true }),
  92. };
  93. }
  94. export const ViewTypeOptions = [['off', 'Off'], ['box', 'Bounded Box'], ['selection-box', 'Around Focus'], ['cell', 'Whole Structure']] as [ViewTypes, string][];
  95. export type ViewTypes = 'off' | 'box' | 'selection-box' | 'cell'
  96. export type ParamDefinition = typeof createParams extends (...args: any[]) => (infer T) ? T : never
  97. export type Params = ParamDefinition extends PD.Params ? PD.Values<ParamDefinition> : {}
  98. type ChannelsInfo = { [name in ChannelType]?: { isoValue: Volume.IsoValue, color: Color, wireframe: boolean, opacity: number } }
  99. type ChannelsData = { [name in 'EM' | '2FO-FC' | 'FO-FC']?: Volume }
  100. export type ChannelType = 'em' | '2fo-fc' | 'fo-fc(+ve)' | 'fo-fc(-ve)'
  101. export const ChannelTypeOptions: [ChannelType, string][] = [['em', 'em'], ['2fo-fc', '2fo-fc'], ['fo-fc(+ve)', 'fo-fc(+ve)'], ['fo-fc(-ve)', 'fo-fc(-ve)']];
  102. export interface ChannelInfo {
  103. data: Volume,
  104. color: Color,
  105. wireframe: boolean,
  106. isoValue: Volume.IsoValue.Relative,
  107. opacity: number
  108. }
  109. export type Channels = { [name in ChannelType]?: ChannelInfo }
  110. export type DefaultChannelParams = { [name in ChannelType]?: Partial<ChannelParams> }
  111. export class Behavior extends PluginBehavior.WithSubscribers<Params> {
  112. private cache = LRUCache.create<{ data: ChannelsData, asset: Asset.Wrapper }>(25);
  113. public params: Params = {} as any;
  114. private lastLoci: StructureElement.Loci | EmptyLoci = EmptyLoci;
  115. private ref: string = '';
  116. public infoMap: Map<string, VolumeServerInfo.EntryData>
  117. channels: Channels = {}
  118. public get info () {
  119. return this.infoMap.get(this.params.entry.name)!;
  120. }
  121. private async queryData(box?: Box3D) {
  122. let url = urlCombine(this.data.serverUrl, `${this.info.kind}/${this.info.dataId.toLowerCase()}`);
  123. if (box) {
  124. const { min: a, max: b } = box;
  125. url += `/box`
  126. + `/${a.map(v => Math.round(1000 * v) / 1000).join(',')}`
  127. + `/${b.map(v => Math.round(1000 * v) / 1000).join(',')}`;
  128. } else {
  129. url += `/cell`;
  130. }
  131. url += `?detail=${this.params.entry.params.detailLevel}`;
  132. const entry = LRUCache.get(this.cache, url);
  133. if (entry) return entry.data;
  134. const urlAsset = Asset.getUrlAsset(this.plugin.managers.asset, url);
  135. const asset = await this.plugin.runTask(this.plugin.managers.asset.resolve(urlAsset, 'binary'));
  136. const data = await this.parseCif(asset.data);
  137. if (!data) return;
  138. const removed = LRUCache.set(this.cache, url, { data, asset });
  139. if (removed) removed.asset.dispose();
  140. return data;
  141. }
  142. private async parseCif(data: Uint8Array): Promise<ChannelsData | undefined> {
  143. const parsed = await this.plugin.runTask(CIF.parseBinary(data));
  144. if (parsed.isError) {
  145. this.plugin.log.error('VolumeStreaming, parsing CIF: ' + parsed.toString());
  146. return;
  147. }
  148. if (parsed.result.blocks.length < 2) {
  149. this.plugin.log.error('VolumeStreaming: Invalid data.');
  150. return;
  151. }
  152. const ret: ChannelsData = {};
  153. for (let i = 1; i < parsed.result.blocks.length; i++) {
  154. const block = parsed.result.blocks[i];
  155. const densityServerCif = CIF.schema.densityServer(block);
  156. const volume = await this.plugin.runTask(volumeFromDensityServerData(densityServerCif));
  157. (ret as any)[block.header as any] = volume;
  158. }
  159. return ret;
  160. }
  161. private updateDynamicBox(box: Box3D) {
  162. if (this.params.entry.params.view.name !== 'selection-box') return;
  163. const state = this.plugin.state.data;
  164. const newParams: Params = {
  165. ...this.params,
  166. entry: {
  167. name: this.params.entry.name,
  168. params: {
  169. ...this.params.entry.params,
  170. view: {
  171. name: 'selection-box' as 'selection-box',
  172. params: {
  173. radius: this.params.entry.params.view.params.radius,
  174. bottomLeft: box.min,
  175. topRight: box.max
  176. }
  177. }
  178. }
  179. }
  180. };
  181. const update = state.build().to(this.ref).update(newParams);
  182. PluginCommands.State.Update(this.plugin, { state, tree: update, options: { doNotUpdateCurrent: true } });
  183. }
  184. private getStructureRoot() {
  185. return this.plugin.state.data.select(StateSelection.Generators.byRef(this.ref).rootOfType([PluginStateObject.Molecule.Structure]))[0];
  186. }
  187. register(ref: string): void {
  188. this.ref = ref;
  189. this.subscribeObservable(this.plugin.state.events.object.removed, o => {
  190. if (!PluginStateObject.Molecule.Structure.is(o.obj) || !StructureElement.Loci.is(this.lastLoci)) return;
  191. if (this.lastLoci.structure === o.obj.data) {
  192. this.lastLoci = EmptyLoci;
  193. }
  194. });
  195. this.subscribeObservable(this.plugin.state.events.object.updated, o => {
  196. if (!PluginStateObject.Molecule.Structure.is(o.oldObj) || !StructureElement.Loci.is(this.lastLoci)) return;
  197. if (this.lastLoci.structure === o.oldObj.data) {
  198. this.lastLoci = EmptyLoci;
  199. }
  200. });
  201. this.subscribeObservable(this.plugin.managers.structure.focus.behaviors.current, (entry) => {
  202. if (!this.plugin.state.data.tree.children.has(this.ref)) return;
  203. const loci = entry ? entry.loci : EmptyLoci;
  204. if (this.params.entry.params.view.name !== 'selection-box') {
  205. this.lastLoci = loci;
  206. } else {
  207. this.updateInteraction(loci);
  208. }
  209. });
  210. }
  211. unregister() {
  212. let entry = this.cache.entries.first;
  213. while (entry) {
  214. entry.value.data.asset.dispose();
  215. entry = entry.next;
  216. }
  217. }
  218. private getBoxFromLoci(loci: StructureElement.Loci | EmptyLoci): Box3D {
  219. if (Loci.isEmpty(loci)) {
  220. return Box3D.empty();
  221. }
  222. const parent = this.plugin.helpers.substructureParent.get(loci.structure, true);
  223. if (!parent) return Box3D.empty();
  224. const root = this.getStructureRoot();
  225. if (!root || root.obj?.data !== parent.obj?.data) return Box3D.empty();
  226. const extendedLoci = StructureElement.Loci.extendToWholeResidues(loci);
  227. const box = StructureElement.Loci.getBoundary(extendedLoci).box;
  228. if (StructureElement.Loci.size(extendedLoci) === 1) {
  229. Box3D.expand(box, box, Vec3.create(1, 1, 1));
  230. }
  231. return box;
  232. }
  233. private updateInteraction(loci: StructureElement.Loci | EmptyLoci) {
  234. if (Loci.areEqual(this.lastLoci, loci)) {
  235. this.lastLoci = EmptyLoci;
  236. this.updateDynamicBox(Box3D.empty());
  237. return;
  238. }
  239. this.lastLoci = loci;
  240. if (isEmptyLoci(loci)) {
  241. this.updateDynamicBox(Box3D.empty());
  242. return;
  243. }
  244. const box = this.getBoxFromLoci(loci);
  245. this.updateDynamicBox(box);
  246. }
  247. async update(params: Params) {
  248. const switchedToSelection = params.entry.params.view.name === 'selection-box' && this.params && this.params.entry && this.params.entry.params && this.params.entry.params.view && this.params.entry.params.view.name !== 'selection-box';
  249. this.params = params;
  250. let box: Box3D | undefined = void 0, emptyData = false;
  251. switch (params.entry.params.view.name) {
  252. case 'off':
  253. emptyData = true;
  254. break;
  255. case 'box':
  256. box = Box3D.create(params.entry.params.view.params.bottomLeft, params.entry.params.view.params.topRight);
  257. emptyData = Box3D.volume(box) < 0.0001;
  258. break;
  259. case 'selection-box': {
  260. if (switchedToSelection) {
  261. box = this.getBoxFromLoci(this.lastLoci) || Box3D.empty();
  262. } else {
  263. box = Box3D.create(Vec3.clone(params.entry.params.view.params.bottomLeft), Vec3.clone(params.entry.params.view.params.topRight));
  264. }
  265. const r = params.entry.params.view.params.radius;
  266. emptyData = Box3D.volume(box) < 0.0001;
  267. Box3D.expand(box, box, Vec3.create(r, r, r));
  268. break;
  269. }
  270. case 'cell':
  271. box = this.info.kind === 'x-ray'
  272. ? this.data.structure.boundary.box
  273. : void 0;
  274. break;
  275. }
  276. const data = emptyData ? {} : await this.queryData(box);
  277. if (!data) return false;
  278. const info = params.entry.params.channels as ChannelsInfo;
  279. if (this.info.kind === 'x-ray') {
  280. this.channels['2fo-fc'] = this.createChannel(data['2FO-FC'] || Volume.One, info['2fo-fc'], this.info.header.sampling[0].valuesInfo[0]);
  281. this.channels['fo-fc(+ve)'] = this.createChannel(data['FO-FC'] || Volume.One, info['fo-fc(+ve)'], this.info.header.sampling[0].valuesInfo[1]);
  282. this.channels['fo-fc(-ve)'] = this.createChannel(data['FO-FC'] || Volume.One, info['fo-fc(-ve)'], this.info.header.sampling[0].valuesInfo[1]);
  283. } else {
  284. this.channels['em'] = this.createChannel(data['EM'] || Volume.One, info['em'], this.info.header.sampling[0].valuesInfo[0]);
  285. }
  286. return true;
  287. }
  288. private createChannel(data: Volume, info: ChannelsInfo['em'], stats: Grid['stats']): ChannelInfo {
  289. const i = info!;
  290. return {
  291. data,
  292. color: i.color,
  293. wireframe: i.wireframe,
  294. opacity: i.opacity,
  295. isoValue: i.isoValue.kind === 'relative' ? i.isoValue : Volume.IsoValue.toRelative(i.isoValue, stats)
  296. };
  297. }
  298. getDescription() {
  299. if (this.params.entry.params.view.name === 'selection-box') return 'Selection';
  300. if (this.params.entry.params.view.name === 'box') return 'Static Box';
  301. if (this.params.entry.params.view.name === 'cell') return 'Cell';
  302. return '';
  303. }
  304. constructor(public plugin: PluginContext, public data: VolumeServerInfo.Data) {
  305. super(plugin, {} as any);
  306. this.infoMap = new Map<string, VolumeServerInfo.EntryData>();
  307. this.data.entries.forEach(info => this.infoMap.set(info.dataId, info));
  308. }
  309. }
  310. }