-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory.js
More file actions
1632 lines (1408 loc) · 52.2 KB
/
factory.js
File metadata and controls
1632 lines (1408 loc) · 52.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import _ from 'underscore';
import '../../common/lib/polyfills'; // required for String.prototype.endsWith
import classMethodsMixin from './sequence_class_methods_mixin';
import smartMemoizeAndClear from 'gentle-utils/smart_memoize_and_clear';
import deprecated from 'gentle-utils/deprecated_method';
import SequenceTransforms from 'gentle-sequence-transforms';
import SequenceRange from './range';
import HistorySteps from '../../sequence/models/history_steps';
const STICKY_END_FULL = 'full';
const STICKY_END_OVERHANG = 'overhang';
const STICKY_END_NONE = 'none';
// Used to represent cases when there are no sticky ends on the model so the
// format type does not matter. NOTE: this is not a valid format to set on the
// sequenceModel. Only a valid format to request of functions.
var STICKY_END_ANY;
const stickyEndFormats = [STICKY_END_FULL, STICKY_END_OVERHANG, STICKY_END_NONE];
let instantiateSingle = function(constructor, otherArgs, fieldValue) {
let instance = fieldValue;
if(!_.isUndefined(instance) && !(instance instanceof constructor)) {
if(otherArgs.parentSequence) {
instance.parentSequence = otherArgs.parentSequence;
}
let opts = {};
if(_.has(otherArgs, 'doNotValidated')) opts.doNotValidated = otherArgs.doNotValidated;
// Instantiate a new instance of the given constructor with instance
instance = new constructor(instance, opts);
}
return instance;
};
/**
* @function instantiate
* @param {String} association
* @param {Any} fieldValue
* @param {Object} otherArgs
* @return {Instance or undefined}
*/
let instantiate = function(association, fieldValue, otherArgs) {
if(association.many) {
// Instantiate an array of new instances of the given constructor
fieldValue = _.map(fieldValue, _.partial(instantiateSingle, association.constructor, otherArgs));
} else if(!_.isUndefined(fieldValue)) {
fieldValue = instantiateSingle(association.constructor, otherArgs, fieldValue);
}
return fieldValue;
};
function sequenceModelFactory(BackboneModel) {
// `associations` has the following form:
// [
// {
// klass: ASequenceModelClass,
// classAssociations: [
// {
// associationName: String,
// many: Boolean,
// constructor: SomeChildClass
// },
// ...
// ]
// },
// ...
// ]
let associations = [];
var associationsForKlass = function(klass) {
return _.find(associations, (association) => association.klass === klass);
};
var allAssociationsForInstance = function(instance) {
var allAssociations = [];
_.each(associations, (association) => {
if(instance instanceof association.klass) allAssociations = allAssociations.concat(association.classAssociations);
});
return allAssociations;
};
let preProcessors = [];
/**
* Represents a sequence of nucleotides (DNA bases).
* @class BaseSequenceModel
* @constructor
*/
class Sequence extends BackboneModel {
/**
* @constructor
* @param {Object} attributes
* @param {Object} options List of available options:
* `disabledSave`
*/
constructor(attributes, options={}) {
// Mark model instance as not validated yet. Commented out as "'this'
// is not allowed before super()"
// this._validated = false;
// Run all preProcessors on attributes
attributes = _.reduce(preProcessors, (attribs, pp) => pp(attribs), attributes);
super(attributes, options);
this.disabledSave = options.disabledSave;
this.validateFields(attributes);
this.sortFeatures();
this.getComplements = _.bind(_.partial(this.getTransformedSubSeq, 'complements', {}), this);
var defaultStickyEndsEvent = 'change:stickyEnds change:stickyEndFormat';
smartMemoizeAndClear(this, {
maxOverlappingFeatures: `change:sequence change:features ${defaultStickyEndsEvent}`,
nbFeaturesInRange: `change:sequence change:features ${defaultStickyEndsEvent}`,
getSequence: `change:sequence ${defaultStickyEndsEvent}`,
getFeatures: `change:features ${defaultStickyEndsEvent}`,
getStickyEnds: defaultStickyEndsEvent,
editableRange: `change:sequence ${defaultStickyEndsEvent}`,
selectableRange: `change:sequence ${defaultStickyEndsEvent}`,
});
// If a value in this.attributes has a key with the same value as an
// associations `associationName` then run its `validate()` method.
var allAssociations = allAssociationsForInstance(this);
_.each(allAssociations, ({associationName, many}) => {
if(_.has(this.attributes, associationName)) {
let value = this.attributes[associationName];
if(many) {
_.each(value, function(subVal) {
if(_.isFunction(subVal.validate)) subVal.validate();
});
} else {
if(_.isFunction(value.validate)) value.validate();
}
}
});
this.setNonEnumerableFields();
}
get STICKY_END_FULL() {
return STICKY_END_FULL;
}
get STICKY_END_OVERHANG() {
return STICKY_END_OVERHANG;
}
get STICKY_END_NONE() {
return STICKY_END_NONE;
}
get STICKY_END_ANY() {
return STICKY_END_ANY;
}
/**
* Return a list of all possible attribute fields on this model.
* @method allFields
* @return {Array<String>}
*/
get allFields() {
var allFields = allFields || _.unique(this.requiredFields.concat(this.optionalFields));
return allFields;
}
/**
* Return a list of all required attribute fields on this model.
* @method requiredFields
* @return {Array<String>}
*/
get requiredFields() {
return ['sequence'];
}
/**
* Return a list of all optional attribute fields on this model.
* @method optionalFields
* @return {Array<String>}
*/
get optionalFields() {
return [
'id',
'name',
'version',
'desc',
'stickyEnds',
'features',
'reverse',
'readOnly',
'isCircular',
'stickyEndFormat',
'parentSequence',
'shortName',
'_type'
];
}
/**
* @method nonEnumerableFields
* @return {Array}
*/
get nonEnumerableFields() {
var associationNames = _.pluck(
allAssociationsForInstance(this),
'associationName'
);
return associationNames.concat([
'parentSequence'
]);
}
setNonEnumerableFields() {
_.each(this.nonEnumerableFields, (fieldName) => {
// Makes non-enumerable fields we want to remain hidden and only used by
// the class instance. e.g. Which won't be found with `for(x of this.attributes)`
var configurable = false;
var writable = true;
var enumerable = false;
var value = this.attributes[fieldName];
if(_.has(this.attributes, fieldName)) {
Object.defineProperty(this.attributes, fieldName, {enumerable, value, writable, configurable});
}
});
}
validateFields(attributes) {
var attributeNames = _.keys(attributes);
var missingAttributes = _.without(this.requiredFields, ...attributeNames);
var extraAttributes = _.without(attributeNames, ...this.allFields);
if(missingAttributes.length) {
throw `${this.constructor.name} is missing the following attributes: ${missingAttributes.join(', ')}`;
}
if(extraAttributes.length) {
// console.warn(`Assigned the following disallowed attributes to ${this.constructor.name}: ${extraAttributes.join(', ')}`);
}
this._validated = true;
}
defaults() {
return {
id: _.uniqueId(),
version: 0,
readOnly: false,
isCircular: false,
history: new HistorySteps(),
stickyEndFormat: STICKY_END_OVERHANG
};
}
superGet(attribute) {
return super.get(attribute);
}
/**
* Wraps the standard get function to use a custom getNnnnnnn if available.
* @param {String} attribute
* @param {Object} options=undefined
* @return {Any}
*/
get(attribute, options = undefined) {
var value;
var customGet = "get" + _.ucFirst(attribute);
if (this[customGet]){
deprecated(this, `get('${attribute}')`, customGet);
value = this[customGet](options);
} else {
value = super.get(attribute);
}
return value;
}
/**
* @method set
* @param {String} attribute
* @param {Any} value
* @param {Object} options
*/
set(attribute, value, options) {
if(_.isString(attribute)) {
value = this.transformAttributeValue(attribute, value);
} else if (_.isObject(attribute)) {
_.each(attribute, (val, attr) => {
attribute[attr] = this.transformAttributeValue(attr, val);
});
}
var ret = super.set(attribute, value, options);
this.setNonEnumerableFields();
return ret;
}
transformAttributeValue(attribute, val) {
var allAssociations = allAssociationsForInstance(this);
var association = _(allAssociations).findWhere({associationName: attribute});
if(association) {
// `doNotValidated` and `this._validated` only relevant to the
// constructor and skipping validation of associated child models.
val = instantiate(association, val, {parentSequence: this, doNotValidated: !this._validated});
}
return val;
}
/**
* @method getStickyEnds
* @param {Boolean} withDefaults=false
* @return {undefined or Object}
*/
getStickyEnds(withDefaults=false) {
var stickyEnds = _.deepClone(super.get('stickyEnds'));
// If stickyEnds is an empty object, force it to be undefined so that
// `getStickyEnds(false)` can be used in conditionals for truthiness.
if(_.isEmpty(stickyEnds)) stickyEnds = undefined;
if(withDefaults) {
stickyEnds = _.defaults((stickyEnds || {}), {
start: {size: 0, offset: 0, reverse: false, name: ''},
end: {size: 0, offset: 0, reverse: false, name: ''},
});
}
return stickyEnds;
}
/**
* @method setStickyEnds
* @param {object} stickyEnds
* @throws {Error} If sequenceModel already has stickyEnds
*/
setStickyEnds(stickyEnds, options={}) {
// Must set silent to false to trigger clearing incorrect cache values.
options = _.defaults({silent: false}, options);
var currentStickyEnds = this.getStickyEnds(false);
if(currentStickyEnds) {
throw new Error('Sequence already has stickyEnds, remove them first with removeStickyEnds');
} else {
var opts = {updateHistory: false, stickyEndFormat: STICKY_END_ANY};
this.insertBases(stickyEnds.start.sequence, 0, opts);
this.insertBases(stickyEnds.end.sequence, this.getLength(STICKY_END_ANY), opts);
super.set({stickyEnds}, options);
}
}
/**
* @method deleteStickyEnds
* @throws {Error} If no stickyEnds to delete.
*/
deleteStickyEnds(options={}) {
// Must set silent to false to trigger clearing incorrect cache values.
options = _.defaults({silent: false}, options);
var stickyEnds = this.getStickyEnds(false);
if(stickyEnds) {
var opts = {updateHistory: false, stickyEndFormat: STICKY_END_FULL};
// delete `end` before `start` because of various functions caching values.
if(stickyEnds.end) {
var offset = this.getOffset(STICKY_END_NONE);
var len = this.getLength(STICKY_END_NONE);
this.deleteBases(offset + len, stickyEnds.end.size + stickyEnds.end.offset, opts);
}
if(stickyEnds.start) {
this.deleteBases(0, stickyEnds.start.size + stickyEnds.start.offset, opts);
}
super.set({stickyEnds: undefined}, options);
} else {
throw new Error('Sequence already lacks stickyEnds.');
}
}
getStickyEndFormat() {
return super.get('stickyEndFormat');
}
validateStickyEndFormat(value) {
if(!value || !~stickyEndFormats.indexOf(value)) {
throw `'${JSON.stringify(value, null, 2)}' is not an acceptable sticky end format`;
}
}
setStickyEndFormat(value) {
this.validateStickyEndFormat(value);
return this.set('stickyEndFormat', value);
}
/**
* Specialized function for getting the sequence attribute. Varies result depending on value of the `stickyEndFormat` attribute
* 'none' will return the sequence without sticky ends.
* 'overhang' will return the sequence with the active section of sticky ends.
* Default value will return the full (blunt) sticky end.
* @method getSequence
* @param {String} stickyEndFormat=undefined
* @return {String} Formatted sequence
*/
getSequence(stickyEndFormat=undefined) {
var sequence = super.get('sequence');
stickyEndFormat = stickyEndFormat || this.getStickyEndFormat();
this.validateStickyEndFormat(stickyEndFormat);
var startPostion = this.getOffset(stickyEndFormat);
var endStickyEnds = this.getStickyEnds(true).end;
var endPosition;
if(stickyEndFormat === STICKY_END_NONE) {
endPosition = sequence.length - endStickyEnds.size - endStickyEnds.offset;
} else if(stickyEndFormat === STICKY_END_OVERHANG) {
endPosition = sequence.length - endStickyEnds.offset;
}
if(endPosition !== undefined) {
sequence = sequence.substring(startPostion, endPosition);
}
return sequence;
}
/**
* @method getOffset
* The number of bases the start stickyEnd accounts for before the start of
* the main sequence.
* @param {String} stickyEndFormat=undefined
* @return {Integer}
*/
getOffset(stickyEndFormat=undefined) {
var offset = 0;
stickyEndFormat = stickyEndFormat || this.getStickyEndFormat();
var startStickyEnd = this.getStickyEnds(true).start;
if(stickyEndFormat === STICKY_END_NONE) {
offset = startStickyEnd.offset + startStickyEnd.size;
} else if(stickyEndFormat === STICKY_END_OVERHANG) {
offset = startStickyEnd.offset;
}
return offset;
}
getFeatures(stickyEndFormat = undefined) {
stickyEndFormat = stickyEndFormat || this.getStickyEndFormat();
var length = this.getLength(stickyEndFormat);
let offset = this.getOffset(stickyEndFormat);
let maxValue = offset + length;
var filterAndAdjustRanges = function(offset, maxValue, feature) {
feature.ranges = _.filter(feature.ranges, function(range) {
let include;
if(range instanceof SequenceRange) {
include = range.from < maxValue && range.to > offset;
} else {
if(range.from <= range.to) {
include = range.from < maxValue && range.to >= offset;
} else {
// going in reverse
include = range.to < (maxValue - 2) && range.from >= offset;
}
}
return include;
});
_.each(feature.ranges, function(range) {
range.from = Math.max(Math.min(range.from - offset, length -1), 0);
range.to = Math.max(Math.min(range.to - offset, length -1), 0);
});
};
let func = _.partial(filterAndAdjustRanges, offset, maxValue);
let adjustedFeatures = _.deepClone(super.get('features'));
_.map(adjustedFeatures, func);
adjustedFeatures = _.reject(adjustedFeatures, (feature) => !feature.ranges.length);
return adjustedFeatures;
}
/**
Returns the subsequence between the bases startBase and end Base
@method getSubSeq
@param {Integer} startBase start of the subsequence (indexed from 0)
@param {Integer} endBase end of the subsequence (indexed from 0), INCLUSIVE.
@param {String} stickyEndFormat=undefined
**/
getSubSeq(startBase, endBase, stickyEndFormat=undefined) {
var len = this.getLength(stickyEndFormat);
if(endBase === undefined) {
endBase = startBase;
} else {
if (endBase >= len && startBase >= len) return '';
endBase = Math.min(len - 1, endBase);
}
startBase = Math.min(Math.max(0, startBase), len - 1);
return this.getSequence(stickyEndFormat).substr(startBase, endBase - startBase + 1);
// endBase = (endBase === undefined) ? startBase + 1 : endBase;
// return this.get('sequence', options).substring(startBase, endBase);
}
/**
* @method getSubSeqExclusive
* @param {Integer} startBase Inclusive
* @param {Integer} size
* @param {String} stickyEndFormat=undefined
* @return {String}
*/
getSubSeqExclusive(startBase, size, stickyEndFormat=undefined) {
var len = this.getLength(stickyEndFormat);
startBase = Math.min(Math.max(0, startBase), len - 1);
return this.getSequence(stickyEndFormat).substr(startBase, size);
}
/**
* @method minOverhangBeyondStartStickyEndOnBothStrands
* @param {Integer} pos
* @return {Integer}
*/
minOverhangBeyondStartStickyEndOnBothStrands(pos) {
return Math.min(this.overhangBeyondStartStickyEnd(pos, true), this.overhangBeyondStartStickyEnd(pos, false));
}
/**
* @method minOverhangBeyondEndStickyEndOnBothStrands
* @param {Integer} pos
* @return {Integer}
*/
minOverhangBeyondEndStickyEndOnBothStrands(pos) {
return Math.min(this.overhangBeyondEndStickyEnd(pos, true), this.overhangBeyondEndStickyEnd(pos, false));
}
/**
* @method overhangBeyondStartStickyEnd
* If the start sticky end was digested to make it exposed, this function
* returns the number of bases beyond the end, depending on the strand.
*
* e.g. There is a sticky end on the forward strand with offset 3, size 2:
*
* AAA|TT GG...
* --
* TTT AA|CC...
*
* reverse: | false | true |
* pos: | 0 | 5 | 0 | 5 |
* result: | 3 | -2 | 5 | 0 |
*
* @param {Integer} pos
* @param {Boolean} reverse=false If true, assesses reverse strand.
* @return {Integer}
*/
overhangBeyondStartStickyEnd(pos, reverse = false) {
var startStickyEnd = this.getStickyEnds(true).start;
var result = 0;
result = startStickyEnd.offset - pos;
if(reverse !== startStickyEnd.reverse) {
result += startStickyEnd.size;
}
return result;
}
/**
* @method overhangBeyondEndStickyEnd
* @param {Integer} pos
* @param {Boolean} reverse=false If true, assesses reverse strand.
* @return {Integer}
*/
overhangBeyondEndStickyEnd(pos, reverse = false) {
var endStickyEnd = this.getStickyEnds(true).end;
var seqLength = this.getLength(STICKY_END_FULL);
var result = pos - (seqLength - 1 - endStickyEnd.offset);
if(reverse !== endStickyEnd.reverse) {
result += endStickyEnd.size;
}
return result;
}
/**
* @method getStartStickyEndSequence
* @return {Object} see `getStickyEndSequence` for description of return type
*/
getStartStickyEndSequence() {
return this.getStickyEndSequence(true);
}
/**
* @method getEndStickyEndSequence
* @return {Object} see `getStickyEndSequence` for description of return type
*/
getEndStickyEndSequence() {
return this.getStickyEndSequence(false);
}
/**
* @method getStickyEndSequence
* @param {Boolean} getStartStickyEnd
* @return {Object}
* sequenceBases: {String} sequence bases of stickyEnd (if on reverse
* strand then complement is taken but not
* reverse complement)
* isOnReverseStrand: {Boolean} true if sequence is on reverse strand
*/
getStickyEndSequence(getStartStickyEnd) {
var wholeSequence = this.getSequence(this.STICKY_END_FULL);
var stickyEnds = this.getStickyEnds(true);
var stickyEnd, offset;
if(getStartStickyEnd) {
stickyEnd = stickyEnds.start;
offset = stickyEnds.start.offset;
} else {
stickyEnd = stickyEnds.end;
offset = wholeSequence.length - (stickyEnds.end.offset + stickyEnds.end.size);
}
var sequenceBases = wholeSequence.substr(offset, stickyEnd.size);
var isOnReverseStrand = stickyEnd.reverse;
if(isOnReverseStrand) {
sequenceBases = SequenceTransforms.toComplements(sequenceBases);
}
return {sequenceBases, isOnReverseStrand};
}
/**
* Returns True if this sequenceModel has a complementary end stickyEnd to the
* supplied sequenceModel's start stickyEnd
* @method stickyEndConnects
* @param {SequenceModel} sequenceModel
* @return {Boolean}
*/
stickyEndConnects (sequence) {
var thisEndStickySequence = this.getEndStickyEndSequence();
var otherStartStickySequence = sequence.getStartStickyEndSequence();
var canConnect = ((thisEndStickySequence.isOnReverseStrand != otherStartStickySequence.isOnReverseStrand) &&
SequenceTransforms.areComplementary(thisEndStickySequence.sequenceBases, otherStartStickySequence.sequenceBases));
return canConnect;
}
/**
* @method hasBothStickyEnds
* @return {Boolean}
*/
hasBothStickyEnds() {
var stickyEnds = this.getStickyEnds(false);
return !!(stickyEnds && stickyEnds.start && stickyEnds.end);
}
/**
Returns a transformed subsequence between the bases startBase and end Base
@method getTransformedSubSeq
@param {String} variation name of the transformation
@param {Object} options={}
@param {Integer} startBase start of the subsequence (indexed from 0)
@param {Integer} endBase end of the subsequence (indexed from 0)
@return {String or Array}
**/
getTransformedSubSeq(variation, options={}, startBase, endBase) {
var output = '';
options = _.defaults(_.deepClone(options), {offset: 0});
switch (variation) {
case 'aa-long':
case 'aa-short':
var paddedSubSeq = this.getPaddedSubSeq(startBase, endBase, 3, options.offset || 0),
offset;
output = _.map(paddedSubSeq.subSeq.match(/.{1,3}/g) || [], function(codon) {
if (options.complements === true) codon = SequenceTransforms.toComplements(codon);
return SequenceTransforms[variation == 'aa-long' ? 'codonToAALong' : 'codonToAAShort'](codon);
}).join('');
offset = Math.max(0, paddedSubSeq.startBase - startBase);
output = output.substr(Math.max(0, startBase - paddedSubSeq.startBase), endBase - startBase + 1 - offset);
_.times(Math.max(0, offset), function() {
output = ' ' + output;
});
break;
case 'complements':
output = SequenceTransforms.toComplements(this.getSubSeq(startBase, endBase));
break;
default:
throw new Error(`Unsupported sequence transform '${variation}'`);
}
return output;
}
/**
* @method getPaddedSubSeq
* Returns a subsequence including the subsequence between the bases
* `startBase` and `endBase`. Ensures that blocks of size `blockSize` and
* starting from the base `offset` in the complete sequence are not broken
* by the beginning or the end of the subsequence.
*
* @param {Integer} startBase Start of the subsequence (indexed from 0)
* @param {Integer} endBase End of the subsequence (indexed from 0)
* @param {Integer} blockSize
* @param {Integer} offset=0 Relative to the start of full sequence
* @return {Object} Key values:
* {String} subSeq
* {Integer} startBase
* {Integer} endBase
**/
getPaddedSubSeq(startBase, endBase, blockSize, offset=0) {
startBase = Math.max(startBase - (startBase - offset) % blockSize, 0);
endBase = Math.min(endBase - (endBase - offset) % blockSize + blockSize - 1, this.getLength());
return {
subSeq: this.getSubSeq(startBase, endBase),
startBase: startBase,
endBase: endBase
};
}
/**
@method getCodon
@param {Integer} base
@param {Integer, optional} offset
@returns {Object} codon to which the base belongs and position of the base in the codon (from 0)
**/
getCodon(base, offset = 0) {
if(base < 0) throw new Error(`'base' must be >= 0 but was '${base}'`);
var subSeq = this.getPaddedSubSeq(base, base, 3, offset);
if (subSeq.startBase > base) {
return {
sequence: this.getSequence()[base],
position: 1
};
} else {
return {
sequence: subSeq.subSeq,
position: (base - offset) % 3
};
}
}
/**
@method codonToAA
**/
getAA(variation, base, offset) {
var codon = this.getCodon(base, offset || 0),
aa = SequenceTransforms[variation == 'short' ? 'codonToAAShort' : 'codonToAALong'](codon.sequence) || '';
return {
sequence: aa || ' ',
position: codon.position
};
}
/**
* @method getAAs
* @param {Integer} startBase
* @param {Integer} length
* @param {String} stickyEndFormat=undefined
* @return {List of Strings}
*/
getAAs(startBase, length, stickyEndFormat=undefined) {
var subSeq = this.getSubSeq(startBase, startBase + length - 1, stickyEndFormat);
if(length < 0 || subSeq.length % 3 !== 0) throw new Error('length must be non negative and result in a sub sequence length which is multiple of 3');
var codons = subSeq.match(/.{3}/g) || [];
return _.map(codons, function(codon) {
return SequenceTransforms.codonToAAShort(codon).trim();
});
}
/**
@method featuresInRange
@param {integer} startBase
@param {integer} endBase
@returns {array} all features present between start and end base
**/
featuresInRange(startBase, endBase) {
var features = this.getFeatures();
if (_.isArray(features)) {
return _(features).filter((feature) => {
return this.filterRanges(startBase, endBase, feature.ranges).length > 0;
});
} else {
return [];
}
}
/**
* @method filterRanges
* @param {integer} startBase
* @param {integer} endBase
* @param {array} list of feature ranges
* @return {array} all ranges overlapping start and end base
*/
filterRanges(startBase, endBase, ranges) {
return _.filter(ranges, function(range) {
if(range.from < range.to) {
return range.from <= endBase && range.to >= startBase;
} else {
return range.to <= endBase && range.from >= startBase;
}
});
}
/**
Validates that a sequence name is present
@method validate
**/
validate(attrs = this.attributes) {
var errors = [];
if (!(attrs.name && attrs.name.replace(/\s/g, '').length)) {
errors.push('name');
}
return errors.length ? errors : undefined;
}
/**
@method maxOverlappingFeatures
@returns {integer}
**/
maxOverlappingFeatures() {
var ranges = _.flatten(_.pluck(this.attributes.features, 'ranges')),
previousRanges = [],
i = 0,
filterOverlappingRanges = function(ranges) {
return _.filter(ranges, function(range) {
return _.some(ranges, function(testRange) {
return range != testRange && range.from <= testRange.to && range.to >= testRange.from;
});
});
};
while(ranges.length > 1 && _.difference(ranges, previousRanges).length && i < 100) {
previousRanges = _.deepClone(ranges);
ranges = filterOverlappingRanges(ranges);
i++;
}
return i;
}
/**
@method featuresCountInRange
@returns {integer}
**/
nbFeaturesInRange(startBase, endBase) {
return _.filter(this.getFeatures(), function(feature) {
return _.some(feature.ranges, function(range) {
return range.from <= endBase && range.to >= startBase;
});
}).length;
}
insertBases(bases, beforeBase, options = {}){
var seq = super.get('sequence'),
stickyEndFormat = options.stickyEndFormat || this.getStickyEndFormat(),
adjustedBeforeBase,
timestamp;
options = _.defaults(options, {updateHistory: true});
// Adjust offset depending on sticky end format
var offset = this.getOffset(stickyEndFormat);
adjustedBeforeBase = beforeBase + offset;
this.set('sequence',
seq.substr(0, adjustedBeforeBase) +
bases +
seq.substr(adjustedBeforeBase, seq.length - (adjustedBeforeBase) + 1)
);
this.moveFeatures(beforeBase, bases.length, options);
if (options.updateHistory) {
timestamp = this.getHistory().add({
type: 'insert',
position: adjustedBeforeBase,
value: bases,
operation: '@' + adjustedBeforeBase + '+' + bases
}).get('timestamp');
}
this.throttledSave();
return timestamp;
}
moveBases(firstBase, length, newFirstBase, options = {}) {
var lastBase = firstBase + length - 1;
var featuresInRange, subSeq, deletionTimestamp, insertionTimestamp;
options = _.defaults(options, {updateHistory: true});
featuresInRange = _.deepClone(_.filter(this.getFeatures(), function(feature) {
return _.some(feature.ranges, function(range) {
return range.from >= firstBase && range.to <= lastBase;
});
}));
subSeq = this.getSubSeq(firstBase, lastBase);
deletionTimestamp = this.deleteBases(firstBase, length, options);
insertionTimestamp = this.insertBases(
subSeq,
newFirstBase < firstBase ?
newFirstBase :
newFirstBase - length,
options
);
_.each(featuresInRange, (feature) => {
feature.ranges = _.map(_.filter(feature.ranges, function(range) {
return range.from >= firstBase && range.to <= lastBase;
}), function(range) {
var offset = newFirstBase < firstBase ?
newFirstBase - firstBase :
newFirstBase - length - firstBase;
return {
from: range.from + offset,
to: range.to + offset
};
});
this.createFeature(feature, options);
});
}
/**
* @method changeBases
*
* @param {Integer} firstBase
* @param {String} newBases
* @param {Object} options={}, `stickyEndFormat`, `updateHistory`
* @return {TimeStamp}
*/
changeBases(firstBase, newBases, options={}) {
var timestamp;
var seq = this.getSequence(STICKY_END_FULL);
options = _.defaults(options, {updateHistory: true, stickyEndFormat: this.getStickyEndFormat()});
var adjustedFirstBase = firstBase + this.getOffset(options.stickyEndFormat);
var baseTo = adjustedFirstBase + newBases.length;
// var sequenceReplaced = this.getSubSeq(adjustedFirstBase, baseTo - 1, options.stickyEndFormat);
this.set('sequence',
seq.substr(0, adjustedFirstBase) +
newBases +
seq.substr(baseTo, seq.length - baseTo)
);
if (options.updateHistory) {
timestamp = this.getHistory().add({
type: 'change',
position: adjustedFirstBase,
value: newBases,
operation: '@' + adjustedFirstBase + '+' + newBases
}).get('timestamp');
}
this.throttledSave();
return timestamp;
}
insertBasesAndCreateFeatures(beforeBase, bases, features, options) {
var newFeatures = _.deepClone(_.isArray(features) ? features : [features]),
_this = this;
this.insertBases(bases, beforeBase, options);
_.each(newFeatures, function(feature) {
feature.ranges = [{
from: beforeBase,
to: beforeBase + bases.length - 1
}];
delete feature.from;
delete feature.to;
_this.createFeature(feature, options);
});
}
insertSequenceAndCreateFeatures(beforeBase, bases, features, options = {}) {
var newFeatures = _.deepClone(_.isArray(features) ? features : [features]),
_this = this;
this.insertBases(bases, beforeBase, options);
_.each(newFeatures, function(feature) {
feature.ranges = _.map(feature.ranges, function(range) {
return {
from: beforeBase + range.from,
to: beforeBase + range.to
};
});
_this.createFeature(feature, options);
});
}