Importing external Python-Scripts from Disk into Maya - python
Im trying to setup an Interface for calling the current version of the scipts in a certain Folder.
Im appending my personal script folder and try to import it as its told.
Whenever I press the Button, the following Error Message appears:
Error: NameError: file line 1: name 'setVars' is not defined
I´ve tried numerous possible import techniques. But the Errors keep popping up.
I´ll attach the Interface Script and one of the scipts that are ment to be called.
Interface:
import maya.cmds as mc
import sys
import os
import importlib
FolderContent = []
SysPath = 'C:/Users/[Username]/Documents/maya/2019/scripts/Personal'
sys.path.append(SysPath)
print sys.path
for file in os.listdir(SysPath):
if file.endswith(".py"):
FolderContent.append(file)
def UI(FolderContent):
x = 0
if mc.window("Run_Script", ex = True):
mc.deleteUI("Run_Script")
popUp = mc.window("Run_Script")
mc.gridLayout(nc = 1, ch = 30, cw = 300)
for i in FolderContent:
ScriptName = FolderContent[x]
mc.button(label = FolderContent[x], command = 'callFunc(\'%s\')' % (ScriptName), bgc = (0.25, 0.25, 0.25))
x += 1
mc.button(label = 'Cancel', command = 'close()', bgc = (0.92, 0.4, 0.4))
mc.window(popUp, e = True, s = False, h = 50, w = 100)
mc.showWindow()
UI(FolderContent)
def callFunc(ScriptName):
ScriptName = ScriptName[0:-3]
mymodule = importlib.import_module(ScriptName)
def close():
mc.deleteUI("Run_Script")
Example Script to be called:
import maya.cmds as mc
mc.select(hi = True)
BaseChain = mc.ls(sl = True)
ChainLength = len(BaseChain) - 1
###################################################################################
if mc.window("SetVariables", ex = True):
mc.deleteUI("SetVariables")
popUp = mc.window("SetVariables")
mc.gridLayout(nc = 2, ch = 30, cw = 200)
mc.text(label = "Side")
mc.textField("side")
mc.text(label = "Limb")
mc.textField("limb")
mc.text(label = "FK-Amount")
mc.textField("amount", fi = ChainLength)
cmd = 'setVars()'
close = 'closeWindow()'
mc.button(label = "OK", command = cmd, bgc = (0.2, 0.92, 0.75))
mc.button(label = "Cancel", command = close, bgc = (0.92, 0.4, 0.4))
mc.window(popUp, e = True, s = False, h = 50, w = 100)
mc.showWindow()
###################################################################################
def createChains(side, limb, amount):
mc.select(hi = True)
BndChain = mc.ls(sl = True)
x = 0
for i in BndChain:
mc.rename(BndChain[x], side + '_' + limb + '_BND_Chain_0' + str(x + 1))
x += 1
BndChain = mc.ls(sl = True)
ChainLength = len(BndChain)
mc.duplicate( n = side + '_' + limb + '_FK_Chain_01')
FkChain = mc.ls(sl = True)
mc.duplicate( n = side + '_' + limb + '_IK_Chain_01')
IkChain = mc.ls(sl = True)
parentChains(ChainLength, FkChain, IkChain, BndChain, side, limb, amount)
###################################################################################
def parentChains(ChainLength, FkChain, IkChain, BndChain, side, limb, amount):
x = 0
while x < ChainLength:
mc.select(FkChain[x])
mc.select(IkChain[x], add = True)
mc.select(BndChain[x], add = True)
mc.parentConstraint(mo = False)
x += 1
FKChainCtrl(ChainLength, FkChain, IkChain, BndChain, side, limb, amount)
###################################################################################
def FKChainCtrl(ChainLength, FkChain, IkChain, BndChain, side, limb, amount):
listLength = len(FkChain)
invertedNumber = listLength - int(amount)
doFK = listLength - invertedNumber
x = 0
Fk_ctrls = []
while x < doFK:
queryObj = FkChain[x]
currCtrl = mc.circle(n = side + '_' + limb + '_' + 'FK' + '_' + 'CTRL' + '_01', nr = [1, 0, 0], sw = 180)[0]
mc.curveRGBColor('translate.X', 1, 0, 1)
Fk_ctrls.append(currCtrl)
mc.parentConstraint(queryObj, currCtrl, mo = False)
mc.select(cl = True)
mc.select(queryObj)
mc.select(currCtrl, add = True)
mc.RemoveConstraintTarget()
mc.select(cl = True)
mc.select(currCtrl)
sel = mc.ls(sl = True)[0]
mc.FreezeTransformations(sel)
mc.parentConstraint(currCtrl, queryObj, mo = True)
if(x > 0):
mc.parent(Fk_ctrls[-1], Fk_ctrls[-2])
x += 1
mc.hide(FkChain)
IKChainCtrl(IkChain, BndChain, side, limb)
###################################################################################
def IKChainCtrl(IkChain, BndChain, side, limb):
currHandle = mc.ikHandle(n = side + '_' + limb + '_IkHandle', sj = IkChain[0], ee = IkChain[-1])[0]
mc.hide()
currHandlePos = mc.xform(currHandle, q = True, t = True, ws = True)
currCtrl = mc.circle(n = currHandle + '_CTRL', nr = [1, 0, 0], r = 1.5)
# currCtrl = mc.curve(n = currHandle + '_CTRL', d = 1, p = [(-0.75, 0, 0), (-0.75, 0, 2.5), (-2.5, 0, 2.5), (0, 0, 6.25), (2.5, 0, 2.5), (0.75, 0, 2.5), (0.75, 0, 0), (0.75, 0, -2.5), (2.5, 0, -2.5), (0, 0, -6.25), (-2.5, 0, -2.5), (-0.75, 0, -2.5), (-0.75, 0, 0)])
# mc.setAttr(currCtrl + '.overrideEnabled', 1)
# mc.setAttr(currCtrl + '.overrideColor', 21)
mc.select(IkChain[-2])
mc.select(currCtrl, add = True)
mc.parentConstraint(mo = False)
mc.select(IkChain[-2])
mc.select(currCtrl, add = True)
sel = mc.ls(sl = True)
mc.select(sel[0:-1], r = True)
mc.RemoveConstraintTarget()
mc.xform(currCtrl, t = [currHandlePos[0], currHandlePos[1], currHandlePos[2]])
mc.select(currCtrl, r = True)
mc.FreezeTransformations()
# mc.select('makeNurbCircle3', d = True)
mc.duplicate()
mc.parentConstraint(currCtrl, currHandle, mo = True)
mc.rename(side + '_' + limb + '_IkHandle_CTRL1', side + '_' + limb + '_Switch')
mc.xform(s = [1.5, 1.5, 1.5])
SwitchCtrl = mc.ls(sl = True)
mc.pointConstraint(BndChain[-1], SwitchCtrl)
currCtrl = mc.ls(sl = True)[0]
mc.hide(IkChain)
AddSwitchAttributes(currCtrl, side, limb)
###################################################################################
def AddSwitchAttributes(currCtrl, side, limb):
mc.addAttr(currCtrl, sn = 'FK', nn = 'FK', min = 0, max = 1, dv = 0, k = True, h = True)
mc.addAttr(currCtrl, sn = 'IK', nn = 'IK', min = 0, max = 1, dv = 1, k = True, h = True)
mc.addAttr(currCtrl, sn = 'Switch', nn = 'FK|IK Switch', min = 0, max = 1, dv = 1, k = True)
mc.connectAttr(side + '_' + limb + '_Switch.FK', side + '_' + limb + '_FK_CTRL_01.visibility')
mc.connectAttr(side + '_' + limb + '_Switch.IK', side + '_' + limb + '_IkHandle_CTRL.visibility')
i = 1
while i < ChainLength + 2:
mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(i) + '_parentConstraint1.' + side + '_' + limb + '_IK_Chain_0' + str(i) + 'W1', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(i) + '_parentConstraint1.' + side + '_' + limb + '_FK_Chain_0' + str(i) + 'W0', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
i += 1
mc.setDrivenKeyframe(side + '_' + limb + '_Switch.IK', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
mc.setDrivenKeyframe(side + '_' + limb + '_Switch.FK', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
mc.setAttr(side + '_' + limb + '_Switch.Switch', 0)
y = 1
while y < ChainLength + 2:
mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(y) + '_parentConstraint1.' + side + '_' + limb + '_IK_Chain_0' + str(y) + 'W1', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(y) + '_parentConstraint1.' + side + '_' + limb + '_FK_Chain_0' + str(y) + 'W0', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
y += 1
mc.setDrivenKeyframe(side + '_' + limb + '_Switch.IK', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
mc.setDrivenKeyframe(side + '_' + limb + '_Switch.FK', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
mc.setAttr(side + '_' + limb + '_Switch.Switch', 1)
mc.select(cl = True)
###################################################################################
def setVars():
side = mc.textField("side", q = True, tx = True)
limb = mc.textField("limb", q = True, tx = True)
amount = mc.textField("amount", q = True, tx = True)
createChains(side, limb, amount)
closeWindow()
###################################################################################
def closeWindow():
mc.deleteUI("SetVariables")
Thank you for your help!
Okay, I tried it now and there are some problems. I suppose you executed your main script directly from within maya? Because if I put it into a module and load it, I get a similiar error that "close()" is not found as well as "callFunc()" is not found. Both have the same reason which can easily be solved by not using strings.
In your main script, you can replace the "close()" in the button command with the same procedure as mentioned above:
mc.button(label = 'Cancel', command = close, bgc = (0.92, 0.4, 0.4))
Since the button command automatically adds an argument you will have an default argument to the close() command, something like close(dummyArg).
The callFunc() is a little bit more complicated because you use an argument. This can be solved by partial e.g.:
from functools import partial
for value in FolderContent:
mc.button(label = value, command = partial(callFunc, value), bgc = (0.25, 0.25, 0.25))
The button call will add another boolean to the call, so that the callFunc will receive another argument which can be captured by adding another argument to the callFunc definition like callFunc(scriptName, value).
This way your function object is used not a string. But now you have another problem because if you load the module the first time, you will get an error
NameError: global name 'close' is not defined #
That's because the function is not yet defined at the moment it us used, so you have to put the function definition at before the UI definition function.
Now if your script is imported you will get similiar problems with functions defined by strings, but they can be solved the same way as in the main module.
Without trying... I suppose the reason is that you use the string "setVars()" as command name. If you call it from your main module, there is no setVars(), but a a function called WhatEverYourModuelNameIs.setVars().
You could either try to import all like this:
from WhatEverYourModuelNameIs import *
What is not a really good solution, or you can try to use the function object directly as parameter for the button:
mc.button(label = "OK", command = setVars, bgc = (0.2, 0.92, 0.75))
Sorry for the delay guys, but Im glad to report that is working now!
Turn out the problem was indeed, that i didnt import the scripts before executing the UI.
So thats the dynamic UI at this point:
import maya.cmds as mc
import sys
import os
FolderContent = []
SysPath = 'C:/Users/mkzie/Documents/maya/2019/scripts/Personal'
sys.path.append(SysPath)
for file in os.listdir(SysPath):
if file.endswith(".py"):
FolderContent.append(file[0:-3])
print FolderContent
x = 0
for i in FolderContent:
exec('import %s') % (FolderContent[x])
x += 1
def UI(FolderContent):
x = 0
if mc.window("CXL_Interface", ex = True):
mc.deleteUI("CXL_Interface")
Interface = mc.window("CXL_Interface", s = True, rtf = True, h = 1)
# mc.scrollLayout()
for i in FolderContent:
ScriptName = FolderContent[x]
col = mc.columnLayout(cat = ('left', -1))
mc.frameLayout(l = ScriptName, cll = True, cl = True, w = 300, mh = 5, mw = 0)
exec('%s.init()') % (ScriptName)
mc.setParent( '..' )
mc.setParent( '..' )
x += 1
mc.setParent( '..' )
mc.setParent( '..' )
mc.separator(h = 1, st = 'none')
mc.columnLayout(h = 45, adj = True)
mc.separator(h = 5, st = 'shelf')
mc.button(l = 'Close Interface', c = 'close()', h = 40, w = 300, bgc = (.9, 0.2, 0.3))
mc.window(Interface, e = True, h = 1, w = 1)
mc.showWindow()
UI(FolderContent)
def callFunc(ScriptName):
exec('%s.init()') % (ScriptName)
def close():
mc.deleteUI("CXL_Interface")
By doing that before calling the UI, its even not a problem to use strings in the respective sripts:
mc.button(l = "OK", c = 'BuildKinematics.setVars()', bgc = (.4, .75, .4))
I think its a bit rough yet.
I'm just starting out doing stuff like that( like 4 weeks maybe), so improvements are very much appreciated.
Thank you very much for the big help!
Cheers.
Related
Removing a personalized class inside the view.py - Django
here is my view.py. Despite the code is a little bit long, I'd like to remove the class Ibm() from inside the else element to a new file called Ibm_class.py. I tried to do that but I couldn't find any way! def index(request): if 'GET' == request.method: return render(request, 'auditoria_app/index.html') else: class Ibm(object): def __init__(self, i): self.numeroIbm = inputsCombo[get_column_letter(i) + str(10)].value self.nome = inputsCombo[get_column_letter(i) + str(11)].value self.cidade = inputsCombo[get_column_letter(i) + str(12)].value self.uf = inputsCombo[get_column_letter(i) + str(13)].value self.anosProjeto = inputsCombo[get_column_letter(i) + str(16)].value self.anosAlternativa = inputsDNCombo[get_column_letter(i) + str(14)].value if self.anosAlternativa is None: self.anosAlternativa = 0 self.tipoInvestimento = inputsCombo[get_column_letter(i) + str(21)].value self.tipoProposta = inputsCombo[get_column_letter(i) + str(24)].value self.inicioVigencia = inputsCombo[get_column_letter(i) + str(34)].value self.prazoContrato = inputsCombo[get_column_letter(i) + str(38)].value # gas station variables self.faixaMargem = inputsCombo[get_column_letter(i) + str(19)].value self.rebateTotalCI = 0 self.rebateTotalCB = 0 self.unitariaCI = 0 self.volumeMensalCI = inputsCombo[get_column_letter(i) + str(60)].value self.volumeMensalCB = inputsDNCombo[get_column_letter(i) + str(32)].value self.margemCurva = inputsCombo[get_column_letter(i) + str(67)].value * 1000 self.margemCI = [] self.margemCB = [] self.volume12m = 0 self.margem12m = 0 self.curvaPostoCI = [] self.curvaPostoCB = [] self.rebateCI = [] self.rebateCB = [] self.faixaReal = '' self.volumeTotalCI = inputsCombo[get_column_letter(i) + str(151)].value self.volumeTotalCB = inputsDNCombo[get_column_letter(i) + str(121)].value # SELECT store variables self.feeIsencao = inputsCombo[get_column_letter(i) + str(220)].value self.feeFaturamento = inputsCombo[get_column_letter(i) + str(222)].value self.feeReal = inputsCombo[get_column_letter(i) + str(224)].value self.faturamento = inputsCombo[get_column_letter(i) + str(173)].value self.pvl = inputsCombo[get_column_letter(i) + str(184)].value self.feeLoja = inputsCombo[get_column_letter(i) + str(174)].value self.cashback = [] # credit variables self.prazoMogasCI1 = inputsCombo[get_column_letter(i) + str(159)].value self.prazoMogasCI2 = inputsCombo[get_column_letter(i) + str(160)].value self.prazoMogasCI3 = inputsCombo[get_column_letter(i) + str(161)].value self.prazoMogasCB1 = inputsDNCombo[get_column_letter(i) + str(151)].value self.prazoMogasCB2 = inputsDNCombo[get_column_letter(i) + str(152)].value self.prazoMogasCB3 = inputsDNCombo[get_column_letter(i) + str(153)].value # economics IBM self.unitariaIBM = arredonda(outputCombo[get_column_letter(i - 1) + str(42)].value) self.hsIBM = arredonda(outputCombo[get_column_letter(i - 1) + str(36)].value) self.cmIBM = percentual(outputCombo[get_column_letter(i - 1) + str(39)].value) self.tirIBM = percentual(outputCombo[get_column_letter(i - 1) + str(54)].value) self.npvIBM = arredonda(outputCombo[get_column_letter(i - 1) + str(55)].value) # if self.tipoInvestimento != 'Loja': for k in range(0, self.anosProjeto): margemCI = inputsCombo[get_column_letter(i) + str(109 + k)].value if margemCI is None or margemCI == '': margemCI = 0 self.margemCI.append(arredonda(margemCI * 1000)) curvaPostoCI = inputsCombo[get_column_letter(i) + str(130 + k)].value if curvaPostoCI is None or 0: curvaPostoCI = 1 self.curvaPostoCI.append(arredonda(curvaPostoCI * 100)) rebateCI = inputsCombo[get_column_letter(i) + str(305 + k)].value if rebateCI is None: rebateCI = 0 self.rebateCI.append(rebateCI * 1000) cashback = inputsCombo[get_column_letter(i) + str(485 + k)].value if cashback is None: cashback = 0 else: cashback = cashback / self.faturamento self.cashback.append(cashback) for y in range(0, self.anosAlternativa): margemCB = inputsDNCombo[get_column_letter(i) + str(79 + y)].value if margemCB is None or margemCB == '': margemCB = 0 self.margemCB.append(arredonda(margemCB * 1000)) curvaPostoCB = inputsDNCombo[get_column_letter(i) + str(100 + y)].value if curvaPostoCB is None or 0: curvaPostoCB = 1 self.curvaPostoCB.append(arredonda(curvaPostoCB * 100)) rebateCB = inputsDNCombo[get_column_letter(i) + str(204 + y)].value if rebateCB is None: rebateCB = 0 self.rebateCB.append(rebateCB * 1000) # Selecionando os dados da Loja Select # if self.tipoInvestimento == 'Loja': self.curvaLojaCI = [] self.curvaLojaCB = [] for k in range(0, self.anosProjeto): curvaLojaCI = inputsCombo[get_column_letter(i) + str(198 + k)].value if curvaLojaCI is None or 0: curvaLojaCI = 1 self.curvaLojaCI.append(curvaLojaCI) for k in range(0, self.anosAlternativa): curvaLojaCB = inputsDNCombo[get_column_letter(i) + str(123 + k)].value if curvaLojaCB is None or 0: curvaLojaCB = 1 self.curvaLojaCB.append(curvaLojaCB) self.fpCI = inputsCombo[get_column_letter(i) + str(283)].value if self.fpCI is None: self.fpCI = 0 self.rviCI = inputsCombo[get_column_letter(i) + str(285)].value if self.rviCI is None: self.rviCI = 0 self.fpCB = inputsDNCombo[get_column_letter(i) + str(201)].value if self.fpCB is None: self.fpCB = 0 self.rviCB = inputsDNCombo[get_column_letter(i) + str(202)].value if self.rviCB is None: self.rviCB = 0 # initializing gas station functions self.get_volume() self.rebate_total_CI() self.rebate_total_CB() # self.unitaria_CI() self.check_faixa() def get_volume(self): if self.tipoInvestimento != 'Loja': for j in range(2, sigma.max_row + 1): if self.numeroIbm == sigma['A' + str(j)].value: self.margem12m = sigma['D' + str(j)].value self.volume12m = sigma['E' + str(j)].value def check_faixa(self): if self.tipoInvestimento != 'Loja': if self.faixaMargem[0] == 'R': pass else: for row in range(5, faixas.max_row + 1): cidade = faixas['C' + str(row)].value if cidade == unidecode.unidecode(self.cidade.upper() + '/' + self.uf.upper()): self.faixaReal = faixas['D' + str(row)].value if self.faixaReal == '': self.faixaReal = 'n/a' def rebate_total_CI(self): if self.tipoInvestimento != 'Loja': rebateTotalCI = 0 for k in range(0, self.anosProjeto): rebateTotalCI += self.volumeMensalCI * 12 * self.curvaPostoCI[k] * self.rebateCI[k] self.rebateTotalCI = arredonda(rebateTotalCI / 1000) def rebate_total_CB(self): if self.tipoInvestimento != 'Loja': rebateTotalCB = 0 for k in range(0, self.anosAlternativa): rebateTotalCB += self.volumeMensalCB * 12 * self.curvaPostoCB[k] * self.rebateCB[k] self.rebateTotalCB = arredonda(rebateTotalCB / 1000) # UNIT might be extracted from 'OutPut COMBO' # def unitaria_CI(self): # self.unitariaCI = (self.rebateTotalCI + self.fpCI + self.rviCI)*10/self.volumeTotalCI def check_volume_mensal(self): return self.volumeMensalCI - self.volumeMensalCB def check_volume_total(self): return self.volumeTotalCI - self.volumeTotalCB def check_volumeCB_SIC(self): return self.volumeMensalCB excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file, data_only=True) inputsCombo = wb['Inputs COMBO'] inputsDNCombo = wb['Inputs DN COMBO'] outputCombo = wb['OutPut COMBO'] faixas = wb['Faixas'] wb2 = openpyxl.load_workbook('media/sigma.xlsx', data_only=True) sigma = wb2['Planilha1'] wb3 = openpyxl.load_workbook('media/performance.xlsx', data_only=True) sic = wb3['Performance'] wb4 = openpyxl.load_workbook('media/ultimoContrato.xlsm', data_only=True) ultimoContrato = wb4['Base'] numeroIbms = inputsCombo['F5'].value ibms = [] for i in range(8, 8 + numeroIbms): ibm = Ibm(i) ibms.append(ibm) return render(request, 'auditoria_app/index.html', {'ibms': ibms}) -> wb: file is loaded from a upload -> wb2, wb3, wb4: files are stored inside the media folder I tried to copy/paste this class and then import it to the view.py file but the excel_file variable must be inside the view and is still needed inside the Ibm_class.py. Any suggestion, pls? Thank you!
Use dependency injection on your class instead of relying on local/global scope variables. Here, instead of directly using inputsCombo, inputsDNCombo, outputCombo, faixas, and sigma variables within your class, just pass them to the Ibm constructor as class attributes. views.py ... from my_app.ibm import Ibm # Or wherever you would put that class ... def index(request): ... else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file, data_only=True) inputsCombo = wb['Inputs COMBO'] inputsDNCombo = wb['Inputs DN COMBO'] outputCombo = wb['OutPut COMBO'] faixas = wb['Faixas'] wb2 = openpyxl.load_workbook('media/sigma.xlsx', data_only=True) sigma = wb2['Planilha1'] ... for i in range(8, 8 + numeroIbms): # Pass the dependencies to the constructor of Ibm class ibm = Ibm(i, inputsCombo, inputsDNCombo, outputCombo, faixas, sigma) ... ... ibm.py class Ibm(object): # Accept the injected parameters to Ibm class def __init__(self, i, inputsCombo, inputsDNCombo, outputCombo, faixas, sigma): self.numeroIbm = inputsCombo[get_column_letter(i) + str(10)].value self.anosAlternativa = inputsDNCombo[get_column_letter(i) + str(14)].value self.unitariaIBM = arredonda(outputCombo[get_column_letter(i - 1) + str(42)].value) # For the arguments that will be used by your other functions e.g. check_faixa, define them as class attributes here self.faixas = faixas self.sigma = sigma def get_volume(self): if self.tipoInvestimento != 'Loja': for j in range(2, self.sigma.max_row + 1): # Append "self." to the usage of "sigma" to refer to the class attribute that was set in __init__ if self.numeroIbm == self.sigma['A' + str(j)].value: self.margem12m = self.sigma['D' + str(j)].value self.volume12m = self.sigma['E' + str(j)].value def check_faixa(self): if self.tipoInvestimento != 'Loja': if self.faixaMargem[0] == 'R': pass else: for row in range(5, self.faixas.max_row + 1): # Append "self." to the usage of "faixas" to refer to the class attribute that was set in __init__ cidade = self.faixas['C' + str(row)].value if cidade == unidecode.unidecode(self.cidade.upper() + '/' + self.uf.upper()): self.faixaReal = self.faixas['D' + str(row)].value if self.faixaReal == '': self.faixaReal = 'n/a'
Error , Infeasible No value for uninitialized NumericValue object
I'm trying to optmize a problem of clients/facility allocation and I'm using pyomo to do so. I have the following problem that appear and cannot solve it even if I initialize all the values of Model.z to 0; the problems is still infeasible from __future__ import division import pyomo.environ as pyo #from pyomo.environ import * from pyomo.opt import SolverFactory import sys import numpy as np import sys import os from time import perf_counter from pulp import * from pyomo.util.infeasible import log_infeasible_constraints #print(sys.path) opt = pyo.SolverFactory('glpk') opt.options['threads'] =4 #import instance model = pyo.ConcreteModel() # n is the number of facility related to J # m is the number of clients related to I # t is the number of periods relatdd to T # H is the maximum number of clients that can be served [m,n,t,H] = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, max_rows = 1) f_values = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, max_rows = 4,skip_header=1) c_values = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, skip_footer = 1,skip_header=5) p_values = np.genfromtxt(fname = r'./Instances/data-100-10-4-3-0.txt', dtype = None, skip_header=405) model.J = pyo.Set(initialize=[int(i)+1 for i in range(n)]) model.T= pyo.Set(initialize=[int(i)+1 for i in range(t)]) model.T.pprint() model.I = pyo.Set(initialize=[int(i)+1 for i in range(m)]) model.H = pyo.Set(initialize=[int(i)+1 for i in range(H)]) # Generation of Subsets of all clients client_list = [int(i)+1 for i in range(100)] list_H = [int(i)+1 for i in range(H)] possible_groups_of_clients=[] for i in list_H: possible_groups_of_clients += [list(elem) for elem in itertools.combinations(client_list,i)] possible_groups_of_clients = possible_groups_of_clients[0:5] #Only select the first 5 subsets model.K = pyo.Set(initialize=[int(i)+1 for i in range(len(possible_groups_of_clients))]) p_val = np.zeros((len(model.K),len(model.J),len(model.T))) for t in model.T: t=t-1 #Pyomo starts at 1 for j in model.J: j=j-1 count = 0 for k in possible_groups_of_clients: #k=k+1 c_sum=0; for p in k: if t==0: c_sum = c_sum +c_values[p][j] elif t==1: c_sum = c_sum +c_values[p+100][j] elif t==2: c_sum = c_sum +c_values[p+200][j] elif t==3: c_sum = c_sum +c_values[p+300][j] #print(f_values[t][j]) p_val[count][j][t] = f_values[t][j]+ c_sum count=count+1 model.p_val = pyo.Param(model.K,model.J,model.T, initialize = lambda model,k,j,t: p_val[k-1][j-1][t-1]) #Matrice Aik A = [[0 for k in range(len(possible_groups_of_clients))] for i in range(100)] #model.p_val = pyo.Param(model.T,model.J,model.K, initialize = lambda model,t,j,k: A[t-1][j-1][k-1]) model.A = pyo.Param(model.I, model.K, mutable= True,initialize= lambda model,i,k: A[i-1][k-1]) count=1 for i in possible_groups_of_clients: for k in range(100): k=k+1 #print(k) if k in i: model.A[k,count]=1 else: model.A[k,count]=0 count=count+1 model.z = pyo.Var(model.K,model.J,model.T,initialize= 0,within=pyo.NonNegativeReals,bounds=(0,1)) a=range(len(possible_groups_of_clients)) print(p_values) # Minization of objective functions # Constraint unique client model.uniq_client = pyo.Constraint( model.I, rule=lambda model, i: sum(model.A[i,k]*model.z[k,j,t] for t in model.T for j in model.J for k in model.K) == 1 ) model.unique_service_groupclients = pyo.Constraint( model.J, model.T, rule=lambda model,j,t: sum(model.z[k,j,t] for k in model.K)<=1 ) model.min_factory_perperiod = pyo.Constraint( model.T, rule=lambda model, t: sum(model.z[k,j,t] for j in model.J for k in model.K )>=p_values[t-1] ) model.obj = pyo.Objective(rule= lambda model:sum(model.p_val[k,j,t]*model.z[k,j,t] for t in model.T for j in model.J for k in model.K ), sense= pyo.minimize) model.pprint() Constraint Group Client sol = pyo.SolverFactory('glpk',).solve(model).write() log_infeasible_constraints(model) # ========================================================== # = Solver Results = # ========================================================== # ---------------------------------------------------------- # Problem Information # ---------------------------------------------------------- Problem: - Name: unknown Lower bound: -inf Upper bound: inf Number of objectives: 1 Number of constraints: 145 Number of variables: 201 Number of nonzeros: 601 Sense: minimize # ---------------------------------------------------------- # Solver Information # ---------------------------------------------------------- Solver: - Status: ok Termination condition: infeasible Statistics: Branch and bound: Number of bounded subproblems: 0 Number of created subproblems: 0 Error rc: 0 Time: 0.008042335510253906 ERROR: evaluating object as numeric value: z[1,1,1] (object: <class 'pyomo.core.base.var._GeneralVarData'>) No value for uninitialized NumericValue object z[1,1,1] ERROR: evaluating object as numeric value: 1.0 - (A[1,1]*z[1,1,1] + A[1,2]*z[2,1,1] + A[1,3]*z[3,1,1] + A[1,4]*z[4,1,1] + A[1,5]*z[5,1,1] + A[1,1]*z[1,2,1] + A[1,2]*z[2,2,1] + A[1,3]*z[3,2,1] + A[1,4]*z[4,2,1] + A[1,5]*z[5,2,1] + A[1,1]*z[1,3,1] + A[1,2]*z[2,3,1] + A[1,3]*z[3,3,1] + A[1,4]*z[4,3,1] + A[1,5]*z[5,3,1] + A[1,1]*z[1,4,1] + A[1,2]*z[2,4,1] + A[1,3]*z[3,4,1] + A[1,4]*z[4,4,1] + A[1,5]*z[5,4,1] + A[1,1]*z[1,5,1] + A[1,2]*z[2,5,1] + A[1,3]*z[3,5,1] + A[1,4]*z[4,5,1] + A[1,5]*z[5,5,1] + A[1,1]*z[1,6,1] + A[1,2]*z[2,6,1] + A[1,3]*z[3,6,1] + A[1,4]*z[4,6,1] + A[1,5]*z[5,6,1] + A[1,1]*z[1,7,1] + A[1,2]*z[2,7,1] + A[1,3]*z[3,7,1] + A[1,4]*z[4,7,1] + A[1,5]*z[5,7,1] + A[1,1]*z[1,8,1] + A[1,2]*z[2,8,1] + A[1,3]*z[3,8,1] + A[1,4]*z[4,8,1] + A[1,5]*z[5,8,1] + A[1,1]*z[1,9,1] + A[1,2]*z[2,9,1] + A[1,3]*z[3,9,1] + A[1,4]*z[4,9,1] + A[1,5]*z[5,9,1] + A[1,1]*z[1,10,1] + A[1,2]*z[2,10,1] + A[1,3]*z[3,10,1] + A[1,4]*z[4,10,1] + A[1,5]*z[5,10,1] + A[1,1]*z[1,1,2] + A[1,2]*z[2,1,2] + A[1,3]*z[3,1,2] + A[1,4]*z[4,1,2] + A[1,5]*z[5,1,2] + A[1,1]*z[1,2,2] + A[1,2]*z[2,2,2] + A[1,3]*z[3,2,2] + A[1,4]*z[4,2,2] + A[1,5]*z[5,2,2] + A[1,1]*z[1,3,2] + A[1,2]*z[2,3,2] + A[1,3]*z[3,3,2] + A[1,4]*z[4,3,2] + A[1,5]*z[5,3,2] + A[1,1]*z[1,4,2] + A[1,2]*z[2,4,2] + A[1,3]*z[3,4,2] + A[1,4]*z[4,4,2] + A[1,5]*z[5,4,2] + A[1,1]*z[1,5,2] + A[1,2]*z[2,5,2] + A[1,3]*z[3,5,2] + A[1,4]*z[4,5,2] + A[1,5]*z[5,5,2] + A[1,1]*z[1,6,2] + A[1,2]*z[2,6,2] + A[1,3]*z[3,6,2] + A[1,4]*z[4,6,2] + A[1,5]*z[5,6,2] + A[1,1]*z[1,7,2] + A[1,2]*z[2,7,2] + A[1,3]*z[3,7,2] + A[1,4]*z[4,7,2] + A[1,5]*z[5,7,2] + A[1,1]*z[1,8,2] + A[1,2]*z[2,8,2] + A[1,3]*z[3,8,2] + A[1,4]*z[4,8,2] + A[1,5]*z[5,8,2] + A[1,1]*z[1,9,2] + A[1,2]*z[2,9,2] + A[1,3]*z[3,9,2] + A[1,4]*z[4,9,2] + A[1,5]*z[5,9,2] + A[1,1]*z[1,10,2] + A[1,2]*z[2,10,2] + A[1,3]*z[3,10,2] + A[1,4]*z[4,10,2] + A[1,5]*z[5,10,2] + A[1,1]*z[1,1,3] + A[1,2]*z[2,1,3] + A[1,3]*z[3,1,3] + A[1,4]*z[4,1,3] + A[1,5]*z[5,1,3] + A[1,1]*z[1,2,3] + A[1,2]*z[2,2,3] + A[1,3]*z[3,2,3] + A[1,4]*z[4,2,3] + A[1,5]*z[5,2,3] + A[1,1]*z[1,3,3] + A[1,2]*z[2,3,3] + A[1,3]*z[3,3,3] + A[1,4]*z[4,3,3] + A[1,5]*z[5,3,3] + A[1,1]*z[1,4,3] + A[1,2]*z[2,4,3] + A[1,3]*z[3,4,3] + A[1,4]*z[4,4,3] + A[1,5]*z[5,4,3] + A[1,1]*z[1,5,3] + A[1,2]*z[2,5,3] + A[1,3]*z[3,5,3] + A[1,4]*z[4,5,3] + A[1,5]*z[5,5,3] + A[1,1]*z[1,6,3] + A[1,2]*z[2,6,3] + A[1,3]*z[3,6,3] + A[1,4]*z[4,6,3] + A[1,5]*z[5,6,3] + A[1,1]*z[1,7,3] + A[1,2]*z[2,7,3] + A[1,3]*z[3,7,3] + A[1,4]*z[4,7,3] + A[1,5]*z[5,7,3] + A[1,1]*z[1,8,3] + A[1,2]*z[2,8,3] + A[1,3]*z[3,8,3] + A[1,4]*z[4,8,3] + A[1,5]*z[5,8,3] + A[1,1]*z[1,9,3] + A[1,2]*z[2,9,3] + A[1,3]*z[3,9,3] + A[1,4]*z[4,9,3] + A[1,5]*z[5,9,3] + A[1,1]*z[1,10,3] + A[1,2]*z[2,10,3] + A[1,3]*z[3,10,3] + A[1,4]*z[4,10,3] + A[1,5]*z[5,10,3] + A[1,1]*z[1,1,4] + A[1,2]*z[2,1,4] + A[1,3]*z[3,1,4] + A[1,4]*z[4,1,4] + A[1,5]*z[5,1,4] + A[1,1]*z[1,2,4] + A[1,2]*z[2,2,4] + A[1,3]*z[3,2,4] + A[1,4]*z[4,2,4] + A[1,5]*z[5,2,4] + A[1,1]*z[1,3,4] + A[1,2]*z[2,3,4] + A[1,3]*z[3,3,4] + A[1,4]*z[4,3,4] + A[1,5]*z[5,3,4] + A[1,1]*z[1,4,4] + A[1,2]*z[2,4,4] + A[1,3]*z[3,4,4] + A[1,4]*z[4,4,4] + A[1,5]*z[5,4,4] + A[1,1]*z[1,5,4] + A[1,2]*z[2,5,4] + A[1,3]*z[3,5,4] + A[1,4]*z[4,5,4] + A[1,5]*z[5,5,4] + A[1,1]*z[1,6,4] + A[1,2]*z[2,6,4] + A[1,3]*z[3,6,4] + A[1,4]*z[4,6,4] + A[1,5]*z[5,6,4] + A[1,1]*z[1,7,4] + A[1,2]*z[2,7,4] + A[1,3]*z[3,7,4] + A[1,4]*z[4,7,4] + A[1,5]*z[5,7,4] + A[1,1]*z[1,8,4] + A[1,2]*z[2,8,4] + A[1,3]*z[3,8,4] + A[1,4]*z[4,8,4] + A[1,5]*z[5,8,4] + A[1,1]*z[1,9,4] + A[1,2]*z[2,9,4] + A[1,3]*z[3,9,4] + A[1,4]*z[4,9,4] + A[1,5]*z[5,9,4] + A[1,1]*z[1,10,4] + A[1,2]*z[2,10,4] + A[1,3]*z[3,10,4] + A[1,4]*z[4,10,4] + A[1,5]*z[5,10,4]) (object: <class 'pyomo.core.expr.numeric_expr.SumExpression'>) No value for uninitialized NumericValue object z[1,1,1] Traceback (most recent call last): File "main.py", line 246, in <module> log_infeasible_constraints(model) File "/home/john/.local/lib/python3.6/site-packages/pyomo /util/infeasible.py", line 25, in log_infeasible_constraints if constr.equality and fabs(value(constr.lower - constr.body)) >= tol: File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/numvalue.py", line 226, in value tmp = obj(exception=True) File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/numeric_expr.py", line 222, in __call__ return evaluate_expression(self, exception) File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/visitor.py", line 973, in evaluate_expression return visitor.dfs_postorder_stack(exp) File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/visitor.py", line 518, in dfs_postorder_stack flag, value = self.visiting_potential_leaf(_sub) File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/visitor.py", line 893, in visiting_potential_leaf return True, value(node) File "/home/john/.local/lib/python3.6/site-packages/pyomo/core/expr/numvalue.py", line 230, in value % (obj.name,)) ValueError: No value for uninitialized NumericValue object z[1,1,1] I got this error whatever I try and I don't understand why Z should be initialized as it is the variable I'm trying to minimize
"out of memory" issue with PETsc in Ubuntu
I am running an OpenMDAO code that uses 2 parallel groups. I have installed PETSc4py and mpi4py inside a virtual python environment. I am getting the following error while running my code. The error reads as follows: "Out of memory. Allocated: 0, Used by process: 236814336" Here is the full error message: File "PETSc/Scatter.pyx", line 42, in petsc4py.PETSc.Scatter.create petsc4py.PETSc.Error: error code 55 [1] VecScatterCreate() line 282 in /tmp/pycharm-packaging/petsc/src/vec/vscat/interface/vscreate.c [1] VecScatterSetUp() line 211 in /tmp/pycharm-packaging/petsc/src/vec/vscat/interface/vscatfce.c [1] VecScatterSetUp_MPI1() line 2543 in /tmp/pycharm-packaging/petsc/src/vec/vscat/impls/mpi1/vpscat_mpi1.c [1] VecScatterSetUp_vectype_private() line 865 in /tmp/pycharm-packaging/petsc/src/vec/vscat/impls/vscat.c [1] VecScatterCreate_PtoP() line 746 in /tmp/pycharm-packaging/petsc/src/vec/vscat/impls/vscat.c [1] VecScatterCreateLocal_PtoP_MPI1() line 2436 in /tmp/pycharm-packaging/petsc/src/vec/vscat/impls/mpi1/vpscat_mpi1.c [1] PetscMallocA() line 390 in /tmp/pycharm-packaging/petsc/src/sys/memory/mal.c [1] VecScatterCreateLocal_PtoP_MPI1() line 2436 in /tmp/pycharm-packaging/petsc/src/vec/vscat/impls/mpi1/vpscat_mpi1.c [1] Out of memory. Allocated: 0, Used by process: 237649920 [1] Memory requested 18446744062962991104 ------------------------------------------------------- Primary job terminated normally, but 1 process returned a non-zero exit code.. Per user-direction, the job has been aborted. ------------------------------------------------------- -------------------------------------------------------------------------- mpirun detected that one or more processes exited with non-zero status, thus causing the job to be terminated. The first process to do so was: Process name: [[43240,1],1] Exit code: 1 -------------------------------------------------------------------------- I call the process with the following code: mpirun -np 2 python ./parallel_processing.py Here is the code for IDF optimization: from __future__ import print_function import pickle import numpy as np import pandas as pd import matplotlib.pylab as plt from openmdao.api import Problem, ScipyOptimizeDriver, SqliteRecorder import time import random from openmdao.recorders.case_reader import CaseReader from ssbj_vanaret_mda import SsbjMda from ssbj_vanaret_idf2_mda import SsbjIdf2Mda def idf_run2(nx, ny): # make a counter for discipline calls [str_count, aer_count, pro_count] = np.zeros(3) a = ["str_count.p", "aer_count.p", "pro_count.p"] for i in a: with open(i, "wb") as f: pickle.dump(0, f) # Initialize an MDA to generate the starting point for IDF prob_init = Problem() # initialize the optimization problem prob_init.model = SsbjMda(nx_input=nx) # create the MDA # Design variables prob_init.model.add_design_var('z', lower=np.zeros(nx), upper=np.ones(nx)) prob_init.model.add_design_var('x1', lower=np.zeros(nx), upper=np.ones(nx)) prob_init.model.add_design_var('x2', lower=np.zeros(nx), upper=np.ones(nx)) prob_init.model.add_design_var('x3', lower=np.zeros(nx), upper=np.ones(nx)) # Objective function prob_init.model.add_objective('range') # Constraints for i in range(nx): prob_init.model.add_constraint('con_g1' + str(i + 1), upper=0) prob_init.model.add_constraint('con_g2' + str(i + 1), upper=0) prob_init.model.add_constraint('con_g3' + str(i + 1), upper=0) prob_init.driver = ScipyOptimizeDriver(optimizer='SLSQP') prob_init.driver.options['maxiter'] = 0 prob_init.setup(mode='fwd') prob_init.set_solver_print(1) prob_init.run_driver() prob_init.cleanup() y12_initial = prob_init['y12'] y23_initial = prob_init['y23'] y32_initial = prob_init['y32'] y21_initial = prob_init['y21'] y31_initial = prob_init['y31'] # : initialize MDA for IDF prob = Problem() prob.model = SsbjIdf2Mda(nx, ny, y12_initial, y23_initial, y32_initial, y21_initial, y31_initial) # create the MDA # Design variables prob.model.add_design_var('z', lower=np.zeros(nx), upper=np.ones(nx)) # shared variables prob.model.add_design_var('x1', lower=np.zeros(nx), upper=np.ones(nx)) # local variable for structural discipline prob.model.add_design_var('x2', lower=np.zeros(nx), upper=np.ones(nx)) # local variable for aerodynamic discipline prob.model.add_design_var('x3', lower=np.zeros(nx), upper=np.ones(nx)) # local variable for propulsion discipline # # coupling variables prob.model.add_design_var('y31') prob.model.add_design_var('y12') prob.model.add_design_var('y32') prob.model.add_design_var('y23') prob.model.add_design_var('y21') # Objective function prob.model.add_objective('obj') # Constraints for i in range(nx): prob.model.add_constraint('con_g1' + str(i + 1), upper=0) prob.model.add_constraint('con_g2' + str(i + 1), upper=0) prob.model.add_constraint('con_g3' + str(i + 1), upper=0) epsilon = 1e-9 # Coupling constraints for i in range(ny): prob.model.add_constraint('con_y12' + str(i + 1), upper=epsilon) prob.model.add_constraint('con_y21' + str(i + 1), upper=epsilon) prob.model.add_constraint('con_y23' + str(i + 1), upper=epsilon) prob.model.add_constraint('con_y32' + str(i + 1), upper=epsilon) prob.model.add_constraint('con_y31' + str(i + 1), upper=epsilon) # Optimizer options prob.driver = ScipyOptimizeDriver() prob.set_solver_print(2) prob.driver.options['optimizer'] = 'SLSQP' for tol in [1e-3]: prob.driver.options['maxiter'] = random.randint(40, 50) prob.driver.options['tol'] = tol prob.driver.add_recorder(SqliteRecorder("cases_idf.sql")) # Run optimization start_time = time.time() prob.setup(mode='fwd') # view_model(prob, outfile='n2_mdfgs.html', show_browser=True) prob.run_driver() prob.run_model() # prob.check_partials() prob.cleanup() end_time = time.time() total_time = end_time - start_time if prob.driver.options['tol'] == 1e-6: iters = len(CaseReader('cases_idf.sql').get_cases()) cr = CaseReader('cases_idf.sql') case_ids = cr.get_cases() obj_list = ['obj'] z = [] [z.append(case.get_objectives(case)[obj_list[0]]) for case in case_ids] with open("df_idf.p", "rb") as f: df_idf = pickle.load(f).append(pd.DataFrame({'total iterations[IDF]': [iters], 'total time[IDF]': [total_time], 'final_objective[IDF]': z[-1]})) with open("df_idf.p", "wb") as f: pickle.dump(df_idf, f) elif prob.driver.options['tol'] == 1e-3: iters = len(CaseReader('cases_idf.sql').get_cases()) cr = CaseReader('cases_idf.sql') case_ids = cr.get_cases() obj_list = ['obj'] z = [] a = ["str_count.p", "aer_count.p", "pro_count.p"] k = [] for i in a: with open(i, "rb") as f: k.append(pickle.load(f)) [z.append(case.get_objectives(case)[obj_list[0]]) for case in case_ids] with open("df_idf_tol.p", "rb") as f: df_idf = pickle.load(f).append(pd.DataFrame({'10.total iterations[IDF_tol]': [iters], '11.total time[IDF_tol]': [total_time], '12.final_objective[IDF_tol]': z[-1], '13.str_count[IDF_tol]': k[0], '14.aer_count[IDF_tol]': k[1], '15.pro_count[IDF_tol]': k[2] })) with open("df_idf_tol.p", "wb") as f: pickle.dump(df_idf, f) The MDA for IDF optimization goes here: from openmdao.api import Group import numpy as np from openmdao.api import IndepVarComp, ExecComp, ParallelGroup from ssbj_vanaret_discipline import StructureDisc from ssbj_vanaret_discipline import AerodynamicsDisc from ssbj_vanaret_discipline import PropulsionDisc from ssbj_vanaret_discipline import PerformanceDisc class SsbjIdf2Mda(Group): """ Analysis for IDF formulation where couplings are managed as additional constraints on input/output variables of related disciplines. """ def __init__(self, nx_input, ny_input, y12_initial, y23_initial, y32_initial, y21_initial, y31_initial): super(SsbjIdf2Mda, self).__init__() self.nx = nx_input self.ny = ny_input self.y12 = y12_initial self.y23 = y23_initial self.y32 = y32_initial self.y31 = y31_initial self.y21 = y21_initial def setup(self): # Design variables self.add_subsystem('z_ini', IndepVarComp('z', .5 * np.ones(self.nx)), promotes=['*']) self.add_subsystem('x1_ini', IndepVarComp('x1', .5 * np.ones(self.nx)), promotes=['*']) self.add_subsystem('x2_ini', IndepVarComp('x2', .5 * np.ones(self.nx)), promotes=['*']) self.add_subsystem('x3_ini', IndepVarComp('x3', .5 * np.ones(self.nx)), promotes=['*']) # Couplings self.add_subsystem('y31_ini', IndepVarComp('y31', self.y31), promotes=['*']) self.add_subsystem('y12_ini', IndepVarComp('y12', self.y12), promotes=['*']) self.add_subsystem('y32_ini', IndepVarComp('y32', self.y32), promotes=['*']) self.add_subsystem('y23_ini', IndepVarComp('y23', self.y23), promotes=['*']) self.add_subsystem('y21_ini', IndepVarComp('y21', self.y21), promotes=['*']) # Disciplines parallel = self.add_subsystem('parallel', ParallelGroup()) parallel.add_subsystem('Structure', StructureDisc()) parallel.add_subsystem('Aerodynamics', AerodynamicsDisc()) self.add_subsystem('Propulsion', PropulsionDisc()) self.add_subsystem('Performance', PerformanceDisc()) # Shared variables z self.connect('z', 'parallel.Structure.z') self.connect('z', 'parallel.Aerodynamics.z') self.connect('z', 'Propulsion.z') self.connect('z', 'Performance.z') # Local variables self.connect('x1', 'parallel.Structure.x1') self.connect('x2', 'parallel.Aerodynamics.x2') self.connect('x3', 'Propulsion.x3') self.connect('x1', 'Performance.x1') self.connect('x2', 'Performance.x2') self.connect('x3', 'Performance.x3') # Coupling variables self.connect('y21', 'parallel.Structure.y21') self.connect('y31', 'parallel.Structure.y31') self.connect('y32', 'parallel.Aerodynamics.y32') self.connect('y12', 'parallel.Aerodynamics.y12') self.connect('y23', 'Propulsion.y23') # Objective function self.add_subsystem('Obj', ExecComp('obj=range'), promotes=['obj']) # Connections self.connect('Performance.range', 'Obj.range') # self.connect('Propulsion.y34', 'Performance.y34') # self.connect('Aerodynamics.y24', 'Performance.y24') # self.connect('Structure.y14', 'Performance.y14') self.connect('parallel.Aerodynamics.y21', 'Performance.y21') self.connect('Propulsion.y31', 'Performance.y31') self.connect('Propulsion.y32', 'Performance.y32') self.connect('parallel.Structure.y12', 'Performance.y12') self.connect('parallel.Aerodynamics.y23', 'Performance.y23') # Coupling constraints for i in range(self.ny): self.add_subsystem('con_Y12' + str(i + 1), ExecComp('con_y12' + str(i + 1) + '=(y12[' + str(i) + '] - y12k[' + str(i) + ']) ** 2', y12=self.y12, y12k=self.y12 ), promotes=['con_y12' + str(i + 1)]) self.connect('parallel.Structure.y12', 'con_Y12' + str(i + 1) + '.y12') self.connect('y12', 'con_Y12' + str(i + 1) + '.y12k') for i in range(self.ny): self.add_subsystem('con_Y21' + str(i + 1), ExecComp('con_y21' + str(i + 1) + '=(y21[' + str(i) + '] - y21k[' + str(i) + ']) ** 2', y21=self.y21, y21k=self.y21 ), promotes=['con_y21' + str(i + 1)]) self.connect('parallel.Aerodynamics.y21', 'con_Y21' + str(i + 1) + '.y21') self.connect('y21', 'con_Y21' + str(i + 1) + '.y21k') for i in range(self.ny): self.add_subsystem('con_Y32' + str(i + 1), ExecComp('con_y32' + str(i + 1) + '=(y32[' + str(i) + '] - y32k[' + str(i) + ']) ** 2', y32=self.y32, y32k=self.y32 ), promotes=['con_y32' + str(i + 1)]) self.connect('Propulsion.y32', 'con_Y32' + str(i + 1) + '.y32') self.connect('y32', 'con_Y32' + str(i + 1) + '.y32k') for i in range(self.ny): self.add_subsystem('con_Y23' + str(i + 1), ExecComp('con_y23' + str(i + 1) + '=(y23[' + str(i) + '] - y23k[' + str(i) + ']) ** 2', y23=self.y23, y23k=self.y23 ), promotes=['con_y23' + str(i + 1)]) self.connect('parallel.Aerodynamics.y23', 'con_Y23' + str(i + 1) + '.y23') self.connect('y23', 'con_Y23' + str(i + 1) + '.y23k') for i in range(self.ny): self.add_subsystem('con_Y31' + str(i + 1), ExecComp('con_y31' + str(i + 1) + '=(y31[' + str(i) + '] - y31k[' + str(i) + ']) ** 2', y31=self.y31, y31k=self.y31 ), promotes=['con_y31' + str(i + 1)]) self.connect('Propulsion.y31', 'con_Y31' + str(i + 1) + '.y31') self.connect('y31', 'con_Y31' + str(i + 1) + '.y31k') # Local constraints for i in range(self.nx): self.add_subsystem('con_G1' + str(i + 1), ExecComp('con_g1' + str(i + 1) + '=g1[' + str(i) + ']', g1=np.zeros(self.nx)), promotes=['con_g1' + str(i + 1)]) self.connect('parallel.Structure.g1', 'con_G1' + str(i + 1) + '.g1') for i in range(self.nx): self.add_subsystem('con_G2' + str(i + 1), ExecComp('con_g2' + str(i + 1) + '=g2[' + str(i) + ']', g2=np.zeros(self.nx)), promotes=['con_g2' + str(i + 1)]) self.connect('parallel.Aerodynamics.g2', 'con_G2' + str(i + 1) + '.g2') for i in range(self.nx): self.add_subsystem('con_G3' + str(i + 1), ExecComp('con_g3' + str(i + 1) + '=g3[' + str(i) + ']', g3=np.zeros(self.nx)), promotes=['con_g3' + str(i + 1)]) self.connect('Propulsion.g3', 'con_G3' + str(i + 1) + '.g3')
TypeError: argument 1 must be ImagingCore, not ImagingCore
Under the Windows I get this error. How to fix PIL? This is error: TypeError: argument 1 must be ImagingCore, not ImagingCore #!/usr/bin/python ## -*- coding: utf-8 -*- from PIL import Image, ImageFont import ImageDraw, StringIO, string from random import * from math import * import os SITE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) class Captcha3d(object): _hypot = 4 _xx, _yy = 35, 70 _CIMAGE = None _CHARS = string.ascii_lowercase + string.ascii_uppercase + string.digits _TEXT = '' def __init__(self): self._CIMAGE = Image.new("RGB", (self._yy * self._hypot, self._xx * self._hypot), (255,255,255)) self.generateCode() self.render() def imageColorAllocate(self, r,g,b): hexchars = "0123456789ABCDEF" hexcolor = hexchars[r / 16] + hexchars[r % 16] + hexchars[g / 16] + hexchars[g % 16] + hexchars[b / 16] + hexchars[b % 16] return int(hexcolor, 16) def generateCode(self): chars = self._CHARS self._TEXT = "".join(choice(chars) for x in range(randint(3, 3))) def getText(self): return self._TEXT def getProection(self, x1,y1,z1): x = x1 * self._hypot y = z1 * self._hypot z = -y1 * self._hypot xx = 0.707106781187 xy = 0 xz = -0.707106781187 yx = 0.408248290464 yy = 0.816496580928 yz = 0.408248290464 # 1/sqrt(6) cx = xx*x + xy*y + xz*z cy = yx*x + yy*y + yz*z + 20*self._hypot return [cx, cy] def zFunction(self, x,y): z = 2.6 if self._CIMAGE.getpixel((y/2,x/2)) == (0,0,0): z = 0 if z != 0: z += float(randint(0,60))/100 z += 1.4 * sin((x+self.startX)*pi/15) * sin((y+self.startY)*pi/15) return z def render(self): fontSans = ImageFont.truetype(os.path.join(SITE_PATH, "data", "fonts", "FreeSans.ttf"), 14) draw = ImageDraw.Draw(self._CIMAGE) whiteColor = 'white' draw.rectangle([0, 0, self._yy * self._hypot, self._xx * self._hypot], fill=whiteColor) #textColor = 'black' #imgtext = Image.open("i8n.png") #self._CIMAGE.paste(imgtext, (0,0)) imgtext = Image.new("1", (self._yy * self._hypot, self._xx * self._hypot), (1)) drawtext = ImageDraw.Draw(imgtext) drawtext.text((1,0), self._TEXT, font=fontSans, fill=0) self._CIMAGE.paste(imgtext, (0,0)) #draw.text((2,0), self.text, font=fontSans, fill=textColor) self.startX = randint(0,self._xx) self.startY = randint(0,self._yy) crd = {} x = 0 while x < (self._xx+1): y = 0 while y < (self._yy+1): crd[str(x) + '&' + str(y)] = self.getProection(x,y,self.zFunction(x,y)) y += 1 x += 1 x = 0 while x < self._xx: y = 0 while y < self._yy: coord = [] coord.append((int(crd[str(x) + '&' + str(y)][0]),int(crd[str(x) + '&' + str(y)][1]))) coord.append((int(crd[str(x+1) + '&' + str(y)][0]),int(crd[str(x+1) + '&' + str(y)][1]))) coord.append((int(crd[str(x+1) + '&' + str(y+1)][0]),int(crd[str(x+1) + '&' + str(y+1)][1]))) coord.append((int(crd[str(x) + '&' + str(y+1)][0]),int(crd[str(x) + '&' + str(y+1)][1]))) c = int(self.zFunction(x,y)*32) linesColor = (c,c,c) draw.polygon(coord, fill=whiteColor, outline=linesColor) #draw.polygon(coord, fill=whiteColor) y += 1 x += 1 draw.rectangle([0, 0, self._xx, self._yy], fill=whiteColor) #draw.text((2,0), self.text, font=fontSans, fill=textColor) #imageString($this->image, 1, 3, 0, (microtime(true)-$this->time), $textColor); del draw #self._CIMAGE.save("image.png", "PNG") return [self._CIMAGE, self._TEXT] def main(): a = Captcha3d() print a.getText() if __name__ == '__main__': main()
Also happens for me on OSX 10.6.8, Python 2.6.5. I think some class is getting dynamically imported twice. Try changing from PIL import Image, ImageFont to import Image, ImageFont That worked for me.
In my case it solved the situation to also import ImageDraw from PIL from PIL import ImageDraw
importing all PIL things directly from PIL should always work. However, if you mix imports, as such, from PIL import Image import ImageDraw This can lead to conflict between two un-identical PIL libraries. This can happen if you have installed both PIL and Pillow We should really always do, from PIL import Image from PIL import ImageDraw etc. I.e. be specific about which package to use.
Error in python replace. (AttributeError: 'tuple' object has no attribute 'replace')
Environment I am using Python 3 and my OS is Windows 7. I understand that some commands have changed from the transition from python 2.7 to 3 (What I have used). Problem The variable is temporary but is this: (((((0, 7), 7), 8), 4), 5) Here is the code to get rid of the brackets: randy = randy.replace(")", "") randy = randy.replace("(", "") randy = randy.replace(" ", "") When it tries to execute the replace function, I get thrown an error: Traceback (most recent call last): File "<string>", line 248, in run_nodebug File "Criptic.py", line 134, in <module> randy = randy.replace(")", "") AttributeError: 'tuple' object has no attribute 'replace' Edit: Here is all of the code: #Import string import string import random #Input user data text = input("Enter your text to be converted: ") #Test Print print("-------------------------") print("Your text is: ",text) #Break up all the data data = list(text) #Lowercase count = text.count("a") count1 = text.count("b") count2 = text.count("c") count3 = text.count("d") count4 = text.count("e") count5 = text.count("f") count6 = text.count("g") count7 = text.count("h") count8 = text.count("i") count9 = text.count("j") count10 = text.count("k") count11 = text.count("l") count12 = text.count("m") count13 = text.count("n") count14 = text.count("o") count15 = text.count("p") count16 = text.count("q") count17 = text.count("r") count18 = text.count("s") count19 = text.count("t") count20 = text.count("u") count21 = text.count("v") count22 = text.count("w") count23 = text.count("x") count24 = text.count("y") count25 = text.count("z") count26 = text.count("A") #Uppercase count27 = text.count("B") count28 = text.count("C") count29 = text.count("D") count30 = text.count("E") count31 = text.count("F") count32 = text.count("G") count33 = text.count("H") count34 = text.count("I") count35 = text.count("J") count36 = text.count("K") count37 = text.count("L") count38 = text.count("M") count39 = text.count("N") count40 = text.count("O") count41 = text.count("P") count42 = text.count("Q") count43 = text.count("R") count44 = text.count("S") count45 = text.count("T") count46 = text.count("U") count47 = text.count("V") count48 = text.count("W") count49 = text.count("X") count50 = text.count("Y") count51 = text.count("Z") #Other Characters count52 = text.count(" ") count53 = text.count("?") count54 = text.count("#") count55 = text.count("(") count56 = text.count(")") count57 = text.count(".") #Numbers count58 = text.count("1") count59 = text.count("2") count60 = text.count("3") count61 = text.count("4") count62 = text.count("5") count63 = text.count("6") count64 = text.count("7") count65 = text.count("8") count66 = text.count("9") count67 = text.count("0") #Counting how many characters in the sentence finalcount = count + count1 + count2 + count3 + count4 + count5 + count6 + count7 + count8 + count9 + count10 + count11 + count12 + count13 + count14 + count15 + count16 + count17 + count18 + count19 + count20 + count21 + count22 + count23 + count24 + count25 + count26 + count27 + count28 + count29 + count31 + count32 + count33 + count34 + count35 + count36 + count37 + count38 + count39 + count40 + count41 + count42 + count43 + count44 + count45 + count46 + count47 + count48 + count49 + count50 + count51 + count52 + count53 + count54 + count55 + count56 + count57 + count58 + count59 + count60 + count61 + count62 + count63 + count64 + count65 + count66 + count67 #Final count of Characters print(" Chars: ",finalcount) print("-------------------------") char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!##$%^&*()?_+-=1234567890 " charnum = 74 + 11 list(char) randy = 0 num = 0 while num < finalcount: rand = random.randrange(1,9) randy = randy,rand finalcount = finalcount - 1 if rand == 1: print(text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",") if rand == 2: print(char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",") if rand == 3: print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",") if rand == 4: print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",") if rand == 5: print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",") if rand == 6: print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",") if rand == 7: print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],",") if rand == 8: print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],char[random.randrange(0,charnum)],",") if rand == 9: print(char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],char[random.randrange(0,charnum)],text[finalcount],",") randy = randy.replace(")", "") randy = randy.replace("(", "") randy = randy.replace(" ", "") print("-------------------------") print("::::::::Completed::::::::") print("-------------------------") print(randy) print("-This is your code unlock key. Without this code it will not decript!!!! ") print("-------------------------")
You have a tuple (a sort of list) of numbers, and you want to make that a string. You can't replace the brackets, they aren't a part of the variable, they are just a part of its representation. Instead you should use join() and str() result = " ".join(str(x) for x in randy) However, this probably will not give the right result either, as it is a nested list of tuples. You probably mean: randy = randy + (rand,) instead if randy = randy,rand.
randy = randy,rand This notation creates a tuple of two elements, tuples do not have a method called replace. If you just want to concatenate the numbers into a list representation separated by commas, you could do this in your loop: randy = [] num = 0 while num < finalcount: rand = random.randrange(1,9) randy.append(rand) Then you remove the replace lines, and instead do this randy = ",".join(randy) to get a string that has the values separated by commas. You should maybe add the output that you would like to get to your question, because at the moment it's not quite clear what you want to do exactly.
exam_st_date = (11, 12, 2014) # Sample Output : The examination will start from : 11 / 12 / 2014 newtup = str(exam_st_date).replace(',', ' /') print(newtup) look at mine example should give you some results
To delete a list of characters, you could use the string's translate method: import string name = "(((((0, 7), 7), 8), 4), 5)" table = string.maketrans( '', '', ) print name.translate(table,"()")