quicopt 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/quicopt/wire.rb CHANGED
@@ -69,10 +69,14 @@ module Quicopt
69
69
 
70
70
  # Encode a model (or an already-built +Program+) to bytes.
71
71
  #
72
+ # A model is written straight to bytes (+Bytes.program+): the same bytes
73
+ # as +PB::Program.encode(program(model))+, without building the message
74
+ # tree first.
75
+ #
72
76
  # @param model [Quicopt::Model, PB::Program]
73
77
  # @return [String] binary protobuf bytes
74
78
  def encode(model)
75
- PB::Program.encode(model.is_a?(PB::Program) ? model : program(model))
79
+ model.is_a?(PB::Program) ? PB::Program.encode(model) : Bytes.program(model)
76
80
  end
77
81
 
78
82
  # Parse bytes back into a +Program+ — the inverse of +encode+, and the only
@@ -96,9 +100,10 @@ module Quicopt
96
100
  #
97
101
  # IEEE keeps +-0.0+ distinct from +0.0+ — a distinct bit pattern, and a
98
102
  # distinct protobuf value — and moving a bound across an inequality
99
- # (+f ≤ 0+ ⇒ +0 − f ≥ 0+) produces one whenever that bound is zero. The
100
- # Python and Julia clients send +0.0+ there, so collapse the sign here
101
- # rather than sending bytes that differ from theirs by a sign bit.
103
+ # (<tt>f ≤ 0</tt> ⇒ <tt>0 − f ≥ 0</tt>) produces one whenever that bound
104
+ # is zero. The Python and Julia clients send +0.0+ there, so collapse the
105
+ # sign here rather than sending bytes that differ from theirs by a sign
106
+ # bit.
102
107
  def number(value)
103
108
  float = value.to_f
104
109
  float.zero? ? 0.0 : float
@@ -241,12 +246,12 @@ module Quicopt
241
246
  def structure_decl(structure)
242
247
  start = (structure.start || []).map { |k| k + 1 }
243
248
  if structure.is_a?(Partition)
244
- return PB::StructureDecl.new(name: structure.name, kind: "partition", size: structure.size,
245
- start: start, fixed: false, parts: structure.parts)
249
+ return PB::StructureDecl.new(name: structure.name, kind: "partition", size: structure.n_items,
250
+ start: start, fixed: false, parts: structure.n_parts)
246
251
  end
247
252
 
248
253
  PB::StructureDecl.new(
249
- name: structure.name, kind: "permutation", size: structure.size, start: start, fixed: false,
254
+ name: structure.name, kind: "permutation", size: structure.n_items, start: start, fixed: false,
250
255
  precede: structure.precedences.map { |a, b| PB::Precedence.new(before: a + 1, after: b + 1) }
251
256
  )
252
257
  end
@@ -310,5 +315,254 @@ module Quicopt
310
315
  end
311
316
  end
312
317
  end
