This file is indexed.

/usr/share/pyshared/cvxopt/msk.py is in python-cvxopt 1.1.4-1.2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
"""
CVXOPT interface for MOSEK 6.0
"""

# Copyright 2010-2011 L. Vandenberghe.
# Copyright 2004-2009 J. Dahl and L. Vandenberghe.
# 
# This file is part of CVXOPT version 1.1.4.
#
# CVXOPT is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# CVXOPT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import mosek
from cvxopt import matrix, spmatrix, sparse
from mosek.array import array, zeros
env = mosek.Env()
env.init()
def streamprinter(text): print(text)
env.set_Stream (mosek.streamtype.log, streamprinter)

inf = 0.0

options = {}

def lp(c, G, h, A=None, b=None):
    """
    Solves a pair of primal and dual LPs 

        minimize    c'*x             maximize    -h'*z - b'*y 
        subject to  G*x + s = h      subject to  G'*z + A'*y + c = 0
                    A*x = b                      z >= 0.
                    s >= 0
                    
    using MOSEK 6.0.

    (solsta, x, z, y) = lp(c, G, h, A=None, b=None).

    Input arguments 

        G is m x n, h is m x 1, A is p x n, b is p x 1.  G and A must be 
        dense or sparse 'd' matrices.   h and b are dense 'd' matrices 
        with one column.  The default values for A and b are empty 
        matrices with zero rows.


    Return values

        solsta is a MOSEK solution status key.

            If solsta is mosek.solsta.optimal, then (x, y, z) contains the 
                primal-dual solution.
            If solsta is mosek.solsta.prim_infeas_cer, then (x, y, z) is a 
                certificate of primal infeasibility.
            If solsta is mosek.solsta.dual_infeas_cer, then (x, y, z) is a 
                certificate of dual infeasibility.
            If solsta is mosek.solsta.unknown, then (x, y, z) are all None.

            Other return values for solsta include:  
                mosek.solsta.dual_feas  
                mosek.solsta.near_dual_feas
                mosek.solsta.near_optimal
                mosek.solsta.near_prim_and_dual_feas
                mosek.solsta.near_prim_feas
                mosek.solsta.prim_and_dual_feas
                mosek.solsta.prim_feas
             in which case the (x,y,z) value may not be well-defined,
             c.f., section 17.48 of the MOSEK Python API manual.
        
        x, y, z  the primal-dual solution.                    

    Options are passed to MOSEK solvers via the msk.options dictionary. 
    For example, the following turns off output from the MOSEK solvers
    
        >>> msk.options = {mosek.iparam.log: 0} 
    
    see chapter 15 of the MOSEK Python API manual.                    
    """

    if type(c) is not matrix or c.typecode != 'd' or c.size[1] != 1: 
        raise TypeError("'c' must be a dense column matrix")
    n = c.size[0]
    if n < 1: raise ValueError("number of variables must be at least 1")

    if (type(G) is not matrix and type(G) is not spmatrix) or \
        G.typecode != 'd' or G.size[1] != n:
        raise TypeError("'G' must be a dense or sparse 'd' matrix "\
            "with %d columns" %n)
    m = G.size[0]
    if m is 0: raise ValueError("m cannot be 0")

    if type(h) is not matrix or h.typecode != 'd' or h.size != (m,1):
        raise TypeError("'h' must be a 'd' matrix of size (%d,1)" %m)

    if A is None:  A = spmatrix([], [], [], (0,n), 'd')
    if (type(A) is not matrix and type(A) is not spmatrix) or \
        A.typecode != 'd' or A.size[1] != n:
        raise TypeError("'A' must be a dense or sparse 'd' matrix "\
            "with %d columns" %n)
    p = A.size[0]
    if b is None: b = matrix(0.0, (0,1))
    if type(b) is not matrix or b.typecode != 'd' or b.size != (p,1): 
        raise TypeError("'b' must be a dense matrix of size (%d,1)" %p)
 
    bkc = m*[ mosek.boundkey.up ] + p*[ mosek.boundkey.fx ]
    blc = m*[ -inf ] + [ bi for bi in b ]
    buc = matrix([h, b])

    bkx = n*[mosek.boundkey.fr] 
    blx = n*[ -inf ] 
    bux = n*[ +inf ]

    colptr, asub, acof = sparse([G,A]).CCS
    aptrb, aptre = colptr[:-1], colptr[1:]

    task = env.Task(0,0) 
    task.set_Stream (mosek.streamtype.log, streamprinter) 

    # set MOSEK options 
    for (param, val) in options.items():
        if str(param)[:6] == "iparam":
            task.putintparam(param, val)
        elif str(param)[:6] == "dparam":
            task.putdouparam(param, val)
        elif str(param)[:6] == "sparam":
            task.putstrparam(param, val)
        else:
            raise ValueError("invalid MOSEK parameter: " + str(param))

    task.inputdata (m+p, # number of constraints
                    n,   # number of variables
                    array(c), # linear objective coefficients  
                    0.0, # objective fixed value  
                    array(aptrb), 
                    array(aptre), 
                    array(asub),
                    array(acof), 
                    bkc,
                    blc,
                    buc, 
                    bkx,
                    blx,
                    bux) 

    task.putobjsense(mosek.objsense.minimize)

    task.optimize()

    task.solutionsummary (mosek.streamtype.msg); 

    prosta, solsta = task.getsolutionstatus(mosek.soltype.bas)

    x, z = zeros(n, float), zeros(m, float)
    task.getsolutionslice(mosek.soltype.bas, mosek.solitem.xx, 0, n, x) 
    task.getsolutionslice(mosek.soltype.bas, mosek.solitem.suc, 0, m, z) 
    x, z = matrix(x), matrix(z)
    
    if p is not 0:
        yu, yl = zeros(p, float), zeros(p, float)
        task.getsolutionslice(mosek.soltype.bas, mosek.solitem.suc, m, 
            m+p, yu) 
        task.getsolutionslice(mosek.soltype.bas, mosek.solitem.slc, m, 
            m+p, yl) 
        y = matrix(yu) - matrix(yl)
    else:
        y = matrix(0.0, (0,1))

    if (solsta is mosek.solsta.unknown):
        return (solsta, None, None, None)
    else:
        return (solsta, x, z, y)


