/usr/share/pyshared/openopt/kernel/nonOptMisc.py is in python-openopt 0.38+svn1589-1.
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 | import os
from oologfcn import OpenOptException
from numpy import zeros, hstack, vstack, ndarray, copy, where, prod, asarray, atleast_1d, isscalar, atleast_2d, eye, diag
import sys
syspath = sys.path
Sep = os.sep
try:
import scipy
scipyInstalled = True
scipyAbsentMsg = ''
from scipy.sparse import isspmatrix, csr_matrix, coo_matrix
from scipy.sparse import hstack as HstackSP, vstack as VstackSP, find as Find
def Hstack(Tuple):
ind = where([isscalar(elem) or prod(elem.shape)!=0 for elem in Tuple])[0].tolist()
elems = [Tuple[i] for i in ind]
if any([isspmatrix(elem) for elem in elems]):
return HstackSP(elems)
s = set([(0 if isscalar(elem) else elem.ndim) for elem in elems])
ndim = max(s)
if ndim <= 1: return hstack(elems)
#assert ndim <= 2 and 1 not in s, 'bug in OpenOpt kernel, inform developers'
return hstack(elems) if 0 not in s else hstack([atleast_2d(elem) for elem in elems])
def Vstack(Tuple):
ind = where([prod(elem.shape)!=0 for elem in Tuple])[0].tolist()
elems = [Tuple[i] for i in ind]
if any([isspmatrix(elem) for elem in elems]):
return VstackSP(elems)
s = set([(0 if isscalar(elem) else elem.ndim) for elem in elems])
ndim = max(s)
if ndim <= 1: return vstack(elems)
#assert ndim <= 2 and 1 not in s, 'bug in OpenOpt kernel, inform developers'
return vstack(elems) if 0 not in s else vstack([atleast_2d(elem) for elem in elems])
#Hstack = lambda Tuple: HstackSP(Tuple) if any([isspmatrix(elem) for elem in Tuple]) else hstack(Tuple)
#Vstack = lambda Tuple: VstackSP(Tuple) if any([isspmatrix(elem) for elem in Tuple]) else vstack(Tuple)
SparseMatrixConstructor = lambda *args, **kwargs: scipy.sparse.lil_matrix(*args, **kwargs)
except:
scipyInstalled = False
csr_matrix = None
coo_matrix = None
scipyAbsentMsg = 'Probably scipy installation could speed up running the code involved'
isspmatrix = lambda *args, **kwargs: False
Hstack = hstack
Vstack = vstack
def SparseMatrixConstructor(*args, **kwargs):
raise OpenOptException('error in OpenOpt kernel, inform developers')
def Find(*args, **kwargs):
raise OpenOptException('error in OpenOpt kernel, inform developers')
try:
import numpypy
isPyPy = True
except ImportError:
isPyPy = False
DenseMatrixConstructor = lambda *args, **kwargs: zeros(*args, **kwargs)
def Eye(n):
if not scipyInstalled and n>150:
pWarn(scipyAbsentMsg)
if n == 1:
return 1.0
elif n <= 16 or not scipyInstalled:
return eye(n)
else:
return scipy.sparse.identity(n)
def Diag(x):
if not scipyInstalled and len(x)>150:
pWarn(scipyAbsentMsg)
if isscalar(x): return x
elif len(x) == 1: return asfarray(x)
elif len(x) < 16 or not scipyInstalled: return diag(x)
else: return scipy.sparse.spdiags(x, [0], len(x), len(x))
##################################################################
solverPaths = {}
from os import path as os_path
FILE = os_path.realpath(__file__)
for root, dirs, files in os.walk(''.join([elem + os.sep for elem in FILE.split(os.sep)[:-2]+ ['solvers']])):
rd = root.split(os.sep)
if '.svn' in rd or '__pycache__' in rd: continue
rd = rd[rd.index('solvers')+1:]
for file in files:
if file.endswith('_oo.py'):
solverPaths[file[:-6]] = ''.join(rd+['.',file[:-3]])
def getSolverFromStringName(p, solver_str):
if solver_str not in solverPaths:
p.err('''
incorrect solver is called, maybe the solver "%s" is misspelled
or requires special installation and is not installed,
check http://openopt.org/%s''' % (solver_str, p.probType))
if p.debug:
solverClass = solver_import(solverPaths[solver_str], solver_str)
else:
try:
solverClass = solver_import(solverPaths[solver_str], solver_str)
except ImportError:
p.err('incorrect solver is called, maybe the solver "' + solver_str +'" require its installation, check http://www.openopt.org/%s or try p._solve() for more details' % p.probType)
r = solverClass()
if not hasattr(r, 'fieldsForProbInstance'): r.fieldsForProbInstance = {}
return r
##################################################################
importedSet = set()
ooPath = ''.join(elem+Sep for elem in __file__.split(Sep)[:-3])
def solver_import(solverPath, solverName):
if solverPath not in importedSet:
importedSet.add(solverPath)
syspath.append(ooPath+'openopt'+Sep + 'solvers'+''.join(Sep+elem for elem in solverPath.split('.')[:-1]))
name = 'openopt.solvers.' + solverPath
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return getattr(mod, solverName)
def oosolver(solverName, *args, **kwargs):
if args != ():
raise OpenOptException("Error: oosolver() doesn't consume any *args, use **kwargs only")
try:
if ':' in solverName:
# TODO: make it more properly
# currently it's used for to get filed isInstalled value
# from ooSystem
solverName = solverName.split(':')[1]
solverClass = solver_import(solverPaths[solverName], solverName)
solverClassInstance = solverClass()
solverClassInstance.fieldsForProbInstance = {}
for key, value in kwargs.iteritems():
if hasattr(solverClassInstance, key):
setattr(solverClassInstance, key, value)
else:
solverClassInstance.fieldsForProbInstance[key] = value
solverClassInstance.isInstalled = True
except ImportError:
from baseSolver import baseSolver
solverClassInstance = baseSolver()
solverClassInstance.__name__ = solverName
solverClassInstance.fieldsForProbInstance = {}
solverClassInstance.isInstalled = False
#assert hasattr(solverClassInstance, 'fieldsForProbInstance')
return solverClassInstance
def Copy(arg):
return arg.copy() if isinstance(arg, ndarray) or isspmatrix(arg) else copy(arg)
class EmptyClass: pass
|