318
+
319
+ # Writes a model's +Program+ message straight to protobuf bytes.
320
+ #
321
+ # Building the message tree costs about six protobuf objects per term of a
322
+ # row (+c · x+ is an +Expression+ holding an +Apply+, which holds a constant
323
+ # +Expression+ and a variable +Expression+ with its +VarRef+ and +Index+),
324
+ # and on a model of 90,000 terms that was half of the whole build. Here
325
+ # each field is written as the bytes protobuf would write for it: the
326
+ # fields of a message in the order of their numbers, a message or a string
327
+ # as its length and its bytes, a number as 8 little-endian bytes, a field
328
+ # that holds its default value left out, and a +oneof+ case always written.
329
+ #
330
+ # A variable's term +c · x+ differs from every other term of that variable
331
+ # only in the 8 bytes of +c+, so the bytes before and after them are
332
+ # written once per variable (+Pieces+), and so are those of
333
+ # +c · indicator(x)+ and +c · step(x)+. Lookup tables, permutations,
334
+ # partitions and reads of them go through the message classes, and their
335
+ # bytes are embedded as they come. The tests check that the bytes equal
336
+ # +PB::Program.encode(Wire.program(model))+.
337
+ #
338
+ # @api private
339
+ module Bytes
340
+ # A constant +Expression+ holding 0, which a sum drops.
341
+ ZERO = ("\x09".b + [0.0].pack("E")).freeze
342
+ # +Constraint.set+ holding +ConSet+ +zero+ (+f = 0+) and +nonneg+ (+f ≥ 0+).
343
+ ZERO_SET = "\x12\x02\x0A\x00".b.freeze
344
+ NONNEG_SET = "\x12\x02\x12\x00".b.freeze
345
+ # The empty +Index+ of a reference to a flat variable, as +VarRef.index+.
346
+ EMPTY_INDEX = "\x12\x00".b.freeze
347
+ # +Apply.op+ of a sum, and the head of a constant among a sum's arguments.
348
+ PLUS = "\x0A\x01+".b.freeze
349
+ CONST_ARG = "\x12\x09".b.freeze
350
+ # +Apply.op+ of a product and the head of its constant argument, up to the
351
+ # constant's 8 bytes.
352
+ TIMES_CONST = "\x0A\x01*\x12\x09\x09".b.freeze
353
+
354
+ # The bytes of the terms of one factor (a variable, or a condition on
355
+ # one): +expr+, the factor's +Expression+; +arg+, the same as one of an
356
+ # +Apply+'s arguments, which is both +1 · factor+ in a sum and the second
357
+ # argument of +c · factor+; and the bytes of +c · factor+ before +c+, as
358
+ # an +Expression+ (+head+) and as an argument of a sum (+arg_head+).
359
+ Pieces = Struct.new(:expr, :arg, :head, :arg_head) do
360
+ # The pieces of the factor whose +Expression+ is +expr+.
361
+ def self.of(expr)
362
+ arg = Bytes.field(String.new(encoding: Encoding::BINARY), 2, expr).freeze
363
+ head = (+"\x22".b).tap { |h| Bytes.varint(h, TIMES_CONST.bytesize + 8 + arg.bytesize) } << TIMES_CONST
364
+ arg_head = (+"\x12".b).tap { |h| Bytes.varint(h, head.bytesize + 8 + arg.bytesize) } << head
365
+ new(expr.freeze, arg, head.freeze, arg_head.freeze)
366
+ end
367
+
368
+ # +c · factor+ as an +Expression+, +c+ given as its 8 bytes.
369
+ def term(number)
370
+ head + number + arg
371
+ end
372
+ end
373
+
374
+ # The cached bytes of one flat variable: its +VarRef+ and the +Pieces+ of
375
+ # the variable and of the conditions on it.
376
+ VarBytes = Struct.new(:ref, :pieces, :conditions)
377
+
378
+ class << self
379
+ # The bytes of +PB::Program.encode(Wire.program(model))+.
380
+ #
381
+ # @param model [Quicopt::Model]
382
+ # @return [String] binary protobuf bytes
383
+ def program(model)
384
+ vars = {} # variable name => VarBytes, written once
385
+ out = String.new(encoding: Encoding::BINARY)
386
+ model.tables.sort_by(&:name).each { |t| field(out, 3, PB::ParamTable.encode(Wire.param_table(t))) }
387
+ model.variables.each { |v| field(out, 4, var_decl(v)) }
388
+ field(out, 5, expression(model.objective, vars))
389
+ string(out, 6, model.sense)
390
+ model.constraints.each { |c| field(out, 7, constraint(c, vars)) }
391
+ (model.permutations + model.partitions).sort_by(&:name).each do |s|
392
+ field(out, 12, PB::StructureDecl.encode(Wire.structure_decl(s)))
393
+ end
394
+ model.blocks.sort_by(&:name).each do |b|
395
+ block = string(String.new(encoding: Encoding::BINARY), 1, b.name)
396
+ b.variables.each { |v| field(block, 2, variable(v.name, vars).ref) }
397
+ field(out, 13, block)
398
+ end
399
+ out
400
+ end
401
+
402
+ # Append field +number+ (below 16) holding the bytes of a message.
403
+ def field(out, number, bytes)
404
+ out << ((number << 3) | 2)
405
+ varint(out, bytes.bytesize)
406
+ out << bytes
407
+ end
408
+
409
+ # Append the base-128 varint of +n+, low group first.
410
+ def varint(out, n)
411
+ while n >= 0x80
412
+ out << ((n & 0x7F) | 0x80)
413
+ n >>= 7
414
+ end
415
+ out << n
416
+ end
417
+
418
+ private
419
+
420
+ # +Wire.expression+, as bytes: +sum+ of the terms, each written straight
421
+ # into the sum's +Apply+, so a sum of one term is that term.
422
+ def expression(expr, vars)
423
+ body = PLUS.dup
424
+ n = 0
425
+ single = nil # the first term, as an Expression: the whole sum when it is the only one
426
+ unless expr.constant.zero?
427
+ single = const(expr.constant)
428
+ body << CONST_ARG << single
429
+ n += 1
430
+ end
431
+ expr.linear.each do |f, c|
432
+ pieces = pieces(f, vars)
433
+ if pieces.nil?
434
+ term = scaled(c, factor(f, vars))
435
+ next if term == ZERO
436
+
437
+ field(body, 2, term)
438
+ single = term if n.zero?
439
+ elsif c == 1.0
440
+ body << pieces.arg
441
+ single = pieces.expr if n.zero?
442
+ else
443
+ number = [Wire.number(c)].pack("E")
444
+ body << pieces.arg_head << number << pieces.arg
445
+ single = pieces.term(number) if n.zero?
446
+ end
447
+ n += 1
448
+ end
449
+ expr.quadratic.each do |(a, b), c|
450
+ term = scaled(c, apply("*", [factor(a, vars), factor(b, vars)]))
451
+ field(body, 2, term)
452
+ single = term if n.zero?
453
+ n += 1
454
+ end
455
+ return ZERO if n.zero?
456
+ return single if n == 1
457
+
458
+ field(String.new(encoding: Encoding::BINARY), 4, body)
459
+ end
460
+
461
+ # The cached +Pieces+ of the factor +f+ when it is a variable or an
462
+ # +indicator+ or +step+ of a bare variable, else nil.
463
+ def pieces(f, vars)
464
+ return variable(f.name, vars).pieces if f.is_a?(Quicopt::Variable)
465
+ return nil unless f.is_a?(Condition) && %i[indicator step].include?(f.op)
466
+
467
+ arg = f.argument
468
+ return nil unless arg.constant.zero? && arg.quadratic.empty? && arg.linear.size == 1
469
+
470
+ x, c = arg.linear.first
471
+ return nil unless c == 1.0 && x.is_a?(Quicopt::Variable)
472
+
473
+ v = variable(x.name, vars)
474
+ v.conditions[f.op] ||= Pieces.of(apply(f.op.to_s, [v.pieces.expr]))
475
+ end
476
+
477
+ # The cached bytes of the flat variable +name+.
478
+ def variable(name, vars)
479
+ vars[name] ||= begin
480
+ ref = string(String.new(encoding: Encoding::BINARY), 1, name) << EMPTY_INDEX
481
+ VarBytes.new(ref.freeze, Pieces.of(field(String.new(encoding: Encoding::BINARY), 3, ref)), {})
482
+ end
483
+ end
484
+
485
+ # +Wire.factor+, as bytes. Reads of permutations, partitions and lookup
486
+ # tables go through the message classes.
487
+ def factor(f, vars)
488
+ case f
489
+ when Quicopt::Variable then variable(f.name, vars).pieces.expr
490
+ when Condition then condition(f, vars)
491
+ when Extremum then f.args.map { |a| expression(a, vars) }.reduce { |acc, e| apply(f.op.to_s, [acc, e]) }
492
+ else PB::Expression.encode(Wire.factor(f))
493
+ end
494
+ end
495
+
496
+ # +Wire.condition+, as bytes.
497
+ def condition(cond, vars)
498
+ arg = expression(cond.argument, vars)
499
+ case cond.op
500
+ when :indicator then apply("indicator", [arg])
501
+ when :step then apply("step", [arg])
502
+ when :near then apply("step", [apply("-", [const(cond.tol), apply("abs", [arg])])])
503
+ else raise Error, "unknown condition #{cond.op.inspect}"
504
+ end
505
+ end
506
+
507
+ # +Wire.constraint+, as bytes.
508
+ def constraint(con, vars)
509
+ f = expression(con.body, vars)
510
+ c = con.bound
511
+ out = String.new(encoding: Encoding::BINARY)
512
+ case con.sense
513
+ when :eq then field(out, 1, minus(f, c)) << ZERO_SET
514
+ when :ge then field(out, 1, minus(f, c)) << NONNEG_SET
515
+ when :le then field(out, 1, apply("-", [const(c), f])) << NONNEG_SET
516
+ else raise Error, "unknown constraint sense #{con.sense.inspect}"
517
+ end
518
+ end
519
+
520
+ # +Wire.var_decl+, as bytes. A domain is never 0 (+DOMAIN_UNSPECIFIED+),
521
+ # and a start of 0 is the default, left out.
522
+ def var_decl(variable)
523
+ out = string(String.new(encoding: Encoding::BINARY), 1, variable.name)
524
+ domain = variable.domain.is_a?(Integer) ? variable.domain : PB::Domain.resolve(variable.domain)
525
+ raise Error, "unknown domain #{variable.domain.inspect}" if domain.nil?
526
+
527
+ out << 0x18
528
+ varint(out, domain)
529
+ out << "\x22\x09\x09".b << [Wire.number(variable.lower)].pack("E")
530
+ out << "\x2A\x09\x09".b << [Wire.number(variable.upper)].pack("E")
531
+ start = Wire.number(variable.start)
532
+ out << 0x31 << [start].pack("E") unless start.zero?
533
+ out
534
+ end
535
+
536
+ # +f − c+ as bytes, dropping the additive zero (+Wire.minus+).
537
+ def minus(f, c)
538
+ c.zero? ? f : apply("-", [f, const(c)])
539
+ end
540
+
541
+ # +coef · expr+ as bytes, dropping a unit coefficient (+Wire.scaled+).
542
+ def scaled(coef, expr)
543
+ coef == 1.0 ? expr : apply("*", [const(coef), expr])
544
+ end
545
+
546
+ # A constant +Expression+, negative zero flattened (+Wire.const+).
547
+ def const(value)
548
+ "\x09".b << [Wire.number(value)].pack("E")
549
+ end
550
+
551
+ # The +Expression+ applying +op+ to the +Expression+ bytes +args+ (+Wire.apply+).
552
+ def apply(op, args)
553
+ body = string(String.new(encoding: Encoding::BINARY), 1, op)
554
+ args.each { |a| field(body, 2, a) }
555
+ field(String.new(encoding: Encoding::BINARY), 4, body)
556
+ end
557
+
558
+ # Append field +number+ (below 16) holding a string; an empty one is the
559
+ # default, left out.
560
+ def string(out, number, value)
561
+ return out if value.empty?
562
+
563
+ field(out, number, value.ascii_only? ? value : value.b)
564
+ end
565
+ end
566
+ end
313
567
  end
314
568
  end
data/lib/quicopt.rb CHANGED
@@ -22,7 +22,7 @@ require_relative "quicopt/client"
22
22
  # m.maximize(3 * x + 2 * y + z)
23
23
  # m.add(x + y <= 5)
24
24
  #
25
- # result = Quicopt::Client.new.solve(m)
25
+ # result = Quicopt::Client.new(api_key: "…").solve(m)
26
26
  # puts result.display
27
27
  #
28
28
  # Three pieces, nothing more: +Model+ authors, +Wire+ encodes, +Client+ ships.
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: quicopt
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tim Bode