def conelp(c, G, h, dims = None):
    """
    Solves a pair of primal and dual SOCPs

        minimize    c'*x
        subject to  G*x + s = h
                    s >= 0

        maximize    -h'*z 
        subject to  G'*z + c = 0
                    z >= 0 

    using MOSEK 6.0.   

    The inequalities are with respect to a cone C defined as the Cartesian
    product of N + 1 cones:
    
        C = C_0 x C_1 x .... x C_N x C_{N+1}.

    The first cone C_0 is the nonnegative orthant of dimension ml.
    The other cones are second order cones of dimension mq[0], ..., 
    mq[N-1].  The second order cone of dimension m is defined as
    
        { (u0, u1) in R x R^{m-1} | u0 >= ||u1||_2 }.

    The formats of G and h are identical to that used in solvers.conelp(), 
    except that only componentwise and second order cone inequalities are 
    (dims['s'] must be zero, if defined).

    Input arguments.
   
        c is a dense 'd' matrix of size (n,1).

        dims is a dictionary with the dimensions of the components of C.  
        It has three fields.
        - dims['l'] = ml, the dimension of the nonnegative orthant C_0.
          (ml >= 0.)
        - dims['q'] = mq = [ mq[0], mq[1], ..., mq[N-1] ], a list of N 
          integers with the dimensions of the second order cones C_1, ..., 
          C_N.  (N >= 0 and mq[k] >= 1.)
        The default value of dims is {'l': G.size[0], 'q': []}.

        G is a dense or sparse 'd' matrix of size (K,n), where

            K = ml + mq[0] + ... + mq[N-1].

        Each column of G describes a vector 

            v = ( v_0, v_1, ..., v_N, vec(v_{N+1}) )

        in V = R^ml x R^mq[0] x ... x R^mq[N-1] stored as a column vector.

        h is a dense 'd' matrix of size (K,1), representing a vector in V,
        in the same format as the columns of G.
    

 
    Return values

        solsta is a MOSEK solution status key.

            If solsta is mosek.solsta.optimal,
                then (x, zl, zq) contains the primal-dual solution.
            If solsta is moseksolsta.prim_infeas_cer,
                then (x, zl, zq) is a certificate of dual infeasibility.
            If solsta is moseksolsta.dual_infeas_cer,
                then (x, zl, zq) is a certificate of primal infeasibility.
            If solsta is mosek.solsta.unknown,
                then (x, zl, zq) are all None

            Other return values for solsta include:  
                mosek.solsta.dual_feas  
                mosek.solsta.near_dual_feas
                mosek.solsta.near_optimal
                mosek.solsta.near_prim_and_dual_feas
                mosek.solsta.near_prim_feas
                mosek.solsta.prim_and_dual_feas
                mosek.solsta.prim_feas
            in which case the (x,y,z) value may not be well-defined,
            c.f., section 17.48 of the MOSEK Python API manual.
        
        x, z the primal-dual solution.


    Options are passed to MOSEK solvers via the msk.options dictionary, 
    e.g., the following turns off output from the MOSEK solvers
    
        >>> msk.options = {mosek.iparam.log:0} 
    
    see chapter 15 of the MOSEK Python API manual.                    
    """

    if dims is None: 
        (solsta, x, y, z) = lp(c, G, h)
        return (solsta, x, z, None)

    try:
        if len(dims['s']) > 0: raise ValueError("dims['s'] must be zero")
    except:
        pass

    N, n = G.size
    ml, mq = dims['l'], dims['q']
    cdim = ml + sum(mq)
    if cdim is 0: raise ValueError("ml+mq cannot be 0")

    # Data for kth 'q' constraint are found in rows indq[k]:indq[k+1] of G.
    indq = [ dims['l'] ]  
    for k in dims['q']:  indq = indq + [ indq[-1] + k ] 

    if type(h) is not matrix or h.typecode != 'd' or h.size[1] != 1:
        raise TypeError("'h' must be a 'd' matrix with 1 column")
    if type(G) is matrix or type(G) is spmatrix:
        if G.typecode != 'd' or G.size[0] != cdim:
            raise TypeError("'G' must be a 'd' matrix with %d rows " %cdim)
        if h.size[0] != cdim:
            raise TypeError("'h' must have %d rows" %cdim)
    else: 
        raise TypeError("'G' must be a matrix")

    if min(dims['q'])<1: raise TypeError(
        "dimensions of quadratic cones must be positive")

    bkc = n*[ mosek.boundkey.fx ] 
    blc = array(-c)
    buc = array(-c)

    bkx = ml*[ mosek.boundkey.lo ] + sum(mq)*[ mosek.boundkey.fr ]
    blx = ml*[ 0.0 ] + sum(mq)*[ -inf ]
    bux = N*[ +inf ] 

    c   = array(-h)       
    
    colptr, asub, acof = sparse([G.T]).CCS
    aptrb, aptre = colptr[:-1], colptr[1:]

    task = env.Task(0,0) 
    task.set_Stream (mosek.streamtype.log, streamprinter) 

    # set MOSEK options 
    for (param, val) in options.items():
        if str(param)[:6] == "iparam":
            task.putintparam(param, val)
        elif str(param)[:6] == "dparam":
            task.putdouparam(param, val)
        elif str(param)[:6] == "sparam":
            task.putstrparam(param, val)
        else:
            raise ValueError("invalid MOSEK parameter: "+str(param))

    task.inputdata (n,   # number of constraints
                    N,   # number of variables
                    c,   # linear objective coefficients  
                    0.0, # objective fixed value  
                    array(aptrb), 
                    array(aptre), 
                    array(asub),
                    array(acof), 
                    bkc,
                    blc,
                    buc, 
                    bkx,
                    blx,
                    bux) 

    task.putobjsense(mosek.objsense.maximize)

    for k in range(len(mq)):
        task.appendcone(mosek.conetype.quad, 0.0, 
                        array(range(ml+sum(mq[:k]),ml+sum(mq[:k+1]))))
    task.optimize()

    task.solutionsummary (mosek.streamtype.msg); 

    prosta, solsta = task.getsolutionstatus(mosek.soltype.itr)

    xu, xl, zq = zeros(n, float), zeros(n, float), zeros(sum(mq), float)
    task.getsolutionslice(mosek.soltype.itr, mosek.solitem.slc, 0, n, xl) 
    task.getsolutionslice(mosek.soltype.itr, mosek.solitem.suc, 0, n, xu) 
    task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, ml, N, zq) 
    x = matrix(xu-xl)
    zq = matrix(zq)

    if ml:
        zl = zeros(ml, float)
        task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, ml, 
            zl) 
        zl = matrix(zl)
    else:
        zl = matrix(0.0, (0,1))

    if (solsta is mosek.solsta.unknown):
        return (solsta, None, None)
    else:
        return (solsta, x, matrix([zl, zq]))



