-
Notifications
You must be signed in to change notification settings - Fork 1
/
adstrum.js
3487 lines (3078 loc) · 130 KB
/
adstrum.js
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
var Adstrum =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;;;
!(__WEBPACK_AMD_DEFINE_RESULT__ = function(require, exports, module){
var CSP = __webpack_require__(1),
FloatVariable = __webpack_require__(6),
IntegerVariable = __webpack_require__(14);
exports.CSP = CSP;
exports.FloatVariable = FloatVariable;
exports.IntegerVariable = IntegerVariable;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* Hold on to your butts, its a constraint solver in JavaScript.
*
* CSP is the constraint satisfaction problem class-- this holds the machinery
* for actually solving itself, but also all the bookkeeping.
* See readme.md for usage details.
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(2), __webpack_require__(3), __webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function(Inheritance, UndoStack, MemoTable){'use strict';
/**
* A function to replicate the common string.format() methods in other languages.
* Cribbed from:
* http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
* @param {String} string The format string to use
* @param {Array} args An array of the arguments to use for the format string
* @return {String} The format string, where format symbols have been replaced by args.
*/
function strFormat(string, args){
return string.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
}
var csp = Class.extend({
/**
* Constructor for the CSP class.
* @return {CSP} A new constraint satisifaction problem, ready to add
* variables and constraints to it.
*/
init : function(){
this.configurationPhase = true;
this.variables = [];
this.canonicalVariables = [];
this.constraints = [];
this.intervalUndoStack = new UndoStack();
this.choiceStack = [];
this.memoTable = new MemoTable();
this.nonUniqueVariables = [];
this.pending = [];
this.maxSteps = 1000;
this.currentConstraint = null; //start currentConstraint uninitialized
},
/**
* Returns the number of variables currently in the CSP
* @return {Number} The number of variables currently in the CSP
*/
variableCount : function(){
return this.variables.length;
},
/**
* Returns the number of constraints currently in the CSP
* @return {Number} The number of constraints currently in the CSP
*/
constraintCount : function(){
return this.constraintCount.length;
},
/**
* Get a new solution to the CSP. Note that the solution isn't returned--
* instead, all the various objects that the CSP points to have been modified such that
* all the required constraints hold true.
*
*/
newSolution : function(){
console.log("New Solution");
this.startSolutionPhase();
this.choiceStack.length = 0; //NOTE: if we can ensure that nothing else references choiceStack, then choiceStack = [] is faster
this.solverSteps = 0;
this.intervalUndoStack.restore(0);
//try{
this.clearPendingQueue();
//trying to eke out speed wherever we can, see
//http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
for (var index = 0, len = this.constraints.length; index < len; ++index){
this.pending.push(this.constraints[index]);
}
var fail = [false]; //pass by ref assurence. TODO: optimize
this.makeConsistent(fail);
if (fail[0]){
throw "Initial configuration is unsatisfiable.";
}
//trying to eke out speed wherever we can, see
//http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
for(var index = 0, len = this.canonicalVariables.length; index < len; ++index){
this.canonicalVariables[index].initializeStartingWidth();
}
var solutionGen = this.solutions();
if (solutionGen.next().done){
throw "No solution found";
}
/* }catch (e){
var retMsg = [];
for(var index = 0, len = this.choiceStack.length; index < len; ++index){
retMsg.push(this.choiceStack[index]);
retMsg.push("\n");
}
retMsg.push(e);
throw retMsg.join("");
} */
},
/**
* Generator that actually does the work of picking a variable, narrowing it, and checking CSP consistency.
* This is the core loop of solving the CSP.
* As with other methods, nothing is returned from solutions, only the objects that the CSP references are modified.
*/
solutions : function*(){
if (this.choiceStack.length > 200){
throw "Size is too big for Craft to handle!";
}
this.solverSteps = this.solverSteps + 1;
if (this.solverSteps > this.maxSteps){
throw "The Craft solver ran for too many steps";
}
var v = this.chooseVariable();
if (v === null){
yield true;
}else{
var mark = this.intervalUndoStack.markStack();
var varNarrower = v.tryNarrowing();
//use the generator's .done property to see when a particular variable
//can't be narrowed anymore.
while(!(varNarrower.next().done)){
var fail = [false]; //boolean pass by ref
this.makeConsistent(fail);
if (!fail[0]){
//recursively continue to search for a solution to the CSP.
var solutionGen = this.solutions();
while (!(solutionGen.next().done)) {
yield false;
}
}
this.popChoiceStack();
this.intervalUndoStack.restore(mark);
}
}
},
/**
* Push a choice on the CSP's choice stack.
* @param {String} format format string
* @param {List} args arguments to the format string
*/
pushChoice : function(format, args){
//this uses a String.format function. Doing so in Javascript is messsssssy
//see the helper function at the top of this Class
var choice = strFormat(format, args);
console.log(choice);
this.choiceStack.unshift(choice);
},
/**
* Pop a choice off of the choice stack.
*/
popChoiceStack : function(){
console.log("Fail: " + this.choiceStack[0]);
this.choiceStack.shift();
},
/**
* Pick the next variable to consider in the CSP. This can be done two ways:
* 1) Randomly
* 2) By heurisitic
* NOTE: Pre-alpha 0.11 uses the random version.
* Craft proper has a conditional compilation step, but that's not a thing
* in Javascript.
*/
chooseVariable : function(){
//This is the randomized variable choice option
this.nonUniqueVariables.length = 0; //NOTE: if I can ensure that nothing else will reference this, setting it equal to [] is faster
for(var index = 0, len = this.canonicalVariables.length; index < len; ++index){
if(!this.canonicalVariables[index].isUnique()){
this.nonUniqueVariables.push(this.canonicalVariables[index]);
}
}
if(this.nonUniqueVariables.length > 0){
return this.nonUniqueVariables[Math.floor(Math.random()*this.nonUniqueVariables.length)];
}else{
return null;
}
/**
This is the non-randomized variable choice option
var best = null;
var maxMeasure = 0;
for(index = 0, len = this.canonicalVariables.length; index < len; ++index){
var relativeMeasure = v.relativeMeasure;
if (relativeMeasure > maxMeasure){
maxMeasure = relativeMeasure;
best = v;
}
}
return best;
*/
},
/**
* Check the consistency of the CSP. This is a method mostly used for testing--
* as when makeConsistent fails it throws an error.
*/
testConsistency : function(){
this.startSolutionPhase();
this.pending.length = 0; //USUAL LINES ABOUT CLEARING ARRAYS
//trying to eke out speed wherever we can, see
//http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
for(var index = 0, len = this.constraints.length; index < len; ++index){
this.pending.push(this.constraints[index]);
}
var fail = [false];
this.makeConsistent(fail);
if(fail[0]){
throw "No solution";
}
},
/**
* Propigate each constraint through the CSP to ensure that all the correct
* properties still hold.
* @param {[boolean]} fail A boolean wrapped in an array so we can pass-by-ref for a primative
*/
makeConsistent : function(fail){
while(this.pending.length > 0){
var constraint = this.pending.shift();
constraint.queued = false;
this.currentConstraint = constraint;
console.log("Propagate " + constraint);
constraint.propagate(fail);
this.currentConstraint = null;
if(fail[0]){
this.clearPendingQueue();
return;
}
}
},
/**
* Check to see if a constraint is currently being propigated
* @param {Constraint} c The constraint to check against
* @return {boolean} true if c is currently being propigated, false otherwise
*/
currentlyPropagating : function(c){
return this.currentConstraint == c;
},
/**
* Add a constraint to the pending constraint queue
* @param {Constraint} c the constraint to add
*/
queueConstraint : function(c){
this.pending.push(c);
},
/**
* Clear out all constraints from the pending cosntraint queue, and also
* clear the currently propigating constraint.
*/
clearPendingQueue : function(){
this.currentConstraint = null;
while(this.pending.length > 0){
this.pending[0].queued = false;
this.pending.shift();
}
},
/**
* Move the CSP from the configuration phase to the solution phase. Have
* constraints register all required canonical variables (and also canonicalize all variables)
*/
startSolutionPhase : function(){
if(this.configurationPhase){
this.configurationPhase = false;
for(var index = 0, len = this.constraints.length; index < len; ++index){
this.constraints[index].canonicalizeVariables();
}
for(index = 0, len = this.variables.length; index < len; ++index){
if(this.variables[index].isCanonical()){
this.canonicalVariables.push(this.variables[index]);
}
}
}
//FIXME: there is currently a bug somewhere where constraint.narrowedVariable is getting
//held over from problem to problem. This is a stopgap fix for now.
for(var index = 0, len = this.constraints.length; index < len; ++index){
this.constraints[index].narrowedVariable = null;
}
},
//Some asserts to throw errors if we're not in the correct phase for the stunt
assertConfigurationPhase : function(){
if(!this.configurationPhase){
throw "Operation can only be performed before solving.";
}
},
assertSolvingPhase : function(){
if(this.configurationPhase){
throw "Operation can only be performed during solving.";
}
},
/**
* Add a function to this CSP's memo table. Function memorization maps
* a function name & args to a function value, so the function only needs
* to be computed once.
* Only the first value is memorized, so if a function could return something different with the same args,
* it will not be memorized correctly.
* @param {String} functionName The function name
* @param {Function} func The function to memorize
* @param {List} args A list of arguments to pass to the function
* @return {Object} The memorized value of the function with the provided params
*/
memorize : function(functionName, func, args){
return this.memoTable.memorize(functionName, func, args);
}
});
return csp;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 2 */
/***/ function(module, exports) {
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
function extend(destination, source) {
for (var k in source) {
if (source.hasOwnProperty(k)) {
destination[k] = source[k];
}
}
return destination;
}
// Inspired by base2 and Prototype
(function() {
var initializing = false, fnTest = /xyz/.test(function() { xyz;
}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function() {
};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn) {
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) : prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if (!initializing && this.init)
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
*Definition of an undoStack form Craft
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(2)], __WEBPACK_AMD_DEFINE_RESULT__ = function(Inheritance){
//private things up here
var initialStackSize = 128;
//private inner structure. Using a constructor to give initial values to things
var StackBlock = function(vari){
this.oldFrame = vari.lastSaveFrame;
this.savedValue = vari.realValue;
this.variable = vari;
};
var UndoStack = Class.extend({
init : function(vari){
this.undoDataStack = []; //This needs to be of type StackBlock (these elements are stack blocks)
this.undoStackPointer = 0;
this.framePointer = 0;
},
markStack : function(){
this.framePointer = this.undoStackPointer;
return this.framePointer;
},
restore : function(frame){
while(this.undoStackPointer > frame){
this.undoStackPointer = this.undoStackPointer - 1;
var popped = this.undoDataStack[this.undoStackPointer];
var v = popped.variable;
v.realValue = popped.savedValue;
v.lastSaveFrame = popped.oldFrame;
}
this.framePointer = frame;
},
//this really needs to be private
//this also doesn't make sense to exist, given that this is Javascript
ensureSpace : function(){
console.log("EnsureSpace doesn't do anything in JavaScript, because that's how JavaScript rolls.");
},
maybeSave : function(rest){
if(rest.lastSaveFrame != this.framePointer){
console.log("Save " + this.undoStackPointer + " <- " + rest.realValue);
this.undoDataStack[this.undoStackPointer] = new StackBlock(rest);
this.undoStackPointer = this.undoStackPointer + 1;
rest.lastSaveFrame = this.framePointer;
}
}
});
return UndoStack;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* Implementation of a memory table in Javascript
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(2), __webpack_require__(5)], __WEBPACK_AMD_DEFINE_RESULT__ = function(Inheritance, Dictionary){'use strict';
//Defining an 'inner class' here-- tuple isn't returned from this chunk, so it's only visible to the MemoTable.
var Tuple = Class.extend({
init : function(args){
var compiled = [];
for (var i = 0; i < args.length; i++){
compiled.push(args[i]);
}
this.data = compiled;
},
equals : function(t){
if(t === null || t.data.length != this.data.length){
return false;
}else{
for(var index = 0, len = t.data.length; index < len; ++index){
if(t.data[index] != this.data[index]){ //yes, this means that it won't work for objects. I get it.
return false;
}
}
return true;
}
},
/**
* Javascript doesn't use hash codes?
*/
getHashCode : function(){
console.log("GetHashCode is not implemented...");
}
});
var MemoTable = Class.extend({
init : function(){
this.cache = {};
},
memorize : function(functionName, funct, args){
var tuple = new Tuple(args);
var table = this.cache[functionName];
if(table){
var memorizedValue = table.get(tuple);
if(memorizedValue){
return memorizedValue;
}
}else{
table = new Dictionary();
this.cache[functionName] = table;
}
memorizedValue = funct();
table.put(tuple, memorizedValue);
return memorizedValue;
}
});
return MemoTable;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/**
* Lightweight 'equals' dictionary. The diectionary expects its keys to have an
* equals method.
*/
!(__WEBPACK_AMD_DEFINE_RESULT__ = function(){
var dict = function Dictionary(overwrite){
this.overwrite = overwrite === true;
var __k = [];
var __v = [];
findKey = function(key){
if (key.__proto__.hasOwnProperty('equals')){
for(var i = 0; i < __k.length; i++){
if(key.equals(__k[i])){
return i;
}
}
return -1;
}else{
return __k.indexOf(key);
}
};
this.put = function(key, value){
idx = findKey(key);
if(!this.overwrite || idx === -1){
__k.push(key);
__v.push(value);
}
};
this.get = function(key){
var idx = findKey(key);
if(idx >= 0){
return __v[idx];
}
return null;
};
this.remove = function(key){
var i = __k.indexOf(key);
if(i != -1){
__k.splice(i,1);
__v.splice(i,1);
}
};
this.clearAll = function(value){
for(var i = 0; i < __v.length; i++){
if(__v[i] == value){
__k.splice(i,1);
__v.splice(i,1);
}
}
};
this.iterate = function(func){
for(var i = 0; i < __k.length; i++){
func(__k[i], __v[i]);
}
};
};
return dict;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* A floating point variable in Craft
* This class not only creates new Floating Variables for Scalar Arithmatic in Craft, but also
* handles performing common scalar arithmatic operations to floating variables
*/
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(2), __webpack_require__(7), __webpack_require__(9), __webpack_require__(11), __webpack_require__(12)], __WEBPACK_AMD_DEFINE_RESULT__ = function(Inheritance, Variable, Interval, MathUtil, ScalarArithmaticConstraints){
//For ease of reference later, split the properties of the ScalarArithmaticConstraints
//module.
SumConstraint = ScalarArithmaticConstraints.SumConstraint;
DifferenceConstraint = ScalarArithmaticConstraints.DifferenceConstraint;
ProductConstraint = ScalarArithmaticConstraints.ProductConstraint;
ConstantProductConstraint = ScalarArithmaticConstraints.ConstantProductConstraint;
QuotientConstraint = ScalarArithmaticConstraints.QuotientConstraint;
PowerConstraint = ScalarArithmaticConstraints.PowerConstraint;
//'Static' method constructors for making common variations on a Floating Point Variable.
/**
* 'Static' method for making a float variable with infinate bounds.
* @param {String} name name of the float var
* @param {CSP} p constraint satisifaction problem to assoiate this variable
* with
* @return {FloatVariable} new Float Variable with inf bounds
*/
var makeInfinateFloatVariable = function(name, p){
return new FloatVariable(name, p, Interval.allValues);
};
/**
* 'Static' method for making a float variable with two provided bounds
* @param {String} name Name of the float variable
* @param {CSP} p Constraint Satisifaction Problem to associate the
* the float var with
* @param {Number} lower The lower bound of this float variable
* @param {Number} upper The upper bound of this float variable
* @return {FloatVariable} new float variable in range [lower, upper]
*/
var makeFloatVariableWithBounds = function(name, p, lower, upper){
return new FloatVariable(name, p, new Interval(lower, upper));
};
/**
* 'Static' method for memorizing a 'make constant' function.
*
* @TODO: this is currently unused by Craftjs, untested, and mostly still a stub.
* @param {CSP} p The constraint satisifaction problem to associate this constant with
* @param {Number} c The value of the constant to create
* @return {FloatVariable} the memorized value for the 'constant' function in the CSP's memo table.
* which will be a Float Variable with the correct bounds.
*/
var makeFloatConstant = function(name, p, c){
var funct = function(){return makeFloatVariableWithBounds(name, p, c, c);};
return p.memorize("constant", funct, [c]);
};
var FloatVariable = Variable.extend({
/**
* Create a new Float Varible and register that float variable with a CSP
*
* @param {String} name Name of the float variable
* @param {CSP} p Constraint satisfaction problem to associate with this float variable
* @param {Interval} initialValue Initial bounds of this float variable
* @return {FloatVariable} A new float variable to use with the CSP
*/
init : function(name, p, initialValue){
this._super(name, p, p.intervalUndoStack, initialValue);
this.startingWidth = 0;
},
/**
* Set the starting width of this float variable
*/
initializeStartingWidth : function(){
this.startingWidth = this.value().width();
},
/**
* Get a relative measure of how shrunk this floating variable has become,
* based on its current width vs its starting width
* @return {Number} the relative shrunkenness of this floating variable
*/
relativeMeasure : function(){
return this.value().width() / this.startingWidth;
},
/**
* Add a constraint that this float variable must equal the passed in
* parameter
* @param {Number or Variable} v the variable/Number that this float var
* must equal
*/
mustEqual : function(v){
if (v instanceof Variable){
v.mustBeContainedInInterval(this.value());
this._super(v);
}else if (v.constructor === Number){
//This is our final condition-- also Javascript is awesome
this.mustBeContainedInInterval(new Interval(v, v));
}
},
/**
* Adds a constraint that this float variable must stay in the range
* [lower, upper]
* @param {Number} low Lower Bound of this float variable
* @param {Number} high Upper Bound of this float variable
*/
mustBeContainedInRange : function(low, high){
this.mustBeContainedInInterval(new Interval(low, high));
},
/**
* Adds a constraint that this float variable must be greater than or
* equal to the provided parameter
* This is equivelent to mustBeContainedInRange(low, Number.POSITIVE_INFINITY)
* @param {Variable or Number} low The lower bound, what we're constraining this variable to equal or be greater than
*/
mustBeGreaterThanOrEqualTo : function(low){
if (low instanceof Variable){
this.mustBeContainedInRange(low.value().upper, Number.POSITIVE_INFINITY);
}else if (low.constructor === Number){
this.mustBeContainedInInterval(new Interval(low, Number.POSITIVE_INFINITY));
}
},
/**
* Adds a constraint that this float variable must be less than or
* equal to the provided parameter
* This is equivelent to mustBeContainedInRange(Number.NEGATIVE_INFINITY, high)
* @param {Variable or Number} high the upper bound, we're constraining the float variable to be equal to or less than
* this number
*/
mustBeLessThanOrEqualTo : function(high){
if (high instanceof Variable){
this.mustBeContainedInRange(Number.NEGATIVE_INFINITY, high.value().lower);
}else if (high.constructor === Number){
this.mustBeContainedInInterval(new Interval(Number.NEGATIVE_INFINITY, high));
}
},
/**
* Add a constraint that this float variable must be contained by a particular
* interval
* Although this function can be used externally, is intended to not be.
* This keeps Craftjs from ever having to expose the Interval object / class
* @param {Interval} i the bounds that this variable must be in ([i.lower(), i.upper()])
*/
mustBeContainedInInterval : function(i){
this.csp.assertConfigurationPhase();
var intersection = Interval.intersection(this.value(), i);
if(intersection.empty()){
throw "Argument out of current range of variable";
}
this.currentValue.setInitialValue(intersection);
},
/**
* Narrow the range of this float variable to the passed in restriction.
* @param {Interval} restriction The range to narrow this float variable down to
* @param {[boolean]} fail pass-by-ref failure bool (will be set to true if we can't narrow)
*/
narrowTo : function(restriction, fail){
if(this.value().isUnique()){
if(restriction.nearlyContains(this.value(), MathUtil.defaultEpsilon)){
return;
}else{
fail[0] = true;
console.log(this.name + ": " + this.value() + " -> Empty " + restriction);
return;
}
}
var oldValue = this.value();
if(!restriction.contains(this.value())){
var newValue = Interval.intersection(this.value(), restriction);
if(newValue.nearlyUnique()){
var mid = newValue.midpoint();
newValue = new Interval(mid, mid);
}
console.log(this.name + ": " + oldValue + " -> " + newValue + " " + restriction +
", narrowed by " + (100 * (1-newValue.width() /oldValue.width())));
if(newValue.empty()){
fail[0] = true;
}else{
var propagate = (newValue.width() / this.value().width()) < 0.99;
//console.log(this.canonicalVariable());
this.canonicalVariable().currentValue.set(newValue);
if(propagate){
for(var index = 0, len = this.constraints.length; index < len; index++){
this.constraints[index].queuePropigation(this);
}
}
}
}
},
/**
* Narrow this float var to the union of the intersections of the provided intervals
* @param {Interval} a The first interval
* @param {Interval} b The second interval
* @param {[boolean]} fail pass-by-ref failure bool (will be set to true if we can't narrow)
*/
narrowToUnion : function(a, b, fail){
this.narrowTo(Interval.unionOfIntersections(this.value(), a, b), fail);
},
/**
* Narrow the current variable down to the quotient of the passed in args.
* @param {Interval} numerator Range of the numerator
* @param {Interval} denominator Range of the denominator
* @param {[boolean]} fail pass-by-ref failure bool (will be set to true if we can't narrow)
*/
narrowToQuotient : function(numerator, denominator, fail){
//ok, presenting a simplified version of this
//fast checks -- if the denominator is zero and the number
if(denominator.isZero()){
//Denominator is [0,0], so quotent is the empty set
fail[0] = !numerator.containsZero();
return;
}
if(numerator.isZero()){
if(!denominator.containsZero()){
//Quotent is [0,0].
this.narrowTo(new Interval(0,0), fail);
return;
}
}
if(!denominator.containsZero()){
//check to see if we'll overflow JS here-- if so, fail fast
if(1 / denominator.lower === Number.POSITIVE_INFINITY || 1 / denominator.upper === Number.POSITIVE_INFINITY ||
1 / denominator.lower === Number.NEGATIVE_INFINITY || 1 / denominator.upper === Number.NEGATIVE_INFINITY){
fail[0] = true;
return;
}
this.narrowTo(Interval.multiply(numerator, denominator.reciprocal()), fail);
return;
}
//three cases: crosses zero, [a, 0] and [0, b]
if(denominator.lower === 0){
if (numerator.upper < 0){
this.narrowTo(new Interval(Number.NEGATIVE_INFINITY, numerator.upper / denominator.upper), fail);
}else if(numerator.lower >= 0){
this.narrowTo(new Interval(numerator.lower / denominator.upper, Number.POSITIVE_INFINITY), fail);
}
return;
}
if(denominator.upper === 0){
if(numerator.upper <= 0){
this.narrowTo(new Interval(numerator.upper / denominator.lower, Number.POSITIVE_INFINITY), fail);
}else if(numerator.lower > 0){
this.narrowTo(new Interval(Number.NEGATIVE_INFINITY, numerator.lower / denominator.lower), fail);
}
return;
}
if(numerator.upper < 0){
var lowerHalf = new Interval(Number.NEGATIVE_INFINITY, numerator.upper / denominator.upper);
var upperHalf = new Interval(numerator.upper / denominator.lower, Number.POSITIVE_INFINITY);
this.narrowToUnion(lowerHalf, upperHalf, fail);
return;
}
if(numerator.lower > 0){
var lowerHalf = new Interval(Number.NEGATIVE_INFINITY, numerator.lower / denominator.lower);
var upperHalf = new Interval(numerator.lower / denominator.upper, Number.POSITIVE_INFINITY);
this.narrowToUnion(lowerHalf, upperHalf, fail);
return;
}
return;
},
/**
* Narrow this float variable to the signed square root of the provided bounds
* @param {Interval} square the range of the square
* @param {[boolean]} fail pass-by-ref failure bool (will be set to true if we can't narrow)
*/
narrowToSignedSqrt : function(square, fail){
var lower = Math.max(0, square.lower);
var upper = square.upper;
if(upper < 0){
fail[0] = true;
return;
}
var sqrt = new Interval(Math.sqrt(lower), Math.sqrt(upper));
var restriction;
if (this.value().crossesZero()){
restriction = Interval.unionOfIntersections(this.value(), sqrt, Interval.invert(sqrt));
}else if(this.value().isZero()){
//this value is zero, so don't do anything. We need this before the strict
//negative check to catch cases like [x, 0] and miss [0,0], which is
//unsigned.
restriction = sqrt;
}else if(this.value().upper <= 0){
//current value is strictly negative
restriction = Interval.invert(sqrt);
}else{
//current value is strictly positive ([0, x] or greater).
restriction = sqrt;
}
this.narrowTo(restriction, fail);
},
/**
* Generator (because execution pausing) to try and narrow down a float
* variable to either a single value, or a range. This is the core of
* Craft's 'optimistic' guessing-- start by narrowing a float variable
* to a single value, see if it works. If it does, awesome. If not, then
* either try again with [var.lower, guessed val] or [guessed val, var.upper]
*
* If the range picked doesn't work, try the other one.
*/