deltablue.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. // Copyright 2013 the V8 project authors. All rights reserved.
  2. // Redistribution and use in source and binary forms, with or without
  3. // modification, are permitted provided that the following conditions are
  4. // met:
  5. //
  6. // * Redistributions of source code must retain the above copyright
  7. // notice, this list of conditions and the following disclaimer.
  8. // * Redistributions in binary form must reproduce the above
  9. // copyright notice, this list of conditions and the following
  10. // disclaimer in the documentation and/or other materials provided
  11. // with the distribution.
  12. // * Neither the name of Google Inc. nor the names of its
  13. // contributors may be used to endorse or promote products derived
  14. // from this software without specific prior written permission.
  15. //
  16. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  17. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  18. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  19. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  20. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  22. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. // Performance.now is used in latency benchmarks, the fallback is Date.now.
  28. var performance = performance || {};
  29. performance.now = (function() {
  30. return performance.now ||
  31. performance.mozNow ||
  32. performance.msNow ||
  33. performance.oNow ||
  34. performance.webkitNow ||
  35. Date.now;
  36. })();
  37. // Simple framework for running the benchmark suites and
  38. // computing a score based on the timing measurements.
  39. // A benchmark has a name (string) and a function that will be run to
  40. // do the performance measurement. The optional setup and tearDown
  41. // arguments are functions that will be invoked before and after
  42. // running the benchmark, but the running time of these functions will
  43. // not be accounted for in the benchmark score.
  44. function Benchmark(name, doWarmup, doDeterministic, deterministicIterations,
  45. run, setup, tearDown, rmsResult, minIterations) {
  46. this.name = name;
  47. this.doWarmup = doWarmup;
  48. this.doDeterministic = doDeterministic;
  49. this.deterministicIterations = deterministicIterations;
  50. this.run = run;
  51. this.Setup = setup ? setup : function() { };
  52. this.TearDown = tearDown ? tearDown : function() { };
  53. this.rmsResult = rmsResult ? rmsResult : null;
  54. this.minIterations = minIterations ? minIterations : 32;
  55. }
  56. // Benchmark results hold the benchmark and the measured time used to
  57. // run the benchmark. The benchmark score is computed later once a
  58. // full benchmark suite has run to completion. If latency is set to 0
  59. // then there is no latency score for this benchmark.
  60. function BenchmarkResult(benchmark, time, latency) {
  61. this.benchmark = benchmark;
  62. this.time = time;
  63. this.latency = latency;
  64. }
  65. // Automatically convert results to numbers. Used by the geometric
  66. // mean computation.
  67. BenchmarkResult.prototype.valueOf = function() {
  68. return this.time;
  69. }
  70. // Suites of benchmarks consist of a name and the set of benchmarks in
  71. // addition to the reference timing that the final score will be based
  72. // on. This way, all scores are relative to a reference run and higher
  73. // scores implies better performance.
  74. function BenchmarkSuite(name, reference, benchmarks) {
  75. this.name = name;
  76. this.reference = reference;
  77. this.benchmarks = benchmarks;
  78. BenchmarkSuite.suites.push(this);
  79. }
  80. // Keep track of all declared benchmark suites.
  81. BenchmarkSuite.suites = [];
  82. // Scores are not comparable across versions. Bump the version if
  83. // you're making changes that will affect that scores, e.g. if you add
  84. // a new benchmark or change an existing one.
  85. BenchmarkSuite.version = '9';
  86. // Defines global benchsuite running mode that overrides benchmark suite
  87. // behavior. Intended to be set by the benchmark driver. Undefined
  88. // values here allow a benchmark to define behaviour itself.
  89. BenchmarkSuite.config = {
  90. doWarmup: undefined,
  91. doDeterministic: undefined
  92. };
  93. // Override the alert function to throw an exception instead.
  94. alert = function(s) {
  95. throw "Alert called with argument: " + s;
  96. };
  97. // To make the benchmark results predictable, we replace Math.random
  98. // with a 100% deterministic alternative.
  99. BenchmarkSuite.ResetRNG = function() {
  100. Math.random = (function() {
  101. var seed = 49734321;
  102. return function() {
  103. // Robert Jenkins' 32 bit integer hash function.
  104. seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
  105. seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
  106. seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
  107. seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
  108. seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
  109. seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
  110. return (seed & 0xfffffff) / 0x10000000;
  111. };
  112. })();
  113. }
  114. // Runs all registered benchmark suites and optionally yields between
  115. // each individual benchmark to avoid running for too long in the
  116. // context of browsers. Once done, the final score is reported to the
  117. // runner.
  118. BenchmarkSuite.RunSuites = function(runner, skipBenchmarks) {
  119. skipBenchmarks = typeof skipBenchmarks === 'undefined' ? [] : skipBenchmarks;
  120. var continuation = null;
  121. var suites = BenchmarkSuite.suites;
  122. var length = suites.length;
  123. BenchmarkSuite.scores = [];
  124. var index = 0;
  125. function RunStep() {
  126. while (continuation || index < length) {
  127. if (continuation) {
  128. continuation = continuation();
  129. } else {
  130. var suite = suites[index++];
  131. if (runner.NotifyStart) runner.NotifyStart(suite.name);
  132. if (skipBenchmarks.indexOf(suite.name) > -1) {
  133. suite.NotifySkipped(runner);
  134. } else {
  135. continuation = suite.RunStep(runner);
  136. }
  137. }
  138. if (continuation && typeof window != 'undefined' && window.setTimeout) {
  139. window.setTimeout(RunStep, 25);
  140. return;
  141. }
  142. }
  143. // show final result
  144. if (runner.NotifyScore) {
  145. var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores);
  146. var formatted = BenchmarkSuite.FormatScore(100 * score);
  147. runner.NotifyScore(formatted);
  148. }
  149. }
  150. RunStep();
  151. }
  152. // Counts the total number of registered benchmarks. Useful for
  153. // showing progress as a percentage.
  154. BenchmarkSuite.CountBenchmarks = function() {
  155. var result = 0;
  156. var suites = BenchmarkSuite.suites;
  157. for (var i = 0; i < suites.length; i++) {
  158. result += suites[i].benchmarks.length;
  159. }
  160. return result;
  161. }
  162. // Computes the geometric mean of a set of numbers.
  163. BenchmarkSuite.GeometricMean = function(numbers) {
  164. var log = 0;
  165. for (var i = 0; i < numbers.length; i++) {
  166. log += Math.log(numbers[i]);
  167. }
  168. return Math.pow(Math.E, log / numbers.length);
  169. }
  170. // Computes the geometric mean of a set of throughput time measurements.
  171. BenchmarkSuite.GeometricMeanTime = function(measurements) {
  172. var log = 0;
  173. for (var i = 0; i < measurements.length; i++) {
  174. log += Math.log(measurements[i].time);
  175. }
  176. return Math.pow(Math.E, log / measurements.length);
  177. }
  178. // Computes the geometric mean of a set of rms measurements.
  179. BenchmarkSuite.GeometricMeanLatency = function(measurements) {
  180. var log = 0;
  181. var hasLatencyResult = false;
  182. for (var i = 0; i < measurements.length; i++) {
  183. if (measurements[i].latency != 0) {
  184. log += Math.log(measurements[i].latency);
  185. hasLatencyResult = true;
  186. }
  187. }
  188. if (hasLatencyResult) {
  189. return Math.pow(Math.E, log / measurements.length);
  190. } else {
  191. return 0;
  192. }
  193. }
  194. // Converts a score value to a string with at least three significant
  195. // digits.
  196. BenchmarkSuite.FormatScore = function(value) {
  197. if (value > 100) {
  198. return value.toFixed(0);
  199. } else {
  200. return value.toPrecision(3);
  201. }
  202. }
  203. // Notifies the runner that we're done running a single benchmark in
  204. // the benchmark suite. This can be useful to report progress.
  205. BenchmarkSuite.prototype.NotifyStep = function(result) {
  206. this.results.push(result);
  207. if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name);
  208. }
  209. // Notifies the runner that we're done with running a suite and that
  210. // we have a result which can be reported to the user if needed.
  211. BenchmarkSuite.prototype.NotifyResult = function() {
  212. var mean = BenchmarkSuite.GeometricMeanTime(this.results);
  213. var score = this.reference[0] / mean;
  214. BenchmarkSuite.scores.push(score);
  215. if (this.runner.NotifyResult) {
  216. var formatted = BenchmarkSuite.FormatScore(100 * score);
  217. this.runner.NotifyResult(this.name, formatted);
  218. }
  219. if (this.reference.length == 2) {
  220. var meanLatency = BenchmarkSuite.GeometricMeanLatency(this.results);
  221. if (meanLatency != 0) {
  222. var scoreLatency = this.reference[1] / meanLatency;
  223. BenchmarkSuite.scores.push(scoreLatency);
  224. if (this.runner.NotifyResult) {
  225. var formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
  226. this.runner.NotifyResult(this.name + "Latency", formattedLatency);
  227. }
  228. }
  229. }
  230. }
  231. BenchmarkSuite.prototype.NotifySkipped = function(runner) {
  232. BenchmarkSuite.scores.push(1); // push default reference score.
  233. if (runner.NotifyResult) {
  234. runner.NotifyResult(this.name, "Skipped");
  235. }
  236. }
  237. // Notifies the runner that running a benchmark resulted in an error.
  238. BenchmarkSuite.prototype.NotifyError = function(error) {
  239. if (this.runner.NotifyError) {
  240. this.runner.NotifyError(this.name, error);
  241. }
  242. if (this.runner.NotifyStep) {
  243. this.runner.NotifyStep(this.name);
  244. }
  245. }
  246. // Runs a single benchmark for at least a second and computes the
  247. // average time it takes to run a single iteration.
  248. BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark, data) {
  249. var config = BenchmarkSuite.config;
  250. var doWarmup = config.doWarmup !== undefined
  251. ? config.doWarmup
  252. : benchmark.doWarmup;
  253. var doDeterministic = config.doDeterministic !== undefined
  254. ? config.doDeterministic
  255. : benchmark.doDeterministic;
  256. function Measure(data) {
  257. var elapsed = 0;
  258. var start = new Date();
  259. // Run either for 1 second or for the number of iterations specified
  260. // by minIterations, depending on the config flag doDeterministic.
  261. for (var i = 0; (doDeterministic ?
  262. i<benchmark.deterministicIterations : elapsed < 1000); i++) {
  263. benchmark.run();
  264. elapsed = new Date() - start;
  265. }
  266. if (data != null) {
  267. data.runs += i;
  268. data.elapsed += elapsed;
  269. }
  270. }
  271. // Sets up data in order to skip or not the warmup phase.
  272. if (!doWarmup && data == null) {
  273. data = { runs: 0, elapsed: 0 };
  274. }
  275. if (data == null) {
  276. Measure(null);
  277. return { runs: 0, elapsed: 0 };
  278. } else {
  279. Measure(data);
  280. // If we've run too few iterations, we continue for another second.
  281. if (data.runs < benchmark.minIterations) return data;
  282. var usec = (data.elapsed * 1000) / data.runs;
  283. var rms = (benchmark.rmsResult != null) ? benchmark.rmsResult() : 0;
  284. this.NotifyStep(new BenchmarkResult(benchmark, usec, rms));
  285. return null;
  286. }
  287. }
  288. // This function starts running a suite, but stops between each
  289. // individual benchmark in the suite and returns a continuation
  290. // function which can be invoked to run the next benchmark. Once the
  291. // last benchmark has been executed, null is returned.
  292. BenchmarkSuite.prototype.RunStep = function(runner) {
  293. BenchmarkSuite.ResetRNG();
  294. this.results = [];
  295. this.runner = runner;
  296. var length = this.benchmarks.length;
  297. var index = 0;
  298. var suite = this;
  299. var data;
  300. // Run the setup, the actual benchmark, and the tear down in three
  301. // separate steps to allow the framework to yield between any of the
  302. // steps.
  303. function RunNextSetup() {
  304. if (index < length) {
  305. try {
  306. suite.benchmarks[index].Setup();
  307. } catch (e) {
  308. suite.NotifyError(e);
  309. return null;
  310. }
  311. return RunNextBenchmark;
  312. }
  313. suite.NotifyResult();
  314. return null;
  315. }
  316. function RunNextBenchmark() {
  317. try {
  318. data = suite.RunSingleBenchmark(suite.benchmarks[index], data);
  319. } catch (e) {
  320. suite.NotifyError(e);
  321. return null;
  322. }
  323. // If data is null, we're done with this benchmark.
  324. return (data == null) ? RunNextTearDown : RunNextBenchmark();
  325. }
  326. function RunNextTearDown() {
  327. try {
  328. suite.benchmarks[index++].TearDown();
  329. } catch (e) {
  330. suite.NotifyError(e);
  331. return null;
  332. }
  333. return RunNextSetup;
  334. }
  335. // Start out running the setup.
  336. return RunNextSetup();
  337. }
  338. // Copyright 2008 the V8 project authors. All rights reserved.
  339. // Copyright 1996 John Maloney and Mario Wolczko.
  340. // This program is free software; you can redistribute it and/or modify
  341. // it under the terms of the GNU General Public License as published by
  342. // the Free Software Foundation; either version 2 of the License, or
  343. // (at your option) any later version.
  344. //
  345. // This program is distributed in the hope that it will be useful,
  346. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  347. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  348. // GNU General Public License for more details.
  349. //
  350. // You should have received a copy of the GNU General Public License
  351. // along with this program; if not, write to the Free Software
  352. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  353. // This implementation of the DeltaBlue benchmark is derived
  354. // from the Smalltalk implementation by John Maloney and Mario
  355. // Wolczko. Some parts have been translated directly, whereas
  356. // others have been modified more aggresively to make it feel
  357. // more like a JavaScript program.
  358. var DeltaBlue = new BenchmarkSuite('DeltaBlue', [66118], [
  359. new Benchmark('DeltaBlue', true, false, 4400, deltaBlue)
  360. ]);
  361. /**
  362. * A JavaScript implementation of the DeltaBlue constraint-solving
  363. * algorithm, as described in:
  364. *
  365. * "The DeltaBlue Algorithm: An Incremental Constraint Hierarchy Solver"
  366. * Bjorn N. Freeman-Benson and John Maloney
  367. * January 1990 Communications of the ACM,
  368. * also available as University of Washington TR 89-08-06.
  369. *
  370. * Beware: this benchmark is written in a grotesque style where
  371. * the constraint model is built by side-effects from constructors.
  372. * I've kept it this way to avoid deviating too much from the original
  373. * implementation.
  374. */
  375. /* --- O b j e c t M o d e l --- */
  376. Object.defineProperty(Object.prototype, "inheritsFrom", {
  377. value: function (shuper) {
  378. function Inheriter() { }
  379. Inheriter.prototype = shuper.prototype;
  380. this.prototype = new Inheriter();
  381. this.superConstructor = shuper;
  382. }
  383. });
  384. function OrderedCollection() {
  385. this.elms = new Array();
  386. }
  387. OrderedCollection.prototype.add = function (elm) {
  388. this.elms.push(elm);
  389. }
  390. OrderedCollection.prototype.at = function (index) {
  391. return this.elms[index];
  392. }
  393. OrderedCollection.prototype.size = function () {
  394. return this.elms.length;
  395. }
  396. OrderedCollection.prototype.removeFirst = function () {
  397. return this.elms.pop();
  398. }
  399. OrderedCollection.prototype.remove = function (elm) {
  400. var index = 0, skipped = 0;
  401. for (var i = 0; i < this.elms.length; i++) {
  402. var value = this.elms[i];
  403. if (value != elm) {
  404. this.elms[index] = value;
  405. index++;
  406. } else {
  407. skipped++;
  408. }
  409. }
  410. for (var i = 0; i < skipped; i++)
  411. this.elms.pop();
  412. }
  413. /* --- *
  414. * S t r e n g t h
  415. * --- */
  416. /**
  417. * Strengths are used to measure the relative importance of constraints.
  418. * New strengths may be inserted in the strength hierarchy without
  419. * disrupting current constraints. Strengths cannot be created outside
  420. * this class, so pointer comparison can be used for value comparison.
  421. */
  422. function Strength(strengthValue, name) {
  423. this.strengthValue = strengthValue;
  424. this.name = name;
  425. }
  426. Strength.stronger = function (s1, s2) {
  427. return s1.strengthValue < s2.strengthValue;
  428. }
  429. Strength.weaker = function (s1, s2) {
  430. return s1.strengthValue > s2.strengthValue;
  431. }
  432. Strength.weakestOf = function (s1, s2) {
  433. return this.weaker(s1, s2) ? s1 : s2;
  434. }
  435. Strength.strongest = function (s1, s2) {
  436. return this.stronger(s1, s2) ? s1 : s2;
  437. }
  438. Strength.prototype.nextWeaker = function () {
  439. switch (this.strengthValue) {
  440. case 0: return Strength.WEAKEST;
  441. case 1: return Strength.WEAK_DEFAULT;
  442. case 2: return Strength.NORMAL;
  443. case 3: return Strength.STRONG_DEFAULT;
  444. case 4: return Strength.PREFERRED;
  445. case 5: return Strength.REQUIRED;
  446. }
  447. }
  448. // Strength constants.
  449. Strength.REQUIRED = new Strength(0, "required");
  450. Strength.STONG_PREFERRED = new Strength(1, "strongPreferred");
  451. Strength.PREFERRED = new Strength(2, "preferred");
  452. Strength.STRONG_DEFAULT = new Strength(3, "strongDefault");
  453. Strength.NORMAL = new Strength(4, "normal");
  454. Strength.WEAK_DEFAULT = new Strength(5, "weakDefault");
  455. Strength.WEAKEST = new Strength(6, "weakest");
  456. /* --- *
  457. * C o n s t r a i n t
  458. * --- */
  459. /**
  460. * An abstract class representing a system-maintainable relationship
  461. * (or "constraint") between a set of variables. A constraint supplies
  462. * a strength instance variable; concrete subclasses provide a means
  463. * of storing the constrained variables and other information required
  464. * to represent a constraint.
  465. */
  466. function Constraint(strength) {
  467. this.strength = strength;
  468. }
  469. /**
  470. * Activate this constraint and attempt to satisfy it.
  471. */
  472. Constraint.prototype.addConstraint = function () {
  473. this.addToGraph();
  474. planner.incrementalAdd(this);
  475. }
  476. /**
  477. * Attempt to find a way to enforce this constraint. If successful,
  478. * record the solution, perhaps modifying the current dataflow
  479. * graph. Answer the constraint that this constraint overrides, if
  480. * there is one, or nil, if there isn't.
  481. * Assume: I am not already satisfied.
  482. */
  483. Constraint.prototype.satisfy = function (mark) {
  484. this.chooseMethod(mark);
  485. if (!this.isSatisfied()) {
  486. if (this.strength == Strength.REQUIRED)
  487. alert("Could not satisfy a required constraint!");
  488. return null;
  489. }
  490. this.markInputs(mark);
  491. var out = this.output();
  492. var overridden = out.determinedBy;
  493. if (overridden != null) overridden.markUnsatisfied();
  494. out.determinedBy = this;
  495. if (!planner.addPropagate(this, mark))
  496. alert("Cycle encountered");
  497. out.mark = mark;
  498. return overridden;
  499. }
  500. Constraint.prototype.destroyConstraint = function () {
  501. if (this.isSatisfied()) planner.incrementalRemove(this);
  502. else this.removeFromGraph();
  503. }
  504. /**
  505. * Normal constraints are not input constraints. An input constraint
  506. * is one that depends on external state, such as the mouse, the
  507. * keybord, a clock, or some arbitraty piece of imperative code.
  508. */
  509. Constraint.prototype.isInput = function () {
  510. return false;
  511. }
  512. /* --- *
  513. * U n a r y C o n s t r a i n t
  514. * --- */
  515. /**
  516. * Abstract superclass for constraints having a single possible output
  517. * variable.
  518. */
  519. function UnaryConstraint(v, strength) {
  520. UnaryConstraint.superConstructor.call(this, strength);
  521. this.myOutput = v;
  522. this.satisfied = false;
  523. this.addConstraint();
  524. }
  525. UnaryConstraint.inheritsFrom(Constraint);
  526. /**
  527. * Adds this constraint to the constraint graph
  528. */
  529. UnaryConstraint.prototype.addToGraph = function () {
  530. this.myOutput.addConstraint(this);
  531. this.satisfied = false;
  532. }
  533. /**
  534. * Decides if this constraint can be satisfied and records that
  535. * decision.
  536. */
  537. UnaryConstraint.prototype.chooseMethod = function (mark) {
  538. this.satisfied = (this.myOutput.mark != mark)
  539. && Strength.stronger(this.strength, this.myOutput.walkStrength);
  540. }
  541. /**
  542. * Returns true if this constraint is satisfied in the current solution.
  543. */
  544. UnaryConstraint.prototype.isSatisfied = function () {
  545. return this.satisfied;
  546. }
  547. UnaryConstraint.prototype.markInputs = function (mark) {
  548. // has no inputs
  549. }
  550. /**
  551. * Returns the current output variable.
  552. */
  553. UnaryConstraint.prototype.output = function () {
  554. return this.myOutput;
  555. }
  556. /**
  557. * Calculate the walkabout strength, the stay flag, and, if it is
  558. * 'stay', the value for the current output of this constraint. Assume
  559. * this constraint is satisfied.
  560. */
  561. UnaryConstraint.prototype.recalculate = function () {
  562. this.myOutput.walkStrength = this.strength;
  563. this.myOutput.stay = !this.isInput();
  564. if (this.myOutput.stay) this.execute(); // Stay optimization
  565. }
  566. /**
  567. * Records that this constraint is unsatisfied
  568. */
  569. UnaryConstraint.prototype.markUnsatisfied = function () {
  570. this.satisfied = false;
  571. }
  572. UnaryConstraint.prototype.inputsKnown = function () {
  573. return true;
  574. }
  575. UnaryConstraint.prototype.removeFromGraph = function () {
  576. if (this.myOutput != null) this.myOutput.removeConstraint(this);
  577. this.satisfied = false;
  578. }
  579. /* --- *
  580. * S t a y C o n s t r a i n t
  581. * --- */
  582. /**
  583. * Variables that should, with some level of preference, stay the same.
  584. * Planners may exploit the fact that instances, if satisfied, will not
  585. * change their output during plan execution. This is called "stay
  586. * optimization".
  587. */
  588. function StayConstraint(v, str) {
  589. StayConstraint.superConstructor.call(this, v, str);
  590. }
  591. StayConstraint.inheritsFrom(UnaryConstraint);
  592. StayConstraint.prototype.execute = function () {
  593. // Stay constraints do nothing
  594. }
  595. /* --- *
  596. * E d i t C o n s t r a i n t
  597. * --- */
  598. /**
  599. * A unary input constraint used to mark a variable that the client
  600. * wishes to change.
  601. */
  602. function EditConstraint(v, str) {
  603. EditConstraint.superConstructor.call(this, v, str);
  604. }
  605. EditConstraint.inheritsFrom(UnaryConstraint);
  606. /**
  607. * Edits indicate that a variable is to be changed by imperative code.
  608. */
  609. EditConstraint.prototype.isInput = function () {
  610. return true;
  611. }
  612. EditConstraint.prototype.execute = function () {
  613. // Edit constraints do nothing
  614. }
  615. /* --- *
  616. * B i n a r y C o n s t r a i n t
  617. * --- */
  618. var Direction = new Object();
  619. Direction.NONE = 0;
  620. Direction.FORWARD = 1;
  621. Direction.BACKWARD = -1;
  622. /**
  623. * Abstract superclass for constraints having two possible output
  624. * variables.
  625. */
  626. function BinaryConstraint(var1, var2, strength) {
  627. BinaryConstraint.superConstructor.call(this, strength);
  628. this.v1 = var1;
  629. this.v2 = var2;
  630. this.direction = Direction.NONE;
  631. this.addConstraint();
  632. }
  633. BinaryConstraint.inheritsFrom(Constraint);
  634. /**
  635. * Decides if this constraint can be satisfied and which way it
  636. * should flow based on the relative strength of the variables related,
  637. * and record that decision.
  638. */
  639. BinaryConstraint.prototype.chooseMethod = function (mark) {
  640. if (this.v1.mark == mark) {
  641. this.direction = (this.v2.mark != mark && Strength.stronger(this.strength, this.v2.walkStrength))
  642. ? Direction.FORWARD
  643. : Direction.NONE;
  644. }
  645. if (this.v2.mark == mark) {
  646. this.direction = (this.v1.mark != mark && Strength.stronger(this.strength, this.v1.walkStrength))
  647. ? Direction.BACKWARD
  648. : Direction.NONE;
  649. }
  650. if (Strength.weaker(this.v1.walkStrength, this.v2.walkStrength)) {
  651. this.direction = Strength.stronger(this.strength, this.v1.walkStrength)
  652. ? Direction.BACKWARD
  653. : Direction.NONE;
  654. } else {
  655. this.direction = Strength.stronger(this.strength, this.v2.walkStrength)
  656. ? Direction.FORWARD
  657. : Direction.BACKWARD
  658. }
  659. }
  660. /**
  661. * Add this constraint to the constraint graph
  662. */
  663. BinaryConstraint.prototype.addToGraph = function () {
  664. this.v1.addConstraint(this);
  665. this.v2.addConstraint(this);
  666. this.direction = Direction.NONE;
  667. }
  668. /**
  669. * Answer true if this constraint is satisfied in the current solution.
  670. */
  671. BinaryConstraint.prototype.isSatisfied = function () {
  672. return this.direction != Direction.NONE;
  673. }
  674. /**
  675. * Mark the input variable with the given mark.
  676. */
  677. BinaryConstraint.prototype.markInputs = function (mark) {
  678. this.input().mark = mark;
  679. }
  680. /**
  681. * Returns the current input variable
  682. */
  683. BinaryConstraint.prototype.input = function () {
  684. return (this.direction == Direction.FORWARD) ? this.v1 : this.v2;
  685. }
  686. /**
  687. * Returns the current output variable
  688. */
  689. BinaryConstraint.prototype.output = function () {
  690. return (this.direction == Direction.FORWARD) ? this.v2 : this.v1;
  691. }
  692. /**
  693. * Calculate the walkabout strength, the stay flag, and, if it is
  694. * 'stay', the value for the current output of this
  695. * constraint. Assume this constraint is satisfied.
  696. */
  697. BinaryConstraint.prototype.recalculate = function () {
  698. var ihn = this.input(), out = this.output();
  699. out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength);
  700. out.stay = ihn.stay;
  701. if (out.stay) this.execute();
  702. }
  703. /**
  704. * Record the fact that this constraint is unsatisfied.
  705. */
  706. BinaryConstraint.prototype.markUnsatisfied = function () {
  707. this.direction = Direction.NONE;
  708. }
  709. BinaryConstraint.prototype.inputsKnown = function (mark) {
  710. var i = this.input();
  711. return i.mark == mark || i.stay || i.determinedBy == null;
  712. }
  713. BinaryConstraint.prototype.removeFromGraph = function () {
  714. if (this.v1 != null) this.v1.removeConstraint(this);
  715. if (this.v2 != null) this.v2.removeConstraint(this);
  716. this.direction = Direction.NONE;
  717. }
  718. /* --- *
  719. * S c a l e C o n s t r a i n t
  720. * --- */
  721. /**
  722. * Relates two variables by the linear scaling relationship: "v2 =
  723. * (v1 * scale) + offset". Either v1 or v2 may be changed to maintain
  724. * this relationship but the scale factor and offset are considered
  725. * read-only.
  726. */
  727. function ScaleConstraint(src, scale, offset, dest, strength) {
  728. this.direction = Direction.NONE;
  729. this.scale = scale;
  730. this.offset = offset;
  731. ScaleConstraint.superConstructor.call(this, src, dest, strength);
  732. }
  733. ScaleConstraint.inheritsFrom(BinaryConstraint);
  734. /**
  735. * Adds this constraint to the constraint graph.
  736. */
  737. ScaleConstraint.prototype.addToGraph = function () {
  738. ScaleConstraint.superConstructor.prototype.addToGraph.call(this);
  739. this.scale.addConstraint(this);
  740. this.offset.addConstraint(this);
  741. }
  742. ScaleConstraint.prototype.removeFromGraph = function () {
  743. ScaleConstraint.superConstructor.prototype.removeFromGraph.call(this);
  744. if (this.scale != null) this.scale.removeConstraint(this);
  745. if (this.offset != null) this.offset.removeConstraint(this);
  746. }
  747. ScaleConstraint.prototype.markInputs = function (mark) {
  748. ScaleConstraint.superConstructor.prototype.markInputs.call(this, mark);
  749. this.scale.mark = this.offset.mark = mark;
  750. }
  751. /**
  752. * Enforce this constraint. Assume that it is satisfied.
  753. */
  754. ScaleConstraint.prototype.execute = function () {
  755. if (this.direction == Direction.FORWARD) {
  756. this.v2.value = this.v1.value * this.scale.value + this.offset.value;
  757. } else {
  758. this.v1.value = (this.v2.value - this.offset.value) / this.scale.value;
  759. }
  760. }
  761. /**
  762. * Calculate the walkabout strength, the stay flag, and, if it is
  763. * 'stay', the value for the current output of this constraint. Assume
  764. * this constraint is satisfied.
  765. */
  766. ScaleConstraint.prototype.recalculate = function () {
  767. var ihn = this.input(), out = this.output();
  768. out.walkStrength = Strength.weakestOf(this.strength, ihn.walkStrength);
  769. out.stay = ihn.stay && this.scale.stay && this.offset.stay;
  770. if (out.stay) this.execute();
  771. }
  772. /* --- *
  773. * E q u a l i t y C o n s t r a i n t
  774. * --- */
  775. /**
  776. * Constrains two variables to have the same value.
  777. */
  778. function EqualityConstraint(var1, var2, strength) {
  779. EqualityConstraint.superConstructor.call(this, var1, var2, strength);
  780. }
  781. EqualityConstraint.inheritsFrom(BinaryConstraint);
  782. /**
  783. * Enforce this constraint. Assume that it is satisfied.
  784. */
  785. EqualityConstraint.prototype.execute = function () {
  786. this.output().value = this.input().value;
  787. }
  788. /* --- *
  789. * V a r i a b l e
  790. * --- */
  791. /**
  792. * A constrained variable. In addition to its value, it maintain the
  793. * structure of the constraint graph, the current dataflow graph, and
  794. * various parameters of interest to the DeltaBlue incremental
  795. * constraint solver.
  796. **/
  797. function Variable(name, initialValue) {
  798. this.value = initialValue || 0;
  799. this.constraints = new OrderedCollection();
  800. this.determinedBy = null;
  801. this.mark = 0;
  802. this.walkStrength = Strength.WEAKEST;
  803. this.stay = true;
  804. this.name = name;
  805. }
  806. /**
  807. * Add the given constraint to the set of all constraints that refer
  808. * this variable.
  809. */
  810. Variable.prototype.addConstraint = function (c) {
  811. this.constraints.add(c);
  812. }
  813. /**
  814. * Removes all traces of c from this variable.
  815. */
  816. Variable.prototype.removeConstraint = function (c) {
  817. this.constraints.remove(c);
  818. if (this.determinedBy == c) this.determinedBy = null;
  819. }
  820. /* --- *
  821. * P l a n n e r
  822. * --- */
  823. /**
  824. * The DeltaBlue planner
  825. */
  826. function Planner() {
  827. this.currentMark = 0;
  828. }
  829. /**
  830. * Attempt to satisfy the given constraint and, if successful,
  831. * incrementally update the dataflow graph. Details: If satifying
  832. * the constraint is successful, it may override a weaker constraint
  833. * on its output. The algorithm attempts to resatisfy that
  834. * constraint using some other method. This process is repeated
  835. * until either a) it reaches a variable that was not previously
  836. * determined by any constraint or b) it reaches a constraint that
  837. * is too weak to be satisfied using any of its methods. The
  838. * variables of constraints that have been processed are marked with
  839. * a unique mark value so that we know where we've been. This allows
  840. * the algorithm to avoid getting into an infinite loop even if the
  841. * constraint graph has an inadvertent cycle.
  842. */
  843. Planner.prototype.incrementalAdd = function (c) {
  844. var mark = this.newMark();
  845. var overridden = c.satisfy(mark);
  846. while (overridden != null)
  847. overridden = overridden.satisfy(mark);
  848. }
  849. /**
  850. * Entry point for retracting a constraint. Remove the given
  851. * constraint and incrementally update the dataflow graph.
  852. * Details: Retracting the given constraint may allow some currently
  853. * unsatisfiable downstream constraint to be satisfied. We therefore collect
  854. * a list of unsatisfied downstream constraints and attempt to
  855. * satisfy each one in turn. This list is traversed by constraint
  856. * strength, strongest first, as a heuristic for avoiding
  857. * unnecessarily adding and then overriding weak constraints.
  858. * Assume: c is satisfied.
  859. */
  860. Planner.prototype.incrementalRemove = function (c) {
  861. var out = c.output();
  862. c.markUnsatisfied();
  863. c.removeFromGraph();
  864. var unsatisfied = this.removePropagateFrom(out);
  865. var strength = Strength.REQUIRED;
  866. do {
  867. for (var i = 0; i < unsatisfied.size(); i++) {
  868. var u = unsatisfied.at(i);
  869. if (u.strength == strength)
  870. this.incrementalAdd(u);
  871. }
  872. strength = strength.nextWeaker();
  873. } while (strength != Strength.WEAKEST);
  874. }
  875. /**
  876. * Select a previously unused mark value.
  877. */
  878. Planner.prototype.newMark = function () {
  879. return ++this.currentMark;
  880. }
  881. /**
  882. * Extract a plan for resatisfaction starting from the given source
  883. * constraints, usually a set of input constraints. This method
  884. * assumes that stay optimization is desired; the plan will contain
  885. * only constraints whose output variables are not stay. Constraints
  886. * that do no computation, such as stay and edit constraints, are
  887. * not included in the plan.
  888. * Details: The outputs of a constraint are marked when it is added
  889. * to the plan under construction. A constraint may be appended to
  890. * the plan when all its input variables are known. A variable is
  891. * known if either a) the variable is marked (indicating that has
  892. * been computed by a constraint appearing earlier in the plan), b)
  893. * the variable is 'stay' (i.e. it is a constant at plan execution
  894. * time), or c) the variable is not determined by any
  895. * constraint. The last provision is for past states of history
  896. * variables, which are not stay but which are also not computed by
  897. * any constraint.
  898. * Assume: sources are all satisfied.
  899. */
  900. Planner.prototype.makePlan = function (sources) {
  901. var mark = this.newMark();
  902. var plan = new Plan();
  903. var todo = sources;
  904. while (todo.size() > 0) {
  905. var c = todo.removeFirst();
  906. if (c.output().mark != mark && c.inputsKnown(mark)) {
  907. plan.addConstraint(c);
  908. c.output().mark = mark;
  909. this.addConstraintsConsumingTo(c.output(), todo);
  910. }
  911. }
  912. return plan;
  913. }
  914. /**
  915. * Extract a plan for resatisfying starting from the output of the
  916. * given constraints, usually a set of input constraints.
  917. */
  918. Planner.prototype.extractPlanFromConstraints = function (constraints) {
  919. var sources = new OrderedCollection();
  920. for (var i = 0; i < constraints.size(); i++) {
  921. var c = constraints.at(i);
  922. if (c.isInput() && c.isSatisfied())
  923. // not in plan already and eligible for inclusion
  924. sources.add(c);
  925. }
  926. return this.makePlan(sources);
  927. }
  928. /**
  929. * Recompute the walkabout strengths and stay flags of all variables
  930. * downstream of the given constraint and recompute the actual
  931. * values of all variables whose stay flag is true. If a cycle is
  932. * detected, remove the given constraint and answer
  933. * false. Otherwise, answer true.
  934. * Details: Cycles are detected when a marked variable is
  935. * encountered downstream of the given constraint. The sender is
  936. * assumed to have marked the inputs of the given constraint with
  937. * the given mark. Thus, encountering a marked node downstream of
  938. * the output constraint means that there is a path from the
  939. * constraint's output to one of its inputs.
  940. */
  941. Planner.prototype.addPropagate = function (c, mark) {
  942. var todo = new OrderedCollection();
  943. todo.add(c);
  944. while (todo.size() > 0) {
  945. var d = todo.removeFirst();
  946. if (d.output().mark == mark) {
  947. this.incrementalRemove(c);
  948. return false;
  949. }
  950. d.recalculate();
  951. this.addConstraintsConsumingTo(d.output(), todo);
  952. }
  953. return true;
  954. }
  955. /**
  956. * Update the walkabout strengths and stay flags of all variables
  957. * downstream of the given constraint. Answer a collection of
  958. * unsatisfied constraints sorted in order of decreasing strength.
  959. */
  960. Planner.prototype.removePropagateFrom = function (out) {
  961. out.determinedBy = null;
  962. out.walkStrength = Strength.WEAKEST;
  963. out.stay = true;
  964. var unsatisfied = new OrderedCollection();
  965. var todo = new OrderedCollection();
  966. todo.add(out);
  967. while (todo.size() > 0) {
  968. var v = todo.removeFirst();
  969. for (var i = 0; i < v.constraints.size(); i++) {
  970. var c = v.constraints.at(i);
  971. if (!c.isSatisfied())
  972. unsatisfied.add(c);
  973. }
  974. var determining = v.determinedBy;
  975. for (var i = 0; i < v.constraints.size(); i++) {
  976. var next = v.constraints.at(i);
  977. if (next != determining && next.isSatisfied()) {
  978. next.recalculate();
  979. todo.add(next.output());
  980. }
  981. }
  982. }
  983. return unsatisfied;
  984. }
  985. Planner.prototype.addConstraintsConsumingTo = function (v, coll) {
  986. var determining = v.determinedBy;
  987. var cc = v.constraints;
  988. for (var i = 0; i < cc.size(); i++) {
  989. var c = cc.at(i);
  990. if (c != determining && c.isSatisfied())
  991. coll.add(c);
  992. }
  993. }
  994. /* --- *
  995. * P l a n
  996. * --- */
  997. /**
  998. * A Plan is an ordered list of constraints to be executed in sequence
  999. * to resatisfy all currently satisfiable constraints in the face of
  1000. * one or more changing inputs.
  1001. */
  1002. function Plan() {
  1003. this.v = new OrderedCollection();
  1004. }
  1005. Plan.prototype.addConstraint = function (c) {
  1006. this.v.add(c);
  1007. }
  1008. Plan.prototype.size = function () {
  1009. return this.v.size();
  1010. }
  1011. Plan.prototype.constraintAt = function (index) {
  1012. return this.v.at(index);
  1013. }
  1014. Plan.prototype.execute = function () {
  1015. for (var i = 0; i < this.size(); i++) {
  1016. var c = this.constraintAt(i);
  1017. c.execute();
  1018. }
  1019. }
  1020. /* --- *
  1021. * M a i n
  1022. * --- */
  1023. /**
  1024. * This is the standard DeltaBlue benchmark. A long chain of equality
  1025. * constraints is constructed with a stay constraint on one end. An
  1026. * edit constraint is then added to the opposite end and the time is
  1027. * measured for adding and removing this constraint, and extracting
  1028. * and executing a constraint satisfaction plan. There are two cases.
  1029. * In case 1, the added constraint is stronger than the stay
  1030. * constraint and values must propagate down the entire length of the
  1031. * chain. In case 2, the added constraint is weaker than the stay
  1032. * constraint so it cannot be accomodated. The cost in this case is,
  1033. * of course, very low. Typical situations lie somewhere between these
  1034. * two extremes.
  1035. */
  1036. function chainTest(n) {
  1037. planner = new Planner();
  1038. var prev = null, first = null, last = null;
  1039. // Build chain of n equality constraints
  1040. for (var i = 0; i <= n; i++) {
  1041. var name = "v" + i;
  1042. var v = new Variable(name);
  1043. if (prev != null)
  1044. new EqualityConstraint(prev, v, Strength.REQUIRED);
  1045. if (i == 0) first = v;
  1046. if (i == n) last = v;
  1047. prev = v;
  1048. }
  1049. new StayConstraint(last, Strength.STRONG_DEFAULT);
  1050. var edit = new EditConstraint(first, Strength.PREFERRED);
  1051. var edits = new OrderedCollection();
  1052. edits.add(edit);
  1053. var plan = planner.extractPlanFromConstraints(edits);
  1054. for (var i = 0; i < 100; i++) {
  1055. first.value = i;
  1056. plan.execute();
  1057. if (last.value != i)
  1058. alert("Chain test failed.");
  1059. }
  1060. }
  1061. /**
  1062. * This test constructs a two sets of variables related to each
  1063. * other by a simple linear transformation (scale and offset). The
  1064. * time is measured to change a variable on either side of the
  1065. * mapping and to change the scale and offset factors.
  1066. */
  1067. function projectionTest(n) {
  1068. planner = new Planner();
  1069. var scale = new Variable("scale", 10);
  1070. var offset = new Variable("offset", 1000);
  1071. var src = null, dst = null;
  1072. var dests = new OrderedCollection();
  1073. for (var i = 0; i < n; i++) {
  1074. src = new Variable("src" + i, i);
  1075. dst = new Variable("dst" + i, i);
  1076. dests.add(dst);
  1077. new StayConstraint(src, Strength.NORMAL);
  1078. new ScaleConstraint(src, scale, offset, dst, Strength.REQUIRED);
  1079. }
  1080. change(src, 17);
  1081. if (dst.value != 1170) alert("Projection 1 failed");
  1082. change(dst, 1050);
  1083. if (src.value != 5) alert("Projection 2 failed");
  1084. change(scale, 5);
  1085. for (var i = 0; i < n - 1; i++) {
  1086. if (dests.at(i).value != i * 5 + 1000)
  1087. alert("Projection 3 failed");
  1088. }
  1089. change(offset, 2000);
  1090. for (var i = 0; i < n - 1; i++) {
  1091. if (dests.at(i).value != i * 5 + 2000)
  1092. alert("Projection 4 failed");
  1093. }
  1094. }
  1095. function change(v, newValue) {
  1096. var edit = new EditConstraint(v, Strength.PREFERRED);
  1097. var edits = new OrderedCollection();
  1098. edits.add(edit);
  1099. var plan = planner.extractPlanFromConstraints(edits);
  1100. for (var i = 0; i < 10; i++) {
  1101. v.value = newValue;
  1102. plan.execute();
  1103. }
  1104. edit.destroyConstraint();
  1105. }
  1106. // Global variable holding the current planner.
  1107. var planner = null;
  1108. function deltaBlue() {
  1109. chainTest(100);
  1110. projectionTest(100);
  1111. }
  1112. ////////////////////////////////////////////////////////////////////////////////
  1113. // Runner
  1114. ////////////////////////////////////////////////////////////////////////////////
  1115. var success = true;
  1116. function NotifyStart(name) {
  1117. }
  1118. function NotifyError(name, error) {
  1119. WScript.Echo(name + " : ERROR : " + error.stack);
  1120. success = false;
  1121. }
  1122. function NotifyResult(name, score) {
  1123. if (success) {
  1124. WScript.Echo("### SCORE:", score);
  1125. }
  1126. }
  1127. function NotifyScore(score) {
  1128. }
  1129. BenchmarkSuite.RunSuites({
  1130. NotifyStart: NotifyStart,
  1131. NotifyError: NotifyError,
  1132. NotifyResult: NotifyResult,
  1133. NotifyScore: NotifyScore
  1134. });