def socp(c, Gl = None, hl = None, Gq = None, hq = None):
    """
    Solves a pair of primal and dual SOCPs

        minimize    c'*x             
        subject to  Gl*x + sl = hl      
                    Gq[k]*x + sq[k] = hq[k],  k = 0, ..., N-1
                    sl >= 0,  
                    sq[k] >= 0, k = 0, ..., N-1

        maximize    -hl'*zl - sum_k hq[k]'*zq[k] 
        subject to  Gl'*zl + sum_k Gq[k]'*zq[k] + c = 0
                    zl >= 0,  zq[k] >= 0, k = 0, ..., N-1.
                    
    using MOSEK 6.0.

    solsta, x, zl, zq = socp(c, Gl = None, hl = None, Gq = None, hq = None)

    Return values

        solsta is a MOSEK solution status key.
            If solsta is mosek.solsta.optimal,
                then (x, zl, zq) contains the primal-dual solution.
            If solsta is mosek.solsta.prim_infeas_cer,
                then (x, zl, zq) is a certificate of dual infeasibility.
            If solsta is mosek.solsta.dual_infeas_cer,
                then (x, zl, zq) is a certificate of primal infeasibility.
            If solsta is mosek.solsta.unknown,
                then (x, zl, zq) are all None

            Other return values for solsta include:  
                mosek.solsta.dual_feas  
                mosek.solsta.near_dual_feas
                mosek.solsta.near_optimal
                mosek.solsta.near_prim_and_dual_feas
                mosek.solsta.near_prim_feas
                mosek.solsta.prim_and_dual_feas
                mosek.solsta.prim_feas
             in which case the (x,y,z) value may not be well-defined,
             c.f., section 17.48 of the MOSEK Python API manual.
        
        x, zl, zq  the primal-dual solution.


    Options are passed to MOSEK solvers via the msk.options dictionary, 
    e.g., the following turns off output from the MOSEK solvers
    
        >>> msk.options = {mosek.iparam.log: 0} 
    
    see chapter 15 of the MOSEK Python API manual.                    
    """

    if type(c) is not matrix or c.typecode != 'd' or c.size[1] != 1: 
        raise TypeError("'c' must be a dense column matrix")
    n = c.size[0]
    if n < 1: raise ValueError("number of variables must be at least 1")

    if Gl is None:  Gl = spmatrix([], [], [], (0,n), tc='d')
    if (type(Gl) is not matrix and type(Gl) is not spmatrix) or \
        Gl.typecode != 'd' or Gl.size[1] != n:
        raise TypeError("'Gl' must be a dense or sparse 'd' matrix "\
            "with %d columns" %n)
    ml = Gl.size[0]
    if hl is None: hl = matrix(0.0, (0,1))
    if type(hl) is not matrix or hl.typecode != 'd' or \
        hl.size != (ml,1):
        raise TypeError("'hl' must be a dense 'd' matrix of " \
            "size (%d,1)" %ml)

    if Gq is None: Gq = []
    if type(Gq) is not list or [ G for G in Gq if (type(G) is not matrix 
        and type(G) is not spmatrix) or G.typecode != 'd' or 
        G.size[1] != n ]:
        raise TypeError("'Gq' must be a list of sparse or dense 'd' "\
            "matrices with %d columns" %n)
    mq = [ G.size[0] for G in Gq ]
    a = [ k for k in range(len(mq)) if mq[k] == 0 ] 
    if a: raise TypeError("the number of rows of Gq[%d] is zero" %a[0])
    if hq is None: hq = []
    if type(hq) is not list or len(hq) != len(mq) or [ h for h in hq if
        (type(h) is not matrix and type(h) is not spmatrix) or 
        h.typecode != 'd' ]: 
            raise TypeError("'hq' must be a list of %d dense or sparse "\
                "'d' matrices" %len(mq))
    a = [ k for k in range(len(mq)) if hq[k].size != (mq[k], 1) ]
    if a:
        k = a[0]
        raise TypeError("'hq[%d]' has size (%d,%d).  Expected size "\
            "is (%d,1)." %(k, hq[k].size[0], hq[k].size[1], mq[k]))

    N = ml + sum(mq)
    h = matrix(0.0, (N,1))
    if type(Gl) is matrix or [ Gk for Gk in Gq if type(Gk) is matrix ]:
        G = matrix(0.0, (N, n))
    else:
        G = spmatrix([], [], [], (N, n), 'd')
    h[:ml] = hl
    G[:ml,:] = Gl
    ind = ml
    for k in range(len(mq)):
        h[ind : ind + mq[k]] = hq[k]
        G[ind : ind + mq[k], :] = Gq[k]
        ind += mq[k]

    bkc = n*[ mosek.boundkey.fx ] 
    blc = array(-c)
    buc = array(-c)

    bkx = ml*[ mosek.boundkey.lo ] + sum(mq)*[ mosek.boundkey.fr ]
    blx = ml*[ 0.0 ] + sum(mq)*[ -inf ]
    bux = N*[ +inf ] 

    c   = -h        
    
    colptr, asub, acof = sparse([G.T]).CCS
    aptrb, aptre = colptr[:-1], colptr[1:]

    task = env.Task(0,0) 
    task.set_Stream (mosek.streamtype.log, streamprinter) 

    # set MOSEK options 
    for (param, val) in options.items():
        if str(param)[:6] == "iparam":
            task.putintparam(param, val)
        elif str(param)[:6] == "dparam":
            task.putdouparam(param, val)
        elif str(param)[:6] == "sparam":
            task.putstrparam(param, val)
        else:
            raise ValueError("invalid MOSEK parameter: "+str(param))

    task.inputdata (n,   # number of constraints
                    N,   # number of variables
                    array(c), # linear objective coefficients  
                    0.0, # objective fixed value  
                    array(aptrb), 
                    array(aptre), 
                    array(asub),
                    array(acof), 
                    bkc,
                    blc,
                    buc, 
                    bkx,
                    blx,
                    bux) 

    task.putobjsense(mosek.objsense.maximize)

    for k in range(len(mq)):
        task.appendcone(mosek.conetype.quad, 0.0, 
                        array(range(ml+sum(mq[:k]),ml+sum(mq[:k+1]))))
    task.optimize()

    task.solutionsummary (mosek.streamtype.msg); 

    prosta, solsta = task.getsolutionstatus(mosek.soltype.itr)

    xu, xl, zq = zeros(n, float), zeros(n, float), zeros(sum(mq), float)
    task.getsolutionslice(mosek.soltype.itr, mosek.solitem.slc, 0, n, xl) 
    task.getsolutionslice(mosek.soltype.itr, mosek.solitem.suc, 0, n, xu) 
    task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, ml, N, zq) 
    x = matrix(xu-xl)

    zq = [ matrix(zq[sum(mq[:k]):sum(mq[:k+1])]) for k in range(len(mq)) ]
    
    if ml:
        zl = zeros(ml, float)
        task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, ml, 
            zl) 
        zl = matrix(zl)
    else:
        zl = matrix(0.0, (0,1))

    if (solsta is mosek.solsta.unknown):
        return (solsta, None, None, None)
    else:
        return (solsta, x, zl, zq)


def qp(P, q, G=None, h=None, A=None, b=None):
    """
    Solves a quadratic program

        minimize    (1/2)*x'*P*x + q'*x 
        subject to  G*x <= h      
                    A*x = b.                    
                    
    using MOSEK 6.0.

    solsta, x, z, y = qp(P, q, G=None, h=None, A=None, b=None)

    Return values

        solsta is a MOSEK solution status key.

            If solsta is mosek.solsta.optimal,
                then (x, y, z) contains the primal-dual solution.
            If solsta is mosek.solsta.prim_infeas_cer,
                then (x, y, z) is a certificate of primal infeasibility.
            If solsta is mosek.solsta.dual_infeas_cer,
                then (x, y, z) is a certificate of dual infeasibility.
            If solsta is mosek.solsta.unknown, then (x, y, z) are all None.

            Other return values for solsta include:  
                mosek.solsta.dual_feas  
                mosek.solsta.near_dual_feas
                mosek.solsta.near_optimal
                mosek.solsta.near_prim_and_dual_feas
                mosek.solsta.near_prim_feas
                mosek.solsta.prim_and_dual_feas
                mosek.solsta.prim_feas
            in which case the (x,y,z) value may not be well-defined,
            c.f., section 17.48 of the MOSEK Python API manual.
        
        x, z, y  the primal-dual solution.                    

    Options are passed to MOSEK solvers via the msk.options dictionary, 
    e.g., the following turns off output from the MOSEK solvers
    
        >>> msk.options = {mosek.iparam.log: 0} 
    
    see chapter 15 of the MOSEK Python API manual.                    
    """

    if (type(P) is not matrix and type(P) is not spmatrix) or \
        P.typecode != 'd' or P.size[0] != P.size[1]:
        raise TypeError("'P' must be a square dense or sparse 'd' matrix ")
    n = P.size[0]

    if n < 1: raise ValueError("number of variables must be at least 1")

    if type(q) is not matrix or q.typecode != 'd' or q.size != (n,1):
        raise TypeError("'q' must be a 'd' matrix of size (%d,1)" %n)

    if G is None: G = spmatrix([], [], [], (0,n), 'd')
    if (type(G) is not matrix and type(G) is not spmatrix) or \
        G.typecode != 'd' or G.size[1] != n:
        raise TypeError("'G' must be a dense or sparse 'd' matrix "\
            "with %d columns" %n)

    m = G.size[0]
    if h is None: h = matrix(0.0, (0,1))
    if type(h) is not matrix or h.typecode != 'd' or h.size != (m,1):
        raise TypeError("'h' must be a 'd' matrix of size (%d,1)" %m)

    if A is None:  A = spmatrix([], [], [], (0,n), 'd')
    if (type(A) is not matrix and type(A) is not spmatrix) or \
        A.typecode != 'd' or A.size[1] != n:
        raise TypeError("'A' must be a dense or sparse 'd' matrix "\
            "with %d columns" %n)
    p = A.size[0]
    if b is None: b = matrix(0.0, (0,1))
    if type(b) is not matrix or b.typecode != 'd' or b.size != (p,1): 
        raise TypeError("'b' must be a dense matrix of size (%d,1)" %p)
 
    if m+p is 0: raise ValueError("m + p must be greater than 0")

    c = array(q)        

    bkc = m*[ mosek.boundkey.up ] + p*[ mosek.boundkey.fx ]
    blc = m*[ -inf ] + [ bi for bi in b ]
    buc = matrix([h, b])

    bkx = n*[mosek.boundkey.fr] 
    blx = n*[ -inf ] 
    bux = n*[ +inf ]

    colptr, asub, acof = sparse([G,A]).CCS
    aptrb, aptre = colptr[:-1], colptr[1:]

    task = env.Task(0,0) 
    task.set_Stream (mosek.streamtype.log, streamprinter) 

    # set MOSEK options 
    for (param, val) in options.items():
        if str(param)[:6] == "iparam":
            task.putintparam(param, val)
        elif str(param)[:6] == "dparam":
            task.putdouparam(param, val)
        elif str(param)[:6] == "sparam":
            task.putstrparam(param, val)
        else:
            raise ValueError("invalid MOSEK parameter: "+str(param))

    task.inputdata (m+p, # number of constraints
                    n,   # number of variables
                    array(c), # linear objective coefficients  
                    0.0, # objective fixed value  
                    array(aptrb), 
                    array(aptre), 
                    array(asub),
                    array(acof), 
                    bkc,
                    blc,
                    buc, 
                    bkx,
                    blx,
                    bux) 

    Ps = sparse(P)
    I, J = Ps.I, Ps.J
    tril = [ k for k in range(len(I)) if I[k] >= J[k] ]
    task.putqobj(array(I[tril]), array(J[tril]), array(Ps.V[tril]))
    
    task.putobjsense(mosek.objsense.minimize)

    task.optimize()

    task.solutionsummary (mosek.streamtype.msg); 

    prosta, solsta = task.getsolutionstatus(mosek.soltype.itr)

    x = zeros(n, float)
    task.getsolutionslice(mosek.soltype.itr, mosek.solitem.xx, 0, n, x) 
    x = matrix(x)

    if m is not 0:
        z = zeros(m, float)
        task.getsolutionslice(mosek.soltype.itr, mosek.solitem.suc, 0, m, 
            z) 
        z = matrix(z)
    else:
        z = matrix(0.0, (0,1))

    if p is not 0:
        yu, yl = zeros(p, float), zeros(p, float)
        task.getsolutionslice(mosek.soltype.itr, mosek.solitem.suc, m, m+p,
            yu) 
        task.getsolutionslice(mosek.soltype.itr, mosek.solitem.slc, m, m+p,
            yl) 
        y = matrix(yu) - matrix(yl)
    else:
        y = matrix(0.0, (0,1))

    if (solsta is mosek.solsta.unknown):
        return (solsta, None, None, None)
    else:
        return (solsta, x, z, y)


def ilp(c, G, h, A=None, b=None, I=None):
    """
    Solves the mixed integer LP

        minimize    c'*x       
        subject to  G*x + s = h
                    A*x = b    
                    s >= 0
                    xi integer, forall i in I
                    
    using MOSEK 6.0.

    solsta, x = ilp(c, G, h, A=None, b=None, I=None).

    Input arguments 

        G is m x n, h is m x 1, A is p x n, b is p x 1.  G and A must be 
        dense or sparse 'd' matrices.   h and b are dense 'd' matrices 
        with one column.  The default values for A and b are empty 
        matrices with zero rows.

        I is a Python set with indices of integer elements of x.  By 
        default all elements in x are constrained to be integer, i.e.,
        the default value of I is I = set(range(n))

        Dual variables are not returned for MOSEK.


    Return values

        solsta is a MOSEK solution status key.
            
            If solsta is mosek.solsta.integer_optimal, then x contains 
                the solution.
            If solsta is mosek.solsta.unknown, then x is None.

            Other return values for solsta include:  
                mosek.solsta.near_integer_optimal
            in which case the x value may not be well-defined,
            c.f., section 17.48 of the MOSEK Python API manual.
        
        x is the solution

    Options are passed to MOSEK solvers via the msk.options dictionary, 
    e.g., the following turns off output from the MOSEK solvers
    
    >>> msk.options = {mosek.iparam.log: 0} 
    
    see chapter 15 of the MOSEK Python API manual.                    
    """

    if type(c) is not matrix or c.typecode != 'd' or c.size[1] != 1: 
        raise TypeError("'c' must be a dense column matrix")
    n = c.size[0]
    if n < 1: raise ValueError("number of variables must be at least 1")

    if (type(G) is not matrix and type(G) is not spmatrix) or \
        G.typecode != 'd' or G.size[1] != n:
        raise TypeError("'G' must be a dense or sparse 'd' matrix "\
            "with %d columns" %n)
    m = G.size[0]
    if m is 0: raise ValueError("m cannot be 0")

    if type(h) is not matrix or h.typecode != 'd' or h.size != (m,1):
        raise TypeError("'h' must be a 'd' matrix of size (%d,1)" %m)

    if A is None:  A = spmatrix([], [], [], (0,n), 'd')
    if (type(A) is not matrix and type(A) is not spmatrix) or \
        A.typecode != 'd' or A.size[1] != n:
        raise TypeError("'A' must be a dense or sparse 'd' matrix "\
            "with %d columns" %n)
    p = A.size[0]
    if b is None: b = matrix(0.0, (0,1))
    if type(b) is not matrix or b.typecode != 'd' or b.size != (p,1): 
        raise TypeError("'b' must be a dense matrix of size (%d,1)" %p)
 
    c = array(c)        

    if I is None: I = set(range(n))

    if type(I) is not set: 
        raise TypeError("invalid argument for integer index set")

    for i in I:
        if type(i) is not int: 
            raise TypeError("invalid integer index set I")

    if len(I) > 0 and min(I) < 0: raise IndexError(
            "negative element in integer index set I")
    if len(I) > 0 and max(I) > n-1: raise IndexError(
            "maximum element in in integer index set I is larger than n-1")

    bkc = m*[ mosek.boundkey.up ] + p*[ mosek.boundkey.fx ]
    blc = m*[ -inf ] + [ bi for bi in b ]
    buc = matrix([h, b])

    bkx = n*[mosek.boundkey.fr] 
    blx = n*[ -inf ] 
    bux = n*[ +inf ]

    colptr, asub, acof = sparse([G,A]).CCS
    aptrb, aptre = colptr[:-1], colptr[1:]

    task = env.Task(0,0) 
    task.set_Stream (mosek.streamtype.log, streamprinter) 

    # set MOSEK options 
    for (param, val) in options.items():
        if str(param)[:6] == "iparam":
            task.putintparam(param, val)
        elif str(param)[:6] == "dparam":
            task.putdouparam(param, val)
        elif str(param)[:6] == "sparam":
            task.putstrparam(param, val)
        else:
            raise ValueError("invalid MOSEK parameter: "+str(param))
    
    task.inputdata (m+p, # number of constraints
                    n,   # number of variables
                    array(c), # linear objective coefficients  
                    0.0, # objective fixed value  
                    array(aptrb), 
                    array(aptre), 
                    array(asub),
                    array(acof), 
                    bkc,
                    blc,
                    buc, 
                    bkx,
                    blx,
                    bux) 

    task.putobjsense(mosek.objsense.minimize)

    # Define integer variables 
    if len(I) > 0:
        task.putvartypelist(list(I), len(I)*[ mosek.variabletype.type_int ])

    task.putintparam (mosek.iparam.mio_mode, mosek.miomode.satisfied) 

    task.optimize()

    task.solutionsummary (mosek.streamtype.msg); 

    if len(I) > 0:
        prosta, solsta = task.getsolutionstatus(mosek.soltype.itg)
    else:
        prosta, solsta = task.getsolutionstatus(mosek.soltype.bas)
        
    x = zeros(n, float)
    if len(I) > 0:
        task.getsolutionslice(mosek.soltype.itg, mosek.solitem.xx, 0, n, x) 
    else:
        task.getsolutionslice(mosek.soltype.bas, mosek.solitem.xx, 0, n, x) 
    x = matrix(x)

    if (solsta is mosek.solsta.unknown):
        return (solsta, None)
    else:
        return (solsta, x)