quicopt 0.4.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 16cdf553d639def3a3a5cbbdb7c9e4240118dc619595edeb9dd710cee798362d
4
- data.tar.gz: 96ce7ae36eb75c68c493a749be503b28240cf843acd5d1196dfaf63410896fcc
3
+ metadata.gz: 0ec5a814d8cb2cb2f79dc7361dd714fb102de6887b1d1070e71919fb503eaaf5
4
+ data.tar.gz: 3b6d2794c026ac7838cddf7e052dbe1099a2670809b67b0e445b4b30496d45a3
5
5
  SHA512:
6
- metadata.gz: 6cc023a263fe6c075da89d9ab6dbdbddc3ad647763a9bd6b58c2f4b50aad76356d686d7256a7ff8fb0c04854419e8df9d8c683586b220d333fcd31808706f441
7
- data.tar.gz: 8a375d5f3f93971f46b9e2a496677f17478b55f7af822a26239a77dd1e5a5a4a90e4a85f19365b614f2f2f1ed9d2f35c5af1f2040a8df52f9d17924e856f3df2
6
+ metadata.gz: fbe0c96463681f0d74d8fc33bbd684ff2411898fc367b239f0d664f186959ac20abada83ce39afbd5ea3341e40586e8d1fb5930ae223f94e12021f2ac5db40d8
7
+ data.tar.gz: 395d4f06288ec8cee8c840097aaf8d2f304cbb6d0f2c36bc4fe280b9967ae535394d083bac8000a01e519a90509b04ce8d12f96ccdc1417f6b70d49a423ef781
data/README.md CHANGED
@@ -374,6 +374,12 @@ baked into the model.
374
374
 
375
375
  **Large models.** `solve(model, gzip: true)` compresses the request body.
376
376
 
377
+ **Connections.** A client keeps its connection to the service open between
378
+ requests, so a run of solves sets up a connection once instead of once per
379
+ request. Threads may share one client: each request in flight uses a connection
380
+ of its own. `client.close` closes the open connections, and the client stays
381
+ usable.
382
+
377
383
  **Time limit.** The service chooses how long a solve may run. `time_limit:` sets that time instead, in seconds. A solver that proves its answer sooner still stops sooner; a search, which cannot prove it is done, may stop sooner too, once it stops finding better answers:
378
384
 
379
385
  ```ruby
@@ -17,7 +17,9 @@ require "zlib"
17
17
  # service's result JSON (+status+ / +objective+ / +solution+ / a ready-to-print
18
18
  # +display+ / …). Every request carries your API key as
19
19
  # <tt>Authorization: Bearer</tt>. Register at https://quicopt.com/signup to
20
- # receive one by email.
20
+ # receive one by email. A client keeps its connection open between requests, so
21
+ # only the first one waits for the connection to be set up; +Client#close+
22
+ # closes it.
21
23
  #
22
24
  # Two entry points mirror the two service endpoints:
23
25
  #
@@ -188,6 +190,12 @@ module Quicopt
188
190
  # The content type of a request body: an encoded model is opaque binary.
189
191
  OCTET_STREAM = "application/octet-stream"
190
192
 
193
+ # Seconds an open connection may sit unused and still carry the next
194
+ # request. Servers and proxies close idle connections after their own
195
+ # timeout, commonly a minute or more; one closed sooner is noticed before
196
+ # the next request and replaced.
197
+ KEEP_ALIVE = 30.0
198
+
191
199
  # @return [String] the service base URL, without a trailing slash
192
200
  attr_reader :base_url
193
201
  # @return [String, nil] the API key in use
@@ -227,6 +235,11 @@ module Quicopt
227
235
  # Only a key that came off disk may be discarded and re-minted on a 401 —
228
236
  # see +request_raw+, which relies on this to bound re-minting to one per run.
229
237
  @from_cache = !@api_key.nil? && !@explicit
238
+ # Open connections between requests, each used by one request at a time
239
+ # (see +connected+), and the process they belong to (see +idle+).
240
+ @idle = []
241
+ @idle_pid = Process.pid
242
+ @idle_lock = Mutex.new
230
243
  end
231
244
 
232
245
  # Solve +model+ synchronously, blocking until the result returns.
@@ -352,7 +365,7 @@ module Quicopt
352
365
  end
353
366
  req["Authorization"] = "Bearer #{@api_key}" if @api_key
354
367
 
355
- resp = http(uri, timeout || @timeout).start { |conn| conn.request(req) }
368
+ resp = connected(uri, timeout || @timeout) { |conn| conn.request(req) }
356
369
  capture_key(resp) # a 502/504 on a first call still minted a key
357
370
  raise QuicoptError.new(resp.code.to_i, Client.decode(resp.body)) unless resp.is_a?(Net::HTTPSuccess)
358
371
 
@@ -477,17 +490,65 @@ module Quicopt
477
490
  tmp&.unlink if tmp&.exist?
478
491
  end
479
492
 
493
+ # Close the connections the client keeps open between requests. The client
494
+ # stays usable: its next request opens a new one.
495
+ #
496
+ # @return [nil]
497
+ def close
498
+ @idle_lock.synchronize { idle.slice!(0..) }.each { |conn| conn.finish if conn.started? }
499
+ nil
500
+ end
501
+
480
502
  private
481
503
 
482
504
  def http(uri, timeout)
483
505
  conn = Net::HTTP.new(uri.host, uri.port)
484
506
  conn.use_ssl = uri.scheme == "https"
507
+ conn.keep_alive_timeout = KEEP_ALIVE
485
508
  conn.open_timeout = timeout
486
509
  conn.read_timeout = timeout
487
510
  conn.write_timeout = timeout
488
511
  conn
489
512
  end
490
513
 
514
+ # Run the block with an open connection to the service, then keep the
515
+ # connection open for a later request.
516
+ #
517
+ # A new connection costs a TCP and a TLS handshake, two round trips before
518
+ # the request goes out, so a solve that submits, polls and fetches would pay
519
+ # them on every request. Each request takes an idle connection, or opens
520
+ # one, and gives it back when its response has been read: threads sharing a
521
+ # client never share a connection. A connection the server has closed is
522
+ # reopened before it is written to (+Net::HTTP+ checks), and one whose
523
+ # request failed is closed, not kept.
524
+ def connected(uri, timeout)
525
+ conn = @idle_lock.synchronize { idle.pop } || http(uri, timeout).tap(&:start)
526
+ conn.read_timeout = timeout
527
+ conn.write_timeout = timeout
528
+ done = false
529
+ result = yield conn
530
+ done = true
531
+ result
532
+ ensure
533
+ if done
534
+ @idle_lock.synchronize { idle.push(conn) }
535
+ elsif conn&.started?
536
+ conn.finish
537
+ end
538
+ end
539
+
540
+ # The idle connections of this process. A process forked from the one that
541
+ # opened them shares their sockets, so it starts with none and leaves them
542
+ # to that process, neither writing to nor closing them. Called under
543
+ # +@idle_lock+.
544
+ def idle
545
+ unless @idle_pid == Process.pid
546
+ @idle = []
547
+ @idle_pid = Process.pid
548
+ end
549
+ @idle
550
+ end
551
+
491
552
  # Coerce to encoded bytes: bytes pass through, a +Program+ is encoded, and a
492
553
  # +Model+ becomes a +Program+ and is encoded — so a caller solves the *model*,
493
554
  # never a hand-built +Program+.
data/lib/quicopt/model.rb CHANGED
@@ -549,6 +549,9 @@ module Quicopt
549
549
  @partitions = []
550
550
  @tables = []
551
551
  @blocks = []
552
+ # The name of the block each blocked variable is in, by identity, so that
553
+ # declaring a block costs time in its own size, not in the model's.
554
+ @block_of = {}.compare_by_identity
552
555
  @structured = {}
553
556
  @interned = {}
554
557
  @reads = 0
@@ -744,19 +747,24 @@ module Quicopt
744
747
  members = Array(vars)
745
748
  raise ArgumentError, "block #{nm.inspect} has no variables" if members.empty?
746
749
 
747
- members.each_with_index do |v, k|
750
+ # The members checked so far, by identity. Nothing is recorded on the model
751
+ # until every member has passed, so a refused block leaves no trace.
752
+ seen = {}.compare_by_identity
753
+ members.each do |v|
748
754
  raise TypeError, "block #{nm.inspect}: a member is a variable, got #{v.class}" unless v.is_a?(Variable)
749
755
  raise ArgumentError, "variable #{v.name.inspect} belongs to a different Quicopt::Model" unless v.model.equal?(self)
750
- raise ArgumentError, "variable #{v.name.inspect} is listed twice in block #{nm.inspect}" if members[0...k].any? { |u| u.equal?(v) }
751
- if (owner = @blocks.find { |b| b.variables.any? { |u| u.equal?(v) } })
752
- raise ArgumentError, "variable #{v.name.inspect} is already in block #{owner.name.inspect}"
756
+ raise ArgumentError, "variable #{v.name.inspect} is listed twice in block #{nm.inspect}" if seen.key?(v)
757
+ if (owner = @block_of[v])
758
+ raise ArgumentError, "variable #{v.name.inspect} is already in block #{owner.inspect}"
753
759
  end
754
760
  unless v.lower.finite? && v.upper.finite?
755
761
  raise ArgumentError, "variable #{v.name.inspect} has bounds [#{v.lower}, #{v.upper}]; " \
756
762
  "a block's variables need finite bounds"
757
763
  end
764
+ seen[v] = true
758
765
  end
759
766
  block = Block.new(nm, members.dup.freeze)
767
+ members.each { |v| @block_of[v] = nm }
760
768
  @blocks << block
761
769
  block
762
770
  end
@@ -5,5 +5,5 @@
5
5
  module Quicopt
6
6
  # The gem version, tracking the client — not the wire schema, which is
7
7
  # versioned separately by its protobuf package (`quicopt.modeler.v1`).
8
- VERSION = "0.4.0"
8
+ VERSION = "0.5.0"
9
9
  end
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
@@ -311,5 +315,254 @@ module Quicopt
311
315
  end
312
316
  end
313
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
314
567
  end
315
568
  end
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.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tim Bode