Skip to content

QuadraticProgram

Quadratically Constrained Quadratic Program representation.

This representation supports inequality and equality constraints, as well as continuous, binary, and integer variables.

Source code in q3as/quadratic/problems/quadratic_program.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
class QuadraticProgram:
    """Quadratically Constrained Quadratic Program representation.

    This representation supports inequality and equality constraints,
    as well as continuous, binary, and integer variables.
    """

    Status = QuadraticProgramStatus

    def __init__(self, name: str = "") -> None:
        """
        Args:
            name: The name of the quadratic program.
        """
        if not name.isprintable():
            warn("Problem name is not printable")
        self._name = ""
        self.name = name
        self._status = QuadraticProgram.Status.VALID

        self._variables: List[Variable] = []
        self._variables_index: Dict[str, int] = {}

        self._linear_constraints: List[LinearConstraint] = []
        self._linear_constraints_index: Dict[str, int] = {}

        self._quadratic_constraints: List[QuadraticConstraint] = []
        self._quadratic_constraints_index: Dict[str, int] = {}

        self._objective = QuadraticObjective(self)

    def __repr__(self) -> str:
        from ..translators.prettyprint import DEFAULT_TRUNCATE, expr2str

        objective = expr2str(
            constant=self._objective.constant,
            linear=self.objective.linear,
            quadratic=self._objective.quadratic,
            truncate=DEFAULT_TRUNCATE,
        )
        num_constraints = (
            self.get_num_linear_constraints() + self.get_num_quadratic_constraints()
        )
        return (
            f"<{self.__class__.__name__}: "
            f"{self.objective.sense.name.lower()} "
            f"{objective}, "
            f"{self.get_num_vars()} variables, "
            f"{num_constraints} constraints, "
            f"'{self._name}'>"
        )

    def __str__(self) -> str:
        num_constraints = (
            self.get_num_linear_constraints() + self.get_num_quadratic_constraints()
        )
        return (
            f"{str(self.objective)} "
            f"({self.get_num_vars()} variables, "
            f"{num_constraints} constraints, "
            f"'{self._name}')"
        )

    def clear(self) -> None:
        """Clears the quadratic program, i.e., deletes all variables, constraints, the
        objective function as well as the name.
        """
        self._name = ""
        self._status = QuadraticProgram.Status.VALID

        self._variables.clear()
        self._variables_index.clear()

        self._linear_constraints.clear()
        self._linear_constraints_index.clear()

        self._quadratic_constraints.clear()
        self._quadratic_constraints_index.clear()

        self._objective = QuadraticObjective(self)

    @property
    def name(self) -> str:
        """Returns the name of the quadratic program.

        Returns:
            The name of the quadratic program.
        """
        return self._name

    @name.setter
    def name(self, name: str) -> None:
        """Sets the name of the quadratic program.

        Args:
            name: The name of the quadratic program.
        """
        self._check_name(name, "Problem")
        self._name = name

    @property
    def status(self) -> QuadraticProgramStatus:
        """Status of the quadratic program.
        It can be infeasible due to variable substitution.

        Returns:
            The status of the quadratic program
        """
        return self._status

    @property
    def variables(self) -> List[Variable]:
        """Returns the list of variables of the quadratic program.

        Returns:
            List of variables.
        """
        return self._variables

    @property
    def variables_index(self) -> Dict[str, int]:
        """Returns the dictionary that maps the name of a variable to its index.

        Returns:
            The variable index dictionary.
        """
        return self._variables_index

    def _add_variable(
        self,
        lowerbound: Union[float, int],
        upperbound: Union[float, int],
        vartype: VarType,
        name: Optional[str],
    ) -> Variable:
        if not name:
            name = "x"
            key_format = "{}"
        else:
            key_format = ""
        return self._add_variables(
            1, lowerbound, upperbound, vartype, name, key_format
        )[1][0]

    def _add_variables(
        self,
        keys: Union[int, Sequence],
        lowerbound: Union[float, int],
        upperbound: Union[float, int],
        vartype: VarType,
        name: Optional[str],
        key_format: str,
    ) -> Tuple[List[str], List[Variable]]:
        if isinstance(keys, int) and keys < 1:
            raise QiskitOptimizationError(
                f"Cannot create non-positive number of variables: {keys}"
            )
        if not name:
            name = "x"
        if "{{}}" in key_format:
            raise QiskitOptimizationError(
                f"Formatter cannot contain nested substitutions: {key_format}"
            )
        if key_format.count("{}") > 1:
            raise QiskitOptimizationError(
                f"Formatter cannot contain more than one substitution: {key_format}"
            )

        def _find_name(name, key_format, k):
            prev = None
            while True:
                new_name = name + key_format.format(k)
                if new_name == prev:
                    raise QiskitOptimizationError(
                        f"Variable name already exists: {new_name}"
                    )
                if new_name in self._variables_index:
                    k += 1
                    prev = new_name
                else:
                    break
            return new_name, k + 1

        names = []
        variables = []
        k = self.get_num_vars()
        lst = keys if isinstance(keys, Sequence) else range(keys)
        for key in lst:
            if isinstance(keys, Sequence):
                indexed_name = name + key_format.format(key)
            else:
                indexed_name, k = _find_name(name, key_format, k)
            if indexed_name in self._variables_index:
                raise QiskitOptimizationError(
                    f"Variable name already exists: {indexed_name}"
                )
            self._check_name(indexed_name, "Variable")
            names.append(indexed_name)
            self._variables_index[indexed_name] = self.get_num_vars()
            variable = Variable(self, indexed_name, lowerbound, upperbound, vartype)
            self._variables.append(variable)
            variables.append(variable)
        return names, variables

    def _var_dict(
        self,
        keys: Union[int, Sequence],
        lowerbound: Union[float, int],
        upperbound: Union[float, int],
        vartype: VarType,
        name: Optional[str],
        key_format: str,
    ) -> Dict[str, Variable]:
        """
        Adds a positive number of variables to the variable list and index and returns a
        dictionary mapping the variable names to their instances. If 'key_format' is present,
        the next 'var_count' available indices are substituted into 'key_format' and appended
        to 'name'.

        Args:
            lowerbound: The lower bound of the variable(s).
            upperbound: The upper bound of the variable(s).
            vartype: The type of the variable(s).
            name: The name(s) of the variable(s).
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A dictionary mapping the variable names to variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return dict(
            zip(
                *self._add_variables(
                    keys, lowerbound, upperbound, vartype, name, key_format
                )
            )
        )

    def _var_list(
        self,
        keys: Union[int, Sequence],
        lowerbound: Union[float, int],
        upperbound: Union[float, int],
        vartype: VarType,
        name: Optional[str],
        key_format: str,
    ) -> List[Variable]:
        """
        Adds a positive number of variables to the variable list and index and returns a
        list of variable instances.

        Args:
            lowerbound: The lower bound of the variable(s).
            upperbound: The upper bound of the variable(s).
            vartype: The type of the variable(s).
            name: The name(s) of the variable(s).
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A dictionary mapping the variable names to variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return self._add_variables(
            keys, lowerbound, upperbound, vartype, name, key_format
        )[1]

    def continuous_var(
        self,
        lowerbound: Union[float, int] = 0,
        upperbound: Union[float, int] = INFINITY,
        name: Optional[str] = None,
    ) -> Variable:
        """Adds a continuous variable to the quadratic program.

        Args:
            lowerbound: The lowerbound of the variable.
            upperbound: The upperbound of the variable.
            name: The name of the variable.
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.

        Returns:
            The added variable.

        Raises:
            QiskitOptimizationError: if the variable name is already occupied.
        """
        return self._add_variable(
            lowerbound, upperbound, Variable.Type.CONTINUOUS, name
        )

    def continuous_var_dict(
        self,
        keys: Union[int, Sequence],
        lowerbound: Union[float, int] = 0,
        upperbound: Union[float, int] = INFINITY,
        name: Optional[str] = None,
        key_format: str = "{}",
    ) -> Dict[str, Variable]:
        """
        Uses 'var_dict' to construct a dictionary of continuous variables

        Args:
            lowerbound: The lower bound of the variable(s).
            upperbound: The upper bound of the variable(s).
            name: The name(s) of the variable(s).
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A dictionary mapping the variable names to variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return self._var_dict(
            keys, lowerbound, upperbound, Variable.Type.CONTINUOUS, name, key_format
        )

    def continuous_var_list(
        self,
        keys: Union[int, Sequence],
        lowerbound: Union[float, int] = 0,
        upperbound: Union[float, int] = INFINITY,
        name: Optional[str] = None,
        key_format: str = "{}",
    ) -> List[Variable]:
        """
        Uses 'var_list' to construct a list of continuous variables

        Args:
            lowerbound: The lower bound of the variable(s).
            upperbound: The upper bound of the variable(s).
            name: The name(s) of the variable(s).
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A list of variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return self._var_list(
            keys, lowerbound, upperbound, Variable.Type.CONTINUOUS, name, key_format
        )

    def binary_var(self, name: Optional[str] = None) -> Variable:
        """Adds a binary variable to the quadratic program.

        Args:
            name: The name of the variable.
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.

        Returns:
            The added variable.

        Raises:
            QiskitOptimizationError: if the variable name is already occupied.
        """
        return self._add_variable(0, 1, Variable.Type.BINARY, name)

    def binary_var_dict(
        self,
        keys: Union[int, Sequence],
        name: Optional[str] = None,
        key_format: str = "{}",
    ) -> Dict[str, Variable]:
        """
        Uses 'var_dict' to construct a dictionary of binary variables

        Args:
            name: The name(s) of the variable(s).
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A dictionary mapping the variable names to variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return self._var_dict(keys, 0, 1, Variable.Type.BINARY, name, key_format)

    def binary_var_list(
        self,
        keys: Union[int, Sequence],
        name: Optional[str] = None,
        key_format: str = "{}",
    ) -> List[Variable]:
        """
        Uses 'var_list' to construct a list of binary variables

        Args:
            name: The name(s) of the variable(s).
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A list of variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return self._var_list(keys, 0, 1, Variable.Type.BINARY, name, key_format)

    def integer_var(
        self,
        lowerbound: Union[float, int] = 0,
        upperbound: Union[float, int] = INFINITY,
        name: Optional[str] = None,
    ) -> Variable:
        """Adds an integer variable to the quadratic program.

        Args:
            lowerbound: The lowerbound of the variable.
            upperbound: The upperbound of the variable.
            name: The name of the variable.
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.

        Returns:
            The added variable.

        Raises:
            QiskitOptimizationError: if the variable name is already occupied.
        """
        return self._add_variable(lowerbound, upperbound, Variable.Type.INTEGER, name)

    def integer_var_dict(
        self,
        keys: Union[int, Sequence],
        lowerbound: Union[float, int] = 0,
        upperbound: Union[float, int] = INFINITY,
        name: Optional[str] = None,
        key_format: str = "{}",
    ) -> Dict[str, Variable]:
        """
        Uses 'var_dict' to construct a dictionary of integer variables

        Args:
            lowerbound: The lower bound of the variable(s).
            upperbound: The upper bound of the variable(s).
            name: The name(s) of the variable(s).
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A dictionary mapping the variable names to variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return self._var_dict(
            keys, lowerbound, upperbound, Variable.Type.INTEGER, name, key_format
        )

    def integer_var_list(
        self,
        keys: Union[int, Sequence],
        lowerbound: Union[float, int] = 0,
        upperbound: Union[float, int] = INFINITY,
        name: Optional[str] = None,
        key_format: str = "{}",
    ) -> List[Variable]:
        """
        Uses 'var_list' to construct a list of integer variables

        Args:
            lowerbound: The lower bound of the variable(s).
            upperbound: The upper bound of the variable(s).
            name: The name(s) of the variable(s).
                If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
            key_format: The format used to name/index the variable(s).
            keys: If keys: int, it is interpreted as the number of variables to construct.
                  Otherwise, the elements of the sequence are converted to strings via 'str' and
                  substituted into `key_format`.

        Returns:
            A list of variable instances.

        Raises:
            QiskitOptimizationError: if the variable name is already taken.
            QiskitOptimizationError: if less than one variable instantiation is attempted.
            QiskitOptimizationError: if `key_format` has more than one substitution or a
                                     nested substitution.
        """
        return self._var_list(
            keys, lowerbound, upperbound, Variable.Type.INTEGER, name, key_format
        )

    def get_variable(self, i: Union[int, str]) -> Variable:
        """Returns a variable for a given name or index.

        Args:
            i: the index or name of the variable.

        Returns:
            The corresponding variable.
        """
        if isinstance(i, (int, np.integer)):
            return self.variables[i]
        else:
            return self.variables[self._variables_index[i]]

    def get_num_vars(self, vartype: Optional[VarType] = None) -> int:
        """Returns the total number of variables or the number of variables of the specified type.

        Args:
            vartype: The type to be filtered on. All variables are counted if None.

        Returns:
            The total number of variables.
        """
        if vartype:
            return sum(variable.vartype == vartype for variable in self._variables)
        else:
            return len(self._variables)

    def get_num_continuous_vars(self) -> int:
        """Returns the total number of continuous variables.

        Returns:
            The total number of continuous variables.
        """
        return self.get_num_vars(Variable.Type.CONTINUOUS)

    def get_num_binary_vars(self) -> int:
        """Returns the total number of binary variables.

        Returns:
            The total number of binary variables.
        """
        return self.get_num_vars(Variable.Type.BINARY)

    def get_num_integer_vars(self) -> int:
        """Returns the total number of integer variables.

        Returns:
            The total number of integer variables.
        """
        return self.get_num_vars(Variable.Type.INTEGER)

    @property
    def linear_constraints(self) -> List[LinearConstraint]:
        """Returns the list of linear constraints of the quadratic program.

        Returns:
            List of linear constraints.
        """
        return self._linear_constraints

    @property
    def linear_constraints_index(self) -> Dict[str, int]:
        """Returns the dictionary that maps the name of a linear constraint to its index.

        Returns:
            The linear constraint index dictionary.
        """
        return self._linear_constraints_index

    def linear_constraint(
        self,
        linear: Union[
            ndarray, spmatrix, List[float], Dict[Union[int, str], float]
        ] = None,
        sense: Union[str, ConstraintSense] = "<=",
        rhs: float = 0.0,
        name: Optional[str] = None,
    ) -> LinearConstraint:
        """Adds a linear equality constraint to the quadratic program of the form:
            ``(linear * x) sense rhs``.

        Args:
            linear: The linear coefficients of the left-hand side of the constraint.
            sense: The sense of the constraint,

                - ``==``, ``=``, ``E``, and ``EQ`` denote 'equal to'.
                - ``>=``, ``>``, ``G``, and ``GE`` denote 'greater-than-or-equal-to'.
                - ``<=``, ``<``, ``L``, and ``LE`` denote 'less-than-or-equal-to'.

            rhs: The right-hand side of the constraint.
            name: The name of the constraint.
                If it's ``None`` or empty ``""``, the default name, e.g., ``c0``, is used.

        Returns:
            The added constraint.

        Raises:
            QiskitOptimizationError: if the constraint name already exists or the sense is not
                valid.
        """
        if name:
            if name in self.linear_constraints_index:
                raise QiskitOptimizationError(
                    f"Linear constraint's name already exists: {name}"
                )
            self._check_name(name, "Linear constraint")
        else:
            k = self.get_num_linear_constraints()
            while f"c{k}" in self.linear_constraints_index:
                k += 1
            name = f"c{k}"
        self.linear_constraints_index[name] = len(self.linear_constraints)
        if linear is None:
            linear = {}
        constraint = LinearConstraint(
            self, name, linear, Constraint.Sense.convert(sense), rhs
        )
        self.linear_constraints.append(constraint)
        return constraint

    def get_linear_constraint(self, i: Union[int, str]) -> LinearConstraint:
        """Returns a linear constraint for a given name or index.

        Args:
            i: the index or name of the constraint.

        Returns:
            The corresponding constraint.

        Raises:
            IndexError: if the index is out of the list size
            KeyError: if the name does not exist
        """
        if isinstance(i, int):
            return self._linear_constraints[i]
        else:
            return self._linear_constraints[self._linear_constraints_index[i]]

    def get_num_linear_constraints(self) -> int:
        """Returns the number of linear constraints.

        Returns:
            The number of linear constraints.
        """
        return len(self._linear_constraints)

    @property
    def quadratic_constraints(self) -> List[QuadraticConstraint]:
        """Returns the list of quadratic constraints of the quadratic program.

        Returns:
            List of quadratic constraints.
        """
        return self._quadratic_constraints

    @property
    def quadratic_constraints_index(self) -> Dict[str, int]:
        """Returns the dictionary that maps the name of a quadratic constraint to its index.

        Returns:
            The quadratic constraint index dictionary.
        """
        return self._quadratic_constraints_index

    def quadratic_constraint(
        self,
        linear: Union[
            ndarray, spmatrix, List[float], Dict[Union[int, str], float]
        ] = None,
        quadratic: Union[
            ndarray,
            spmatrix,
            List[List[float]],
            Dict[Tuple[Union[int, str], Union[int, str]], float],
        ] = None,
        sense: Union[str, ConstraintSense] = "<=",
        rhs: float = 0.0,
        name: Optional[str] = None,
    ) -> QuadraticConstraint:
        """Adds a quadratic equality constraint to the quadratic program of the form:
            ``(x * quadratic * x + linear * x) sense rhs``.

        Args:
            linear: The linear coefficients of the constraint.
            quadratic: The quadratic coefficients of the constraint.
            sense: The sense of the constraint,

                - ``==``, ``=``, ``E``, and ``EQ`` denote 'equal to'.
                - ``>=``, ``>``, ``G``, and ``GE`` denote 'greater-than-or-equal-to'.
                - ``<=``, ``<``, ``L``, and ``LE`` denote 'less-than-or-equal-to'.

            rhs: The right-hand side of the constraint.
            name: The name of the constraint.
                If it's ``None`` or empty ``""``, the default name, e.g., ``q0``, is used.

        Returns:
            The added constraint.

        Raises:
            QiskitOptimizationError: if the constraint name already exists.
        """
        if name:
            if name in self.quadratic_constraints_index:
                raise QiskitOptimizationError(
                    f"Quadratic constraint name already exists: {name}"
                )
            self._check_name(name, "Quadratic constraint")
        else:
            k = self.get_num_quadratic_constraints()
            while f"q{k}" in self.quadratic_constraints_index:
                k += 1
            name = f"q{k}"
        self.quadratic_constraints_index[name] = len(self.quadratic_constraints)
        if linear is None:
            linear = {}
        if quadratic is None:
            quadratic = {}
        constraint = QuadraticConstraint(
            self, name, linear, quadratic, Constraint.Sense.convert(sense), rhs
        )
        self.quadratic_constraints.append(constraint)
        return constraint

    def get_quadratic_constraint(self, i: Union[int, str]) -> QuadraticConstraint:
        """Returns a quadratic constraint for a given name or index.

        Args:
            i: the index or name of the constraint.

        Returns:
            The corresponding constraint.

        Raises:
            IndexError: if the index is out of the list size
            KeyError: if the name does not exist
        """
        if isinstance(i, int):
            return self._quadratic_constraints[i]
        else:
            return self._quadratic_constraints[self._quadratic_constraints_index[i]]

    def get_num_quadratic_constraints(self) -> int:
        """Returns the number of quadratic constraints.

        Returns:
            The number of quadratic constraints.
        """
        return len(self._quadratic_constraints)

    def remove_linear_constraint(self, i: Union[str, int]) -> None:
        """Remove a linear constraint

        Args:
            i: an index or a name of a linear constraint

        Raises:
            KeyError: if name does not exist
            IndexError: if index is out of range
        """
        if isinstance(i, str):
            i = self._linear_constraints_index[i]
        del self._linear_constraints[i]
        self._linear_constraints_index = {
            cst.name: j for j, cst in enumerate(self._linear_constraints)
        }

    def remove_quadratic_constraint(self, i: Union[str, int]) -> None:
        """Remove a quadratic constraint

        Args:
            i: an index or a name of a quadratic constraint

        Raises:
            KeyError: if name does not exist
            IndexError: if index is out of range
        """
        if isinstance(i, str):
            i = self._quadratic_constraints_index[i]
        del self._quadratic_constraints[i]
        self._quadratic_constraints_index = {
            cst.name: j for j, cst in enumerate(self._quadratic_constraints)
        }

    @property
    def objective(self) -> QuadraticObjective:
        """Returns the quadratic objective.

        Returns:
            The quadratic objective.
        """
        return self._objective

    def minimize(
        self,
        constant: float = 0.0,
        linear: Union[
            ndarray, spmatrix, List[float], Dict[Union[str, int], float]
        ] = None,
        quadratic: Union[
            ndarray,
            spmatrix,
            List[List[float]],
            Dict[Tuple[Union[int, str], Union[int, str]], float],
        ] = None,
    ) -> None:
        """Sets a quadratic objective to be minimized.

        Args:
            constant: the constant offset of the objective.
            linear: the coefficients of the linear part of the objective.
            quadratic: the coefficients of the quadratic part of the objective.

        Returns:
            The created quadratic objective.
        """
        self._objective = QuadraticObjective(
            self, constant, linear, quadratic, QuadraticObjective.Sense.MINIMIZE
        )

    def maximize(
        self,
        constant: float = 0.0,
        linear: Union[
            ndarray, spmatrix, List[float], Dict[Union[str, int], float]
        ] = None,
        quadratic: Union[
            ndarray,
            spmatrix,
            List[List[float]],
            Dict[Tuple[Union[int, str], Union[int, str]], float],
        ] = None,
    ) -> None:
        """Sets a quadratic objective to be maximized.

        Args:
            constant: the constant offset of the objective.
            linear: the coefficients of the linear part of the objective.
            quadratic: the coefficients of the quadratic part of the objective.

        Returns:
            The created quadratic objective.
        """
        self._objective = QuadraticObjective(
            self, constant, linear, quadratic, QuadraticObjective.Sense.MAXIMIZE
        )

    def _copy_from(self, other: "QuadraticProgram", include_name: bool) -> None:
        """Copy another QuadraticProgram to this updating QuadraticProgramElement

        Note: this breaks the consistency of `other`. You cannot use `other` after the copy.

        Args:
            other: The quadratic program to be copied from.
            include_name: Whether this method copies the problem name or not.
        """
        for attr, val in vars(other).items():
            if attr == "_name" and not include_name:
                continue
            if isinstance(val, QuadraticProgramElement):
                val.quadratic_program = self
            if isinstance(val, list):
                for elem in val:
                    if isinstance(elem, QuadraticProgramElement):
                        elem.quadratic_program = self
            setattr(self, attr, val)

    def substitute_variables(
        self,
        constants: Optional[Dict[Union[str, int], float]] = None,
        variables: Optional[
            Dict[Union[str, int], Tuple[Union[str, int], float]]
        ] = None,
    ) -> "QuadraticProgram":
        """Substitutes variables with constants or other variables.

        Args:
            constants: replace variable by constant
                e.g., ``{'x': 2}`` means ``x`` is substituted with 2

            variables: replace variables by weighted other variable
                need to copy everything using name reference to make sure that indices are matched
                correctly. The lower and upper bounds are updated accordingly.
                e.g., ``{'x': ('y', 2)}`` means ``x`` is substituted with ``y * 2``

        Returns:
            An optimization problem by substituting variables with constants or other variables.
            If the substitution is valid, ``QuadraticProgram.status`` is still
            ``QuadraticProgram.Status.VALID``.
            Otherwise, it gets ``QuadraticProgram.Status.INFEASIBLE``.

        Raises:
            QiskitOptimizationError: if the substitution is invalid as follows.

                - Same variable is substituted multiple times.
                - Coefficient of variable substitution is zero.
        """
        # pylint: disable=cyclic-import
        from .substitute_variables import substitute_variables

        return substitute_variables(self, constants, variables)

    def to_ising(self) -> Tuple[SparsePauliOp, float]:
        """Return the Ising Hamiltonian of this problem.

        Variables are mapped to qubits in the same order, i.e.,
        i-th variable is mapped to i-th qubit.
        See https://github.com/Qiskit/qiskit-terra/issues/1148 for details.

        Returns:
            qubit_op: The qubit operator for the problem
            offset: The constant value in the Ising Hamiltonian.

        Raises:
            QiskitOptimizationError: If a variable type is not binary.
            QiskitOptimizationError: If constraints exist in the problem.
        """
        # pylint: disable=cyclic-import
        from ..translators.ising import to_ising

        return to_ising(self)

    def from_ising(
        self,
        qubit_op: BaseOperator,
        offset: float = 0.0,
        linear: bool = False,
    ) -> None:
        r"""Create a quadratic program from a qubit operator and a shift value.

        Variables are mapped to qubits in the same order, i.e.,
        i-th variable is mapped to i-th qubit.
        See https://github.com/Qiskit/qiskit-terra/issues/1148 for details.

        Args:
            qubit_op: The qubit operator of the problem.
            offset: The constant value in the Ising Hamiltonian.
            linear: If linear is True, :math:`x^2` is treated as a linear term
                since :math:`x^2 = x` for :math:`x \in \{0,1\}`.
                Else, :math:`x^2` is treated as a quadratic term.
                The default value is False.

        Raises:
            QiskitOptimizationError: If there are Pauli Xs in any Pauli term
            QiskitOptimizationError: If there are more than 2 Pauli Zs in any Pauli term
            NotImplementedError: If the input operator is a ListOp
        """
        # pylint: disable=cyclic-import
        from ..translators.ising import from_ising

        other = from_ising(qubit_op, offset, linear)
        self._copy_from(other, include_name=False)

    def get_feasibility_info(
        self, x: Union[List[float], np.ndarray]
    ) -> Tuple[bool, List[Variable], List[Constraint]]:
        """Returns whether a solution is feasible or not along with the violations.
        Args:
            x: a solution value, such as returned in an optimizer result.
        Returns:
            feasible: Whether the solution provided is feasible or not.
            List[Variable]: List of variables which are violated.
            List[Constraint]: List of constraints which are violated.

        Raises:
            QiskitOptimizationError: If the input `x` is not same len as total vars
        """
        # if input `x` is not the same len as the total vars, raise an error
        if len(x) != self.get_num_vars():
            raise QiskitOptimizationError(
                f"The size of solution `x`: {len(x)}, does not match the number of problem variables: "
                f"{self.get_num_vars()}"
            )

        # check whether the input satisfy the bounds of the problem
        violated_variables = []
        for i, val in enumerate(x):
            variable = self.get_variable(i)
            if val < variable.lowerbound or variable.upperbound < val:
                violated_variables.append(variable)

        # check whether the input satisfy the constraints of the problem
        violated_constraints = []
        for constraint in cast(List[Constraint], self._linear_constraints) + cast(
            List[Constraint], self._quadratic_constraints
        ):
            lhs = constraint.evaluate(x)
            if constraint.sense == ConstraintSense.LE and lhs > constraint.rhs:
                violated_constraints.append(constraint)
            elif constraint.sense == ConstraintSense.GE and lhs < constraint.rhs:
                violated_constraints.append(constraint)
            elif constraint.sense == ConstraintSense.EQ and not isclose(
                lhs, constraint.rhs
            ):
                violated_constraints.append(constraint)

        feasible = not violated_variables and not violated_constraints

        return feasible, violated_variables, violated_constraints

    def is_feasible(self, x: Union[List[float], np.ndarray]) -> bool:
        """Returns whether a solution is feasible or not.

        Args:
            x: a solution value, such as returned in an optimizer result.

        Returns:
            ``True`` if the solution provided is feasible otherwise ``False``.

        """
        feasible, _, _ = self.get_feasibility_info(x)

        return feasible

    def prettyprint(self, wrap: int = 80) -> str:
        """Returns a pretty printed string of this problem.

        Args:
            wrap: The text width to wrap the output strings. It is disabled by setting 0.
                Note that some strings might exceed this value, for example, a long variable
                name won't be wrapped. The default value is 80.

        Returns:
            A pretty printed string representing the problem.

        Raises:
            QiskitOptimizationError: if there is a non-printable name.
        """
        # pylint: disable=cyclic-import
        from ..translators.prettyprint import prettyprint

        return prettyprint(self, wrap)

    @staticmethod
    def _check_name(name: str, name_type: str) -> None:
        """Displays a warning message if a name string is not printable"""
        if not name.isprintable():
            warn(f"{name_type} name is not printable: {repr(name)}")

linear_constraints: List[LinearConstraint] property

Returns the list of linear constraints of the quadratic program.

Returns:

Type Description
List[LinearConstraint]

List of linear constraints.

linear_constraints_index: Dict[str, int] property

Returns the dictionary that maps the name of a linear constraint to its index.

Returns:

Type Description
Dict[str, int]

The linear constraint index dictionary.

name: str property writable

Returns the name of the quadratic program.

Returns:

Type Description
str

The name of the quadratic program.

objective: QuadraticObjective property

Returns the quadratic objective.

Returns:

Type Description
QuadraticObjective

The quadratic objective.

quadratic_constraints: List[QuadraticConstraint] property

Returns the list of quadratic constraints of the quadratic program.

Returns:

Type Description
List[QuadraticConstraint]

List of quadratic constraints.

quadratic_constraints_index: Dict[str, int] property

Returns the dictionary that maps the name of a quadratic constraint to its index.

Returns:

Type Description
Dict[str, int]

The quadratic constraint index dictionary.

status: QuadraticProgramStatus property

Status of the quadratic program. It can be infeasible due to variable substitution.

Returns:

Type Description
QuadraticProgramStatus

The status of the quadratic program

variables: List[Variable] property

Returns the list of variables of the quadratic program.

Returns:

Type Description
List[Variable]

List of variables.

variables_index: Dict[str, int] property

Returns the dictionary that maps the name of a variable to its index.

Returns:

Type Description
Dict[str, int]

The variable index dictionary.

__init__(name='')

Parameters:

Name Type Description Default
name str

The name of the quadratic program.

''
Source code in q3as/quadratic/problems/quadratic_program.py
def __init__(self, name: str = "") -> None:
    """
    Args:
        name: The name of the quadratic program.
    """
    if not name.isprintable():
        warn("Problem name is not printable")
    self._name = ""
    self.name = name
    self._status = QuadraticProgram.Status.VALID

    self._variables: List[Variable] = []
    self._variables_index: Dict[str, int] = {}

    self._linear_constraints: List[LinearConstraint] = []
    self._linear_constraints_index: Dict[str, int] = {}

    self._quadratic_constraints: List[QuadraticConstraint] = []
    self._quadratic_constraints_index: Dict[str, int] = {}

    self._objective = QuadraticObjective(self)

binary_var(name=None)

Adds a binary variable to the quadratic program.

Parameters:

Name Type Description Default
name Optional[str]

The name of the variable. If it's None or empty "", the default name, e.g., x0, is used.

None

Returns:

Type Description
Variable

The added variable.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already occupied.

Source code in q3as/quadratic/problems/quadratic_program.py
def binary_var(self, name: Optional[str] = None) -> Variable:
    """Adds a binary variable to the quadratic program.

    Args:
        name: The name of the variable.
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.

    Returns:
        The added variable.

    Raises:
        QiskitOptimizationError: if the variable name is already occupied.
    """
    return self._add_variable(0, 1, Variable.Type.BINARY, name)

binary_var_dict(keys, name=None, key_format='{}')

Uses 'var_dict' to construct a dictionary of binary variables

Parameters:

Name Type Description Default
name Optional[str]

The name(s) of the variable(s). If it's None or empty "", the default name, e.g., x0, is used.

None
key_format str

The format used to name/index the variable(s).

'{}'
keys Union[int, Sequence]

If keys: int, it is interpreted as the number of variables to construct. Otherwise, the elements of the sequence are converted to strings via 'str' and substituted into key_format.

required

Returns:

Type Description
Dict[str, Variable]

A dictionary mapping the variable names to variable instances.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already taken.

QiskitOptimizationError

if less than one variable instantiation is attempted.

QiskitOptimizationError

if key_format has more than one substitution or a nested substitution.

Source code in q3as/quadratic/problems/quadratic_program.py
def binary_var_dict(
    self,
    keys: Union[int, Sequence],
    name: Optional[str] = None,
    key_format: str = "{}",
) -> Dict[str, Variable]:
    """
    Uses 'var_dict' to construct a dictionary of binary variables

    Args:
        name: The name(s) of the variable(s).
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
        key_format: The format used to name/index the variable(s).
        keys: If keys: int, it is interpreted as the number of variables to construct.
              Otherwise, the elements of the sequence are converted to strings via 'str' and
              substituted into `key_format`.

    Returns:
        A dictionary mapping the variable names to variable instances.

    Raises:
        QiskitOptimizationError: if the variable name is already taken.
        QiskitOptimizationError: if less than one variable instantiation is attempted.
        QiskitOptimizationError: if `key_format` has more than one substitution or a
                                 nested substitution.
    """
    return self._var_dict(keys, 0, 1, Variable.Type.BINARY, name, key_format)

binary_var_list(keys, name=None, key_format='{}')

Uses 'var_list' to construct a list of binary variables

Parameters:

Name Type Description Default
name Optional[str]

The name(s) of the variable(s). If it's None or empty "", the default name, e.g., x0, is used.

None
key_format str

The format used to name/index the variable(s).

'{}'
keys Union[int, Sequence]

If keys: int, it is interpreted as the number of variables to construct. Otherwise, the elements of the sequence are converted to strings via 'str' and substituted into key_format.

required

Returns:

Type Description
List[Variable]

A list of variable instances.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already taken.

QiskitOptimizationError

if less than one variable instantiation is attempted.

QiskitOptimizationError

if key_format has more than one substitution or a nested substitution.

Source code in q3as/quadratic/problems/quadratic_program.py
def binary_var_list(
    self,
    keys: Union[int, Sequence],
    name: Optional[str] = None,
    key_format: str = "{}",
) -> List[Variable]:
    """
    Uses 'var_list' to construct a list of binary variables

    Args:
        name: The name(s) of the variable(s).
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
        key_format: The format used to name/index the variable(s).
        keys: If keys: int, it is interpreted as the number of variables to construct.
              Otherwise, the elements of the sequence are converted to strings via 'str' and
              substituted into `key_format`.

    Returns:
        A list of variable instances.

    Raises:
        QiskitOptimizationError: if the variable name is already taken.
        QiskitOptimizationError: if less than one variable instantiation is attempted.
        QiskitOptimizationError: if `key_format` has more than one substitution or a
                                 nested substitution.
    """
    return self._var_list(keys, 0, 1, Variable.Type.BINARY, name, key_format)

clear()

Clears the quadratic program, i.e., deletes all variables, constraints, the objective function as well as the name.

Source code in q3as/quadratic/problems/quadratic_program.py
def clear(self) -> None:
    """Clears the quadratic program, i.e., deletes all variables, constraints, the
    objective function as well as the name.
    """
    self._name = ""
    self._status = QuadraticProgram.Status.VALID

    self._variables.clear()
    self._variables_index.clear()

    self._linear_constraints.clear()
    self._linear_constraints_index.clear()

    self._quadratic_constraints.clear()
    self._quadratic_constraints_index.clear()

    self._objective = QuadraticObjective(self)

continuous_var(lowerbound=0, upperbound=INFINITY, name=None)

Adds a continuous variable to the quadratic program.

Parameters:

Name Type Description Default
lowerbound Union[float, int]

The lowerbound of the variable.

0
upperbound Union[float, int]

The upperbound of the variable.

INFINITY
name Optional[str]

The name of the variable. If it's None or empty "", the default name, e.g., x0, is used.

None

Returns:

Type Description
Variable

The added variable.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already occupied.

Source code in q3as/quadratic/problems/quadratic_program.py
def continuous_var(
    self,
    lowerbound: Union[float, int] = 0,
    upperbound: Union[float, int] = INFINITY,
    name: Optional[str] = None,
) -> Variable:
    """Adds a continuous variable to the quadratic program.

    Args:
        lowerbound: The lowerbound of the variable.
        upperbound: The upperbound of the variable.
        name: The name of the variable.
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.

    Returns:
        The added variable.

    Raises:
        QiskitOptimizationError: if the variable name is already occupied.
    """
    return self._add_variable(
        lowerbound, upperbound, Variable.Type.CONTINUOUS, name
    )

continuous_var_dict(keys, lowerbound=0, upperbound=INFINITY, name=None, key_format='{}')

Uses 'var_dict' to construct a dictionary of continuous variables

Parameters:

Name Type Description Default
lowerbound Union[float, int]

The lower bound of the variable(s).

0
upperbound Union[float, int]

The upper bound of the variable(s).

INFINITY
name Optional[str]

The name(s) of the variable(s). If it's None or empty "", the default name, e.g., x0, is used.

None
key_format str

The format used to name/index the variable(s).

'{}'
keys Union[int, Sequence]

If keys: int, it is interpreted as the number of variables to construct. Otherwise, the elements of the sequence are converted to strings via 'str' and substituted into key_format.

required

Returns:

Type Description
Dict[str, Variable]

A dictionary mapping the variable names to variable instances.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already taken.

QiskitOptimizationError

if less than one variable instantiation is attempted.

QiskitOptimizationError

if key_format has more than one substitution or a nested substitution.

Source code in q3as/quadratic/problems/quadratic_program.py
def continuous_var_dict(
    self,
    keys: Union[int, Sequence],
    lowerbound: Union[float, int] = 0,
    upperbound: Union[float, int] = INFINITY,
    name: Optional[str] = None,
    key_format: str = "{}",
) -> Dict[str, Variable]:
    """
    Uses 'var_dict' to construct a dictionary of continuous variables

    Args:
        lowerbound: The lower bound of the variable(s).
        upperbound: The upper bound of the variable(s).
        name: The name(s) of the variable(s).
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
        key_format: The format used to name/index the variable(s).
        keys: If keys: int, it is interpreted as the number of variables to construct.
              Otherwise, the elements of the sequence are converted to strings via 'str' and
              substituted into `key_format`.

    Returns:
        A dictionary mapping the variable names to variable instances.

    Raises:
        QiskitOptimizationError: if the variable name is already taken.
        QiskitOptimizationError: if less than one variable instantiation is attempted.
        QiskitOptimizationError: if `key_format` has more than one substitution or a
                                 nested substitution.
    """
    return self._var_dict(
        keys, lowerbound, upperbound, Variable.Type.CONTINUOUS, name, key_format
    )

continuous_var_list(keys, lowerbound=0, upperbound=INFINITY, name=None, key_format='{}')

Uses 'var_list' to construct a list of continuous variables

Parameters:

Name Type Description Default
lowerbound Union[float, int]

The lower bound of the variable(s).

0
upperbound Union[float, int]

The upper bound of the variable(s).

INFINITY
name Optional[str]

The name(s) of the variable(s). If it's None or empty "", the default name, e.g., x0, is used.

None
key_format str

The format used to name/index the variable(s).

'{}'
keys Union[int, Sequence]

If keys: int, it is interpreted as the number of variables to construct. Otherwise, the elements of the sequence are converted to strings via 'str' and substituted into key_format.

required

Returns:

Type Description
List[Variable]

A list of variable instances.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already taken.

QiskitOptimizationError

if less than one variable instantiation is attempted.

QiskitOptimizationError

if key_format has more than one substitution or a nested substitution.

Source code in q3as/quadratic/problems/quadratic_program.py
def continuous_var_list(
    self,
    keys: Union[int, Sequence],
    lowerbound: Union[float, int] = 0,
    upperbound: Union[float, int] = INFINITY,
    name: Optional[str] = None,
    key_format: str = "{}",
) -> List[Variable]:
    """
    Uses 'var_list' to construct a list of continuous variables

    Args:
        lowerbound: The lower bound of the variable(s).
        upperbound: The upper bound of the variable(s).
        name: The name(s) of the variable(s).
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
        key_format: The format used to name/index the variable(s).
        keys: If keys: int, it is interpreted as the number of variables to construct.
              Otherwise, the elements of the sequence are converted to strings via 'str' and
              substituted into `key_format`.

    Returns:
        A list of variable instances.

    Raises:
        QiskitOptimizationError: if the variable name is already taken.
        QiskitOptimizationError: if less than one variable instantiation is attempted.
        QiskitOptimizationError: if `key_format` has more than one substitution or a
                                 nested substitution.
    """
    return self._var_list(
        keys, lowerbound, upperbound, Variable.Type.CONTINUOUS, name, key_format
    )

from_ising(qubit_op, offset=0.0, linear=False)

Create a quadratic program from a qubit operator and a shift value.

Variables are mapped to qubits in the same order, i.e., i-th variable is mapped to i-th qubit. See https://github.com/Qiskit/qiskit-terra/issues/1148 for details.

Parameters:

Name Type Description Default
qubit_op BaseOperator

The qubit operator of the problem.

required
offset float

The constant value in the Ising Hamiltonian.

0.0
linear bool

If linear is True, :math:x^2 is treated as a linear term since :math:x^2 = x for :math:x \in \{0,1\}. Else, :math:x^2 is treated as a quadratic term. The default value is False.

False

Raises:

Type Description
QiskitOptimizationError

If there are Pauli Xs in any Pauli term

QiskitOptimizationError

If there are more than 2 Pauli Zs in any Pauli term

NotImplementedError

If the input operator is a ListOp

Source code in q3as/quadratic/problems/quadratic_program.py
def from_ising(
    self,
    qubit_op: BaseOperator,
    offset: float = 0.0,
    linear: bool = False,
) -> None:
    r"""Create a quadratic program from a qubit operator and a shift value.

    Variables are mapped to qubits in the same order, i.e.,
    i-th variable is mapped to i-th qubit.
    See https://github.com/Qiskit/qiskit-terra/issues/1148 for details.

    Args:
        qubit_op: The qubit operator of the problem.
        offset: The constant value in the Ising Hamiltonian.
        linear: If linear is True, :math:`x^2` is treated as a linear term
            since :math:`x^2 = x` for :math:`x \in \{0,1\}`.
            Else, :math:`x^2` is treated as a quadratic term.
            The default value is False.

    Raises:
        QiskitOptimizationError: If there are Pauli Xs in any Pauli term
        QiskitOptimizationError: If there are more than 2 Pauli Zs in any Pauli term
        NotImplementedError: If the input operator is a ListOp
    """
    # pylint: disable=cyclic-import
    from ..translators.ising import from_ising

    other = from_ising(qubit_op, offset, linear)
    self._copy_from(other, include_name=False)

get_feasibility_info(x)

Returns whether a solution is feasible or not along with the violations. Args: x: a solution value, such as returned in an optimizer result. Returns: feasible: Whether the solution provided is feasible or not. List[Variable]: List of variables which are violated. List[Constraint]: List of constraints which are violated.

Raises:

Type Description
QiskitOptimizationError

If the input x is not same len as total vars

Source code in q3as/quadratic/problems/quadratic_program.py
def get_feasibility_info(
    self, x: Union[List[float], np.ndarray]
) -> Tuple[bool, List[Variable], List[Constraint]]:
    """Returns whether a solution is feasible or not along with the violations.
    Args:
        x: a solution value, such as returned in an optimizer result.
    Returns:
        feasible: Whether the solution provided is feasible or not.
        List[Variable]: List of variables which are violated.
        List[Constraint]: List of constraints which are violated.

    Raises:
        QiskitOptimizationError: If the input `x` is not same len as total vars
    """
    # if input `x` is not the same len as the total vars, raise an error
    if len(x) != self.get_num_vars():
        raise QiskitOptimizationError(
            f"The size of solution `x`: {len(x)}, does not match the number of problem variables: "
            f"{self.get_num_vars()}"
        )

    # check whether the input satisfy the bounds of the problem
    violated_variables = []
    for i, val in enumerate(x):
        variable = self.get_variable(i)
        if val < variable.lowerbound or variable.upperbound < val:
            violated_variables.append(variable)

    # check whether the input satisfy the constraints of the problem
    violated_constraints = []
    for constraint in cast(List[Constraint], self._linear_constraints) + cast(
        List[Constraint], self._quadratic_constraints
    ):
        lhs = constraint.evaluate(x)
        if constraint.sense == ConstraintSense.LE and lhs > constraint.rhs:
            violated_constraints.append(constraint)
        elif constraint.sense == ConstraintSense.GE and lhs < constraint.rhs:
            violated_constraints.append(constraint)
        elif constraint.sense == ConstraintSense.EQ and not isclose(
            lhs, constraint.rhs
        ):
            violated_constraints.append(constraint)

    feasible = not violated_variables and not violated_constraints

    return feasible, violated_variables, violated_constraints

get_linear_constraint(i)

Returns a linear constraint for a given name or index.

Parameters:

Name Type Description Default
i Union[int, str]

the index or name of the constraint.

required

Returns:

Type Description
LinearConstraint

The corresponding constraint.

Raises:

Type Description
IndexError

if the index is out of the list size

KeyError

if the name does not exist

Source code in q3as/quadratic/problems/quadratic_program.py
def get_linear_constraint(self, i: Union[int, str]) -> LinearConstraint:
    """Returns a linear constraint for a given name or index.

    Args:
        i: the index or name of the constraint.

    Returns:
        The corresponding constraint.

    Raises:
        IndexError: if the index is out of the list size
        KeyError: if the name does not exist
    """
    if isinstance(i, int):
        return self._linear_constraints[i]
    else:
        return self._linear_constraints[self._linear_constraints_index[i]]

get_num_binary_vars()

Returns the total number of binary variables.

Returns:

Type Description
int

The total number of binary variables.

Source code in q3as/quadratic/problems/quadratic_program.py
def get_num_binary_vars(self) -> int:
    """Returns the total number of binary variables.

    Returns:
        The total number of binary variables.
    """
    return self.get_num_vars(Variable.Type.BINARY)

get_num_continuous_vars()

Returns the total number of continuous variables.

Returns:

Type Description
int

The total number of continuous variables.

Source code in q3as/quadratic/problems/quadratic_program.py
def get_num_continuous_vars(self) -> int:
    """Returns the total number of continuous variables.

    Returns:
        The total number of continuous variables.
    """
    return self.get_num_vars(Variable.Type.CONTINUOUS)

get_num_integer_vars()

Returns the total number of integer variables.

Returns:

Type Description
int

The total number of integer variables.

Source code in q3as/quadratic/problems/quadratic_program.py
def get_num_integer_vars(self) -> int:
    """Returns the total number of integer variables.

    Returns:
        The total number of integer variables.
    """
    return self.get_num_vars(Variable.Type.INTEGER)

get_num_linear_constraints()

Returns the number of linear constraints.

Returns:

Type Description
int

The number of linear constraints.

Source code in q3as/quadratic/problems/quadratic_program.py
def get_num_linear_constraints(self) -> int:
    """Returns the number of linear constraints.

    Returns:
        The number of linear constraints.
    """
    return len(self._linear_constraints)

get_num_quadratic_constraints()

Returns the number of quadratic constraints.

Returns:

Type Description
int

The number of quadratic constraints.

Source code in q3as/quadratic/problems/quadratic_program.py
def get_num_quadratic_constraints(self) -> int:
    """Returns the number of quadratic constraints.

    Returns:
        The number of quadratic constraints.
    """
    return len(self._quadratic_constraints)

get_num_vars(vartype=None)

Returns the total number of variables or the number of variables of the specified type.

Parameters:

Name Type Description Default
vartype Optional[VarType]

The type to be filtered on. All variables are counted if None.

None

Returns:

Type Description
int

The total number of variables.

Source code in q3as/quadratic/problems/quadratic_program.py
def get_num_vars(self, vartype: Optional[VarType] = None) -> int:
    """Returns the total number of variables or the number of variables of the specified type.

    Args:
        vartype: The type to be filtered on. All variables are counted if None.

    Returns:
        The total number of variables.
    """
    if vartype:
        return sum(variable.vartype == vartype for variable in self._variables)
    else:
        return len(self._variables)

get_quadratic_constraint(i)

Returns a quadratic constraint for a given name or index.

Parameters:

Name Type Description Default
i Union[int, str]

the index or name of the constraint.

required

Returns:

Type Description
QuadraticConstraint

The corresponding constraint.

Raises:

Type Description
IndexError

if the index is out of the list size

KeyError

if the name does not exist

Source code in q3as/quadratic/problems/quadratic_program.py
def get_quadratic_constraint(self, i: Union[int, str]) -> QuadraticConstraint:
    """Returns a quadratic constraint for a given name or index.

    Args:
        i: the index or name of the constraint.

    Returns:
        The corresponding constraint.

    Raises:
        IndexError: if the index is out of the list size
        KeyError: if the name does not exist
    """
    if isinstance(i, int):
        return self._quadratic_constraints[i]
    else:
        return self._quadratic_constraints[self._quadratic_constraints_index[i]]

get_variable(i)

Returns a variable for a given name or index.

Parameters:

Name Type Description Default
i Union[int, str]

the index or name of the variable.

required

Returns:

Type Description
Variable

The corresponding variable.

Source code in q3as/quadratic/problems/quadratic_program.py
def get_variable(self, i: Union[int, str]) -> Variable:
    """Returns a variable for a given name or index.

    Args:
        i: the index or name of the variable.

    Returns:
        The corresponding variable.
    """
    if isinstance(i, (int, np.integer)):
        return self.variables[i]
    else:
        return self.variables[self._variables_index[i]]

integer_var(lowerbound=0, upperbound=INFINITY, name=None)

Adds an integer variable to the quadratic program.

Parameters:

Name Type Description Default
lowerbound Union[float, int]

The lowerbound of the variable.

0
upperbound Union[float, int]

The upperbound of the variable.

INFINITY
name Optional[str]

The name of the variable. If it's None or empty "", the default name, e.g., x0, is used.

None

Returns:

Type Description
Variable

The added variable.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already occupied.

Source code in q3as/quadratic/problems/quadratic_program.py
def integer_var(
    self,
    lowerbound: Union[float, int] = 0,
    upperbound: Union[float, int] = INFINITY,
    name: Optional[str] = None,
) -> Variable:
    """Adds an integer variable to the quadratic program.

    Args:
        lowerbound: The lowerbound of the variable.
        upperbound: The upperbound of the variable.
        name: The name of the variable.
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.

    Returns:
        The added variable.

    Raises:
        QiskitOptimizationError: if the variable name is already occupied.
    """
    return self._add_variable(lowerbound, upperbound, Variable.Type.INTEGER, name)

integer_var_dict(keys, lowerbound=0, upperbound=INFINITY, name=None, key_format='{}')

Uses 'var_dict' to construct a dictionary of integer variables

Parameters:

Name Type Description Default
lowerbound Union[float, int]

The lower bound of the variable(s).

0
upperbound Union[float, int]

The upper bound of the variable(s).

INFINITY
name Optional[str]

The name(s) of the variable(s). If it's None or empty "", the default name, e.g., x0, is used.

None
key_format str

The format used to name/index the variable(s).

'{}'
keys Union[int, Sequence]

If keys: int, it is interpreted as the number of variables to construct. Otherwise, the elements of the sequence are converted to strings via 'str' and substituted into key_format.

required

Returns:

Type Description
Dict[str, Variable]

A dictionary mapping the variable names to variable instances.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already taken.

QiskitOptimizationError

if less than one variable instantiation is attempted.

QiskitOptimizationError

if key_format has more than one substitution or a nested substitution.

Source code in q3as/quadratic/problems/quadratic_program.py
def integer_var_dict(
    self,
    keys: Union[int, Sequence],
    lowerbound: Union[float, int] = 0,
    upperbound: Union[float, int] = INFINITY,
    name: Optional[str] = None,
    key_format: str = "{}",
) -> Dict[str, Variable]:
    """
    Uses 'var_dict' to construct a dictionary of integer variables

    Args:
        lowerbound: The lower bound of the variable(s).
        upperbound: The upper bound of the variable(s).
        name: The name(s) of the variable(s).
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
        key_format: The format used to name/index the variable(s).
        keys: If keys: int, it is interpreted as the number of variables to construct.
              Otherwise, the elements of the sequence are converted to strings via 'str' and
              substituted into `key_format`.

    Returns:
        A dictionary mapping the variable names to variable instances.

    Raises:
        QiskitOptimizationError: if the variable name is already taken.
        QiskitOptimizationError: if less than one variable instantiation is attempted.
        QiskitOptimizationError: if `key_format` has more than one substitution or a
                                 nested substitution.
    """
    return self._var_dict(
        keys, lowerbound, upperbound, Variable.Type.INTEGER, name, key_format
    )

integer_var_list(keys, lowerbound=0, upperbound=INFINITY, name=None, key_format='{}')

Uses 'var_list' to construct a list of integer variables

Parameters:

Name Type Description Default
lowerbound Union[float, int]

The lower bound of the variable(s).

0
upperbound Union[float, int]

The upper bound of the variable(s).

INFINITY
name Optional[str]

The name(s) of the variable(s). If it's None or empty "", the default name, e.g., x0, is used.

None
key_format str

The format used to name/index the variable(s).

'{}'
keys Union[int, Sequence]

If keys: int, it is interpreted as the number of variables to construct. Otherwise, the elements of the sequence are converted to strings via 'str' and substituted into key_format.

required

Returns:

Type Description
List[Variable]

A list of variable instances.

Raises:

Type Description
QiskitOptimizationError

if the variable name is already taken.

QiskitOptimizationError

if less than one variable instantiation is attempted.

QiskitOptimizationError

if key_format has more than one substitution or a nested substitution.

Source code in q3as/quadratic/problems/quadratic_program.py
def integer_var_list(
    self,
    keys: Union[int, Sequence],
    lowerbound: Union[float, int] = 0,
    upperbound: Union[float, int] = INFINITY,
    name: Optional[str] = None,
    key_format: str = "{}",
) -> List[Variable]:
    """
    Uses 'var_list' to construct a list of integer variables

    Args:
        lowerbound: The lower bound of the variable(s).
        upperbound: The upper bound of the variable(s).
        name: The name(s) of the variable(s).
            If it's ``None`` or empty ``""``, the default name, e.g., ``x0``, is used.
        key_format: The format used to name/index the variable(s).
        keys: If keys: int, it is interpreted as the number of variables to construct.
              Otherwise, the elements of the sequence are converted to strings via 'str' and
              substituted into `key_format`.

    Returns:
        A list of variable instances.

    Raises:
        QiskitOptimizationError: if the variable name is already taken.
        QiskitOptimizationError: if less than one variable instantiation is attempted.
        QiskitOptimizationError: if `key_format` has more than one substitution or a
                                 nested substitution.
    """
    return self._var_list(
        keys, lowerbound, upperbound, Variable.Type.INTEGER, name, key_format
    )

is_feasible(x)

Returns whether a solution is feasible or not.

Parameters:

Name Type Description Default
x Union[List[float], ndarray]

a solution value, such as returned in an optimizer result.

required

Returns:

Type Description
bool

True if the solution provided is feasible otherwise False.

Source code in q3as/quadratic/problems/quadratic_program.py
def is_feasible(self, x: Union[List[float], np.ndarray]) -> bool:
    """Returns whether a solution is feasible or not.

    Args:
        x: a solution value, such as returned in an optimizer result.

    Returns:
        ``True`` if the solution provided is feasible otherwise ``False``.

    """
    feasible, _, _ = self.get_feasibility_info(x)

    return feasible

linear_constraint(linear=None, sense='<=', rhs=0.0, name=None)

Adds a linear equality constraint to the quadratic program of the form

(linear * x) sense rhs.

Parameters:

Name Type Description Default
linear Union[ndarray, spmatrix, List[float], Dict[Union[int, str], float]]

The linear coefficients of the left-hand side of the constraint.

None
sense Union[str, ConstraintSense]

The sense of the constraint,

  • ==, =, E, and EQ denote 'equal to'.
  • >=, >, G, and GE denote 'greater-than-or-equal-to'.
  • <=, <, L, and LE denote 'less-than-or-equal-to'.
'<='
rhs float

The right-hand side of the constraint.

0.0
name Optional[str]

The name of the constraint. If it's None or empty "", the default name, e.g., c0, is used.

None

Returns:

Type Description
LinearConstraint

The added constraint.

Raises:

Type Description
QiskitOptimizationError

if the constraint name already exists or the sense is not valid.

Source code in q3as/quadratic/problems/quadratic_program.py
def linear_constraint(
    self,
    linear: Union[
        ndarray, spmatrix, List[float], Dict[Union[int, str], float]
    ] = None,
    sense: Union[str, ConstraintSense] = "<=",
    rhs: float = 0.0,
    name: Optional[str] = None,
) -> LinearConstraint:
    """Adds a linear equality constraint to the quadratic program of the form:
        ``(linear * x) sense rhs``.

    Args:
        linear: The linear coefficients of the left-hand side of the constraint.
        sense: The sense of the constraint,

            - ``==``, ``=``, ``E``, and ``EQ`` denote 'equal to'.
            - ``>=``, ``>``, ``G``, and ``GE`` denote 'greater-than-or-equal-to'.
            - ``<=``, ``<``, ``L``, and ``LE`` denote 'less-than-or-equal-to'.

        rhs: The right-hand side of the constraint.
        name: The name of the constraint.
            If it's ``None`` or empty ``""``, the default name, e.g., ``c0``, is used.

    Returns:
        The added constraint.

    Raises:
        QiskitOptimizationError: if the constraint name already exists or the sense is not
            valid.
    """
    if name:
        if name in self.linear_constraints_index:
            raise QiskitOptimizationError(
                f"Linear constraint's name already exists: {name}"
            )
        self._check_name(name, "Linear constraint")
    else:
        k = self.get_num_linear_constraints()
        while f"c{k}" in self.linear_constraints_index:
            k += 1
        name = f"c{k}"
    self.linear_constraints_index[name] = len(self.linear_constraints)
    if linear is None:
        linear = {}
    constraint = LinearConstraint(
        self, name, linear, Constraint.Sense.convert(sense), rhs
    )
    self.linear_constraints.append(constraint)
    return constraint

maximize(constant=0.0, linear=None, quadratic=None)

Sets a quadratic objective to be maximized.

Parameters:

Name Type Description Default
constant float

the constant offset of the objective.

0.0
linear Union[ndarray, spmatrix, List[float], Dict[Union[str, int], float]]

the coefficients of the linear part of the objective.

None
quadratic Union[ndarray, spmatrix, List[List[float]], Dict[Tuple[Union[int, str], Union[int, str]], float]]

the coefficients of the quadratic part of the objective.

None

Returns:

Type Description
None

The created quadratic objective.

Source code in q3as/quadratic/problems/quadratic_program.py
def maximize(
    self,
    constant: float = 0.0,
    linear: Union[
        ndarray, spmatrix, List[float], Dict[Union[str, int], float]
    ] = None,
    quadratic: Union[
        ndarray,
        spmatrix,
        List[List[float]],
        Dict[Tuple[Union[int, str], Union[int, str]], float],
    ] = None,
) -> None:
    """Sets a quadratic objective to be maximized.

    Args:
        constant: the constant offset of the objective.
        linear: the coefficients of the linear part of the objective.
        quadratic: the coefficients of the quadratic part of the objective.

    Returns:
        The created quadratic objective.
    """
    self._objective = QuadraticObjective(
        self, constant, linear, quadratic, QuadraticObjective.Sense.MAXIMIZE
    )

minimize(constant=0.0, linear=None, quadratic=None)

Sets a quadratic objective to be minimized.

Parameters:

Name Type Description Default
constant float

the constant offset of the objective.

0.0
linear Union[ndarray, spmatrix, List[float], Dict[Union[str, int], float]]

the coefficients of the linear part of the objective.

None
quadratic Union[ndarray, spmatrix, List[List[float]], Dict[Tuple[Union[int, str], Union[int, str]], float]]

the coefficients of the quadratic part of the objective.

None

Returns:

Type Description
None

The created quadratic objective.

Source code in q3as/quadratic/problems/quadratic_program.py
def minimize(
    self,
    constant: float = 0.0,
    linear: Union[
        ndarray, spmatrix, List[float], Dict[Union[str, int], float]
    ] = None,
    quadratic: Union[
        ndarray,
        spmatrix,
        List[List[float]],
        Dict[Tuple[Union[int, str], Union[int, str]], float],
    ] = None,
) -> None:
    """Sets a quadratic objective to be minimized.

    Args:
        constant: the constant offset of the objective.
        linear: the coefficients of the linear part of the objective.
        quadratic: the coefficients of the quadratic part of the objective.

    Returns:
        The created quadratic objective.
    """
    self._objective = QuadraticObjective(
        self, constant, linear, quadratic, QuadraticObjective.Sense.MINIMIZE
    )

prettyprint(wrap=80)

Returns a pretty printed string of this problem.

Parameters:

Name Type Description Default
wrap int

The text width to wrap the output strings. It is disabled by setting 0. Note that some strings might exceed this value, for example, a long variable name won't be wrapped. The default value is 80.

80

Returns:

Type Description
str

A pretty printed string representing the problem.

Raises:

Type Description
QiskitOptimizationError

if there is a non-printable name.

Source code in q3as/quadratic/problems/quadratic_program.py
def prettyprint(self, wrap: int = 80) -> str:
    """Returns a pretty printed string of this problem.

    Args:
        wrap: The text width to wrap the output strings. It is disabled by setting 0.
            Note that some strings might exceed this value, for example, a long variable
            name won't be wrapped. The default value is 80.

    Returns:
        A pretty printed string representing the problem.

    Raises:
        QiskitOptimizationError: if there is a non-printable name.
    """
    # pylint: disable=cyclic-import
    from ..translators.prettyprint import prettyprint

    return prettyprint(self, wrap)

quadratic_constraint(linear=None, quadratic=None, sense='<=', rhs=0.0, name=None)

Adds a quadratic equality constraint to the quadratic program of the form

(x * quadratic * x + linear * x) sense rhs.

Parameters:

Name Type Description Default
linear Union[ndarray, spmatrix, List[float], Dict[Union[int, str], float]]

The linear coefficients of the constraint.

None
quadratic Union[ndarray, spmatrix, List[List[float]], Dict[Tuple[Union[int, str], Union[int, str]], float]]

The quadratic coefficients of the constraint.

None
sense Union[str, ConstraintSense]

The sense of the constraint,

  • ==, =, E, and EQ denote 'equal to'.
  • >=, >, G, and GE denote 'greater-than-or-equal-to'.
  • <=, <, L, and LE denote 'less-than-or-equal-to'.
'<='
rhs float

The right-hand side of the constraint.

0.0
name Optional[str]

The name of the constraint. If it's None or empty "", the default name, e.g., q0, is used.

None

Returns:

Type Description
QuadraticConstraint

The added constraint.

Raises:

Type Description
QiskitOptimizationError

if the constraint name already exists.

Source code in q3as/quadratic/problems/quadratic_program.py
def quadratic_constraint(
    self,
    linear: Union[
        ndarray, spmatrix, List[float], Dict[Union[int, str], float]
    ] = None,
    quadratic: Union[
        ndarray,
        spmatrix,
        List[List[float]],
        Dict[Tuple[Union[int, str], Union[int, str]], float],
    ] = None,
    sense: Union[str, ConstraintSense] = "<=",
    rhs: float = 0.0,
    name: Optional[str] = None,
) -> QuadraticConstraint:
    """Adds a quadratic equality constraint to the quadratic program of the form:
        ``(x * quadratic * x + linear * x) sense rhs``.

    Args:
        linear: The linear coefficients of the constraint.
        quadratic: The quadratic coefficients of the constraint.
        sense: The sense of the constraint,

            - ``==``, ``=``, ``E``, and ``EQ`` denote 'equal to'.
            - ``>=``, ``>``, ``G``, and ``GE`` denote 'greater-than-or-equal-to'.
            - ``<=``, ``<``, ``L``, and ``LE`` denote 'less-than-or-equal-to'.

        rhs: The right-hand side of the constraint.
        name: The name of the constraint.
            If it's ``None`` or empty ``""``, the default name, e.g., ``q0``, is used.

    Returns:
        The added constraint.

    Raises:
        QiskitOptimizationError: if the constraint name already exists.
    """
    if name:
        if name in self.quadratic_constraints_index:
            raise QiskitOptimizationError(
                f"Quadratic constraint name already exists: {name}"
            )
        self._check_name(name, "Quadratic constraint")
    else:
        k = self.get_num_quadratic_constraints()
        while f"q{k}" in self.quadratic_constraints_index:
            k += 1
        name = f"q{k}"
    self.quadratic_constraints_index[name] = len(self.quadratic_constraints)
    if linear is None:
        linear = {}
    if quadratic is None:
        quadratic = {}
    constraint = QuadraticConstraint(
        self, name, linear, quadratic, Constraint.Sense.convert(sense), rhs
    )
    self.quadratic_constraints.append(constraint)
    return constraint

remove_linear_constraint(i)

Remove a linear constraint

Parameters:

Name Type Description Default
i Union[str, int]

an index or a name of a linear constraint

required

Raises:

Type Description
KeyError

if name does not exist

IndexError

if index is out of range

Source code in q3as/quadratic/problems/quadratic_program.py
def remove_linear_constraint(self, i: Union[str, int]) -> None:
    """Remove a linear constraint

    Args:
        i: an index or a name of a linear constraint

    Raises:
        KeyError: if name does not exist
        IndexError: if index is out of range
    """
    if isinstance(i, str):
        i = self._linear_constraints_index[i]
    del self._linear_constraints[i]
    self._linear_constraints_index = {
        cst.name: j for j, cst in enumerate(self._linear_constraints)
    }

remove_quadratic_constraint(i)

Remove a quadratic constraint

Parameters:

Name Type Description Default
i Union[str, int]

an index or a name of a quadratic constraint

required

Raises:

Type Description
KeyError

if name does not exist

IndexError

if index is out of range

Source code in q3as/quadratic/problems/quadratic_program.py
def remove_quadratic_constraint(self, i: Union[str, int]) -> None:
    """Remove a quadratic constraint

    Args:
        i: an index or a name of a quadratic constraint

    Raises:
        KeyError: if name does not exist
        IndexError: if index is out of range
    """
    if isinstance(i, str):
        i = self._quadratic_constraints_index[i]
    del self._quadratic_constraints[i]
    self._quadratic_constraints_index = {
        cst.name: j for j, cst in enumerate(self._quadratic_constraints)
    }

substitute_variables(constants=None, variables=None)

Substitutes variables with constants or other variables.

Parameters:

Name Type Description Default
constants Optional[Dict[Union[str, int], float]]

replace variable by constant e.g., {'x': 2} means x is substituted with 2

None
variables Optional[Dict[Union[str, int], Tuple[Union[str, int], float]]]

replace variables by weighted other variable need to copy everything using name reference to make sure that indices are matched correctly. The lower and upper bounds are updated accordingly. e.g., {'x': ('y', 2)} means x is substituted with y * 2

None

Returns:

Type Description
QuadraticProgram

An optimization problem by substituting variables with constants or other variables.

QuadraticProgram

If the substitution is valid, QuadraticProgram.status is still

QuadraticProgram

QuadraticProgram.Status.VALID.

QuadraticProgram

Otherwise, it gets QuadraticProgram.Status.INFEASIBLE.

Raises:

Type Description
QiskitOptimizationError

if the substitution is invalid as follows.

  • Same variable is substituted multiple times.
  • Coefficient of variable substitution is zero.
Source code in q3as/quadratic/problems/quadratic_program.py
def substitute_variables(
    self,
    constants: Optional[Dict[Union[str, int], float]] = None,
    variables: Optional[
        Dict[Union[str, int], Tuple[Union[str, int], float]]
    ] = None,
) -> "QuadraticProgram":
    """Substitutes variables with constants or other variables.

    Args:
        constants: replace variable by constant
            e.g., ``{'x': 2}`` means ``x`` is substituted with 2

        variables: replace variables by weighted other variable
            need to copy everything using name reference to make sure that indices are matched
            correctly. The lower and upper bounds are updated accordingly.
            e.g., ``{'x': ('y', 2)}`` means ``x`` is substituted with ``y * 2``

    Returns:
        An optimization problem by substituting variables with constants or other variables.
        If the substitution is valid, ``QuadraticProgram.status`` is still
        ``QuadraticProgram.Status.VALID``.
        Otherwise, it gets ``QuadraticProgram.Status.INFEASIBLE``.

    Raises:
        QiskitOptimizationError: if the substitution is invalid as follows.

            - Same variable is substituted multiple times.
            - Coefficient of variable substitution is zero.
    """
    # pylint: disable=cyclic-import
    from .substitute_variables import substitute_variables

    return substitute_variables(self, constants, variables)

to_ising()

Return the Ising Hamiltonian of this problem.

Variables are mapped to qubits in the same order, i.e., i-th variable is mapped to i-th qubit. See https://github.com/Qiskit/qiskit-terra/issues/1148 for details.

Returns:

Name Type Description
qubit_op SparsePauliOp

The qubit operator for the problem

offset float

The constant value in the Ising Hamiltonian.

Raises:

Type Description
QiskitOptimizationError

If a variable type is not binary.

QiskitOptimizationError

If constraints exist in the problem.

Source code in q3as/quadratic/problems/quadratic_program.py
def to_ising(self) -> Tuple[SparsePauliOp, float]:
    """Return the Ising Hamiltonian of this problem.

    Variables are mapped to qubits in the same order, i.e.,
    i-th variable is mapped to i-th qubit.
    See https://github.com/Qiskit/qiskit-terra/issues/1148 for details.

    Returns:
        qubit_op: The qubit operator for the problem
        offset: The constant value in the Ising Hamiltonian.

    Raises:
        QiskitOptimizationError: If a variable type is not binary.
        QiskitOptimizationError: If constraints exist in the problem.
    """
    # pylint: disable=cyclic-import
    from ..translators.ising import to_ising

    return to_ising(self)