<commit_before>
from memops.gui.Button import Button
from memops.gui.CheckButton import CheckButton
from memops.gui.FloatEntry import FloatEntry
from memops.gui.IntEntry import IntEntry
from memops.gui.Label import Label
from memops.gui.PulldownList import PulldownList
from memops.gui.ScrolledGraph import ScrolledGraph
from memops.gui.Entry import Entry
from ccpnmr.analysis.core.AssignmentBasic import getShiftLists

class AnnealingSettingsTab(object) :

  def __init__(self, parent, frame) :

    self.guiParent = parent

    self.frame = frame

    self.project = parent.project

    self.nmrProject = parent.nmrProject

    self.minIsoFrac = 0.1
    self.leavePeaksOutFraction = 0.0
    self.minTypeScore = 1.0
    self.chain         = None
    self.amountOfRepeats = 10
    self.amountOfSteps = 10000
    #self.acceptanceConstantList = [0, 0.1, 0.2,0.4, 0.8,1.0, 1.1, 1.2, 1.4, 1.6,2.0, 2.4,2.8, 3.2,4.0,4.5,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0]
    self.acceptanceConstantList = [0.0, 0.01, 0.015, 0.022, 0.033, 0.050, 0.075, 0.113, 0.170, 0.256, 0.384, 0.576, 0.864, 1.297, 1.946, 2.919, 4.378, 6.568, 9.852, 14.77, 22.16, 33.25]
    self.energyDataSets = [[]]

    self.body()

  def body(self) :

    frame = self.frame

    #frame.expandGrid(13,0)
    frame.expandGrid(13,1)
    row = 0

    text = 'Calculate Assignment Suggestions'
    command = self.runCalculations
    self.startButton = Button(frame,command=command, text=text)
    self.startButton.grid(row=row, column=0, sticky='nsew', columnspan=2)

    row += 1

    label = Label(frame, text='Amount of runs: ', grid=(row,0))
    tipText = 'The amount of times the whole optimization procedure is performed, each result is safed'
    self.repeatEntry = IntEntry(frame, grid=(row,1), width=7, text=10,
                                      returnCallback=self.updateRepeatEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.repeatEntry.bind('<Leave>', self.updateRepeatEntry, '+')

    row += 1

    label = Label(frame, text='Temperature regime: ', grid=(row,0))
    tipText = 'This list of numbers govern the temperature steps during the annealing, every number represents 1/(kb*t), where kb is the Boltzmann constant and t the temperature of one step.'
    self.tempEntry = Entry(frame, text=map(str, self.acceptanceConstantList), width=64,
                           grid=(row,1), isArray=True, returnCallback=self.updateAcceptanceConstantList,
                           tipText=tipText, sticky= 'nsew')

    row += 1

    label = Label(frame, text='Amount of attempts per temperature:', grid=(row,0))
    tipText = 'The amount of attempts to switch the position of two spinsystems in the sequence are performed for each temperature point'
    self.NAStepEntry = IntEntry(frame, grid=(row,1), width=7, text=10000,
                                      returnCallback=self.updateStepEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.NAStepEntry.bind('<Leave>', self.updateStepEntry, '+')

    row += 1

    label = Label(frame, text='Fraction of peaks to leave out:', grid=(row,0))
    tipText = 'In each run a fraction of the peaks can be left out of the optimization, thereby increasing the variability in the outcome and reducing false negatives. In each run this will be different randomly chosen sub-set of all peaks. 0.1 (10%) can be a good value.'
    self.leaveOutPeaksEntry = FloatEntry(frame, grid=(row,1), width=7, text=0.0,
                                      returnCallback=self.updateLeavePeaksOutEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.leaveOutPeaksEntry.bind('<Leave>', self.updateLeavePeaksOutEntry , '+')

    row += 1

    label = Label(frame, text='Minmal amino acid typing score:', grid=(row,0))
    tipText = 'If automatic amino acid typing is selected, a cut-off value has to set. Every amino acid type that scores higher than the cut-off is taken as a possible type. This is the same score as can be found under resonance --> spin systems --> predict type. Value should be between 0 and 100'
    self.minTypeScoreEntry = FloatEntry(frame, grid=(row,1), width=7, text=1.0,
                                      returnCallback=self.updateMinTypeScoreEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.minTypeScoreEntry.bind('<Leave>', self.updateMinTypeScoreEntry, '+')

    row += 1

    label = Label(frame, text='Minimal colabelling fraction:', grid=(row,0))
    tipText = 'The minimal amount of colabelling the different nuclei should have in order to still give rise to a peak.'
    self.minLabelEntry = FloatEntry(frame, grid=(row,1), width=7, text=0.1,
                                      returnCallback=self.updateMinLabelEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.minLabelEntry.bind('<Leave>', self.updateMinLabelEntry, '+')

    row += 1

    label= Label(frame, text = 'Use sequential assignments:', grid=(row,0))
    tipText = 'When this option is select the present sequential assignments will be kept in place'
    self.useAssignmentsCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label= Label(frame, text = 'Use tentative assignments:', grid=(row,0))
    tipText = 'If a spin system has tentative assignments this can be used to narrow down the amount of possible sequential assignments.'
    self.useTentativeCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label = Label(frame, text='Use amino acid types:', grid=(row,0))
    tipText = 'Use amino acid types of the spin systems. If this option is not checked the spin systems are re-typed, only resonance names and frequencies are used'
    self.useTypeCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label = Label(frame, text='Include untyped spin systems:', grid=(row,0))
    tipText = 'Also include spin system that have no type information. Amino acid typing will be done on the fly.'
    self.useAlsoUntypedSpinSystemsCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label = Label(frame, text='Use dimensional assignments:', grid=(row,0))
    tipText = 'If one or more dimensions of a peak is already assigned, assume that this assignment is the only option. If not the check the program will consider all possibilities for the assignment of the dimension.'
    self.useDimenionalAssignmentsCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    self.shiftListLabel    = Label(frame, text ='Shift List:', grid=(row,0), sticky='w')
    self.shiftListPulldown = PulldownList(frame, self.changeShiftList, grid=(row,1), sticky='w')

    row += 1

    label = Label(frame, text='Chain:', grid=(row,0))
    self.molPulldown = PulldownList(frame, callback=self.changeMolecule, grid=(row,1))
    self.updateChains()

    self.updateShiftLists()

    row += 1

    self.energyPlot = ScrolledGraph(frame,symbolSize=2, width=600,
                                       height=200, title='Annealing',
                                       xLabel='time', yLabel='energy')
    self.energyPlot.grid(row=row, column=0, columnspan=2, sticky='nsew')

  def runCalculations(self):

    self.startButton.disable()
    self.disableIllegalButtonsAfterPrecalculations()
    self.guiParent.connector.runAllCalculations()
    self.startButton.configure(text='More runs')
    self.startButton.enable()

  def disableIllegalButtonsAfterPrecalculations(self):

    illegalButtons = [self.minTypeScoreEntry, self.minLabelEntry,
                      self.useAlsoUntypedSpinSystemsCheck, self.useAssignmentsCheck,
                      self.useTypeCheck, self.useDimenionalAssignmentsCheck,
                      self.useTentativeCheck]

    for illegalButton in illegalButtons :
      illegalButton.configure(state='disabled')

    self.molPulldown.disable()
    self.shiftListPulldown.disable()

  def getChainName(self, chain):

    return '%s:%s (%s)' % (chain.molSystem.code,chain.code,chain.molecule.molType)

  def getChains(self):

    chains = []
    if self.project:
      for molSystem in self.project.sortedMolSystems():
        for chain in molSystem.sortedChains():
          if chain.residues:
            chains.append(chain)

    return chains

  def updateChains(self, *opt):

    index  = 0
    texts  = []
    chains = self.getChains()
    chain  = self.chain

    if chains:
      if chain not in chains:
        chain = chains[0]

      texts = [self.getChainName(c) for c in chains]
      index = chains.index(chain)

    else:
      chain = None

    self.molPulldown.setup(texts,chains,index)

    if chain is not self.chain:
      self.chain = chain

  def changeMolecule(self, chain):

    if chain is not self.chain:
      self.chain = chain

  def changeShiftList(self, shiftList):

    if self.shiftList is not shiftList:
      self.shiftList = shiftList

  def updateShiftLists(self):

    index = 0
    shiftLists = getShiftLists(self.nmrProject) + [None,]
    shiftListNames = self.getShiftListNames(shiftLists[:-1]) + ['None',]

    if shiftListNames:
      self.shiftList = shiftLists[0]
      index = 0

    else:
      shiftList = None

    self.shiftListPulldown.setup(shiftListNames,shiftLists,index)

  def getShiftListNames(self, shiftLists):

    shiftListNames = []
    for shiftList in shiftLists:
      if not shiftList.name:
        shiftList.name = "ShiftList "+ str(shiftList.serial)
      shiftListNames.append(shiftList.name)

    return shiftListNames

  def updateStepEntry(self,  event =None):

    value = self.NAStepEntry.get()
    if value == self.amountOfSteps:
      return
    if value < 1:
      self.NAStepEntry.set(1)
      self.amountOfSteps = 1
    else :
      self.amountOfSteps = value
      self.NAStepEntry.set(value)

  def updateRepeatEntry(self,  event =None):

    value = self.repeatEntry.get()

    if value == self.amountOfRepeats:
      return
    if value < 1:
      self.repeatEntry.set(1)
      self.amountOfRepeats = 1
    else :
      self.amountOfRepeats = value
      self.repeatEntry.set(value)

  def updateMinTypeScoreEntry(self, event = None) :

    value = self.minTypeScoreEntry.get()

    if value == self.minTypeScore :
      return
    if value < 0:
      self.minTypeScoreEntry.set(0.0)
      self.minTypeScore = 0.0
    elif value > 100 :
      self.minTypeScoreEntry.set(100.0)
      self.minTypeScore = 100.0
    else :
      self.minTypeScoreEntry.set(value)
      self.minTypeScore = value

  def updateMinLabelEntry(self, event=None) :

    value = self.minLabelEntry.get()

    if value == self.minIsoFrac :
      return
    if value < 0 :
      self.minIsoFrac = 0.0
      self.minLabelEntry.set(0.0)
    elif value > 1 :
      self.minIsoFrac = 1.0
      self.minLabelEntry.set(1.0)
    else :
      self.minIsoFrac = value
      self.minLabelEntry.set(value)

  def updateLeavePeaksOutEntry(self, event=None) :

    value = self.leaveOutPeaksEntry.get()

    if value == self.leavePeaksOutFraction :
      return
    if value < 0 :
      self.leavePeaksOutFraction = 0.0
      self.leaveOutPeaksEntry.set(0.0)
    elif value > 1 :
      self.leavePeaksOutFraction = 1.0
      self.leaveOutPeaksEntry.set(1.0)
    else :
      self.leavePeaksOutFraction = value
      self.leaveOutPeaksEntry.set(value)

  def updateAcceptanceConstantList(self,event=None) :

    acList = self.tempEntry.get()

    newList = []

    for constant in acList :

      try :

        number = float(constant)

        newList.append(number)

      except ValueError :

        string = constant + ' in temperature constants is not a number.'

        showWarning('Not A Number', string, parent=self.guiParent)

        return False

    self.acceptanceConstantList = newList

    return True

  def addEnergyPoint(self,energy,time) :

    point = (time,energy*-1)

    if len(self.energyDataSets[-1]) / (len(self.acceptanceConstantList) + 1) :                # This means one run has finished

      self.energyDataSets.append([point])

    else :

      self.energyDataSets[-1].append(point)

    colors = ['#993366','#000000','#FF0099','#33FF00','#003300','#999999','#FF6633','#000099','#33CCFF','#FFCC00']

    Ncolors = len(colors)

    NdataSets = len(self.energyDataSets)

    colorList = (NdataSets/Ncolors)*colors + colors[:NdataSets%Ncolors]

    self.energyPlot.update(dataSets=self.energyDataSets, dataColors=colorList)

    # Forcing the graph to draw, eventhough calculations
    # are still running. Only do this with high numbers of
    # steps, otherwise drawing takes longer than annealling.
    if self.amountOfSteps >= 100000 :

      self.energyPlot.draw()
  <commit_msg>Changed some labels on the annealing graph<commit_after>
from memops.gui.Button import Button
from memops.gui.CheckButton import CheckButton
from memops.gui.FloatEntry import FloatEntry
from memops.gui.IntEntry import IntEntry
from memops.gui.Label import Label
from memops.gui.PulldownList import PulldownList
from memops.gui.ScrolledGraph import ScrolledGraph
from memops.gui.Entry import Entry
from ccpnmr.analysis.core.AssignmentBasic import getShiftLists

class AnnealingSettingsTab(object) :

  def __init__(self, parent, frame) :

    self.guiParent = parent

    self.frame = frame

    self.project = parent.project

    self.nmrProject = parent.nmrProject

    self.minIsoFrac = 0.1
    self.leavePeaksOutFraction = 0.0
    self.minTypeScore = 1.0
    self.chain         = None
    self.amountOfRepeats = 10
    self.amountOfSteps = 10000
    #self.acceptanceConstantList = [0, 0.1, 0.2,0.4, 0.8,1.0, 1.1, 1.2, 1.4, 1.6,2.0, 2.4,2.8, 3.2,4.0,4.5,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0]
    self.acceptanceConstantList = [0.0, 0.01, 0.015, 0.022, 0.033, 0.050, 0.075, 0.113, 0.170, 0.256, 0.384, 0.576, 0.864, 1.297, 1.946, 2.919, 4.378, 6.568, 9.852, 14.77, 22.16, 33.25]
    self.energyDataSets = [[]]

    self.body()

  def body(self) :

    frame = self.frame

    #frame.expandGrid(13,0)
    frame.expandGrid(13,1)
    row = 0

    text = 'Calculate Assignment Suggestions'
    command = self.runCalculations
    self.startButton = Button(frame,command=command, text=text)
    self.startButton.grid(row=row, column=0, sticky='nsew', columnspan=2)

    row += 1

    label = Label(frame, text='Amount of runs: ', grid=(row,0))
    tipText = 'The amount of times the whole optimization procedure is performed, each result is safed'
    self.repeatEntry = IntEntry(frame, grid=(row,1), width=7, text=10,
                                      returnCallback=self.updateRepeatEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.repeatEntry.bind('<Leave>', self.updateRepeatEntry, '+')

    row += 1

    label = Label(frame, text='Temperature regime: ', grid=(row,0))
    tipText = 'This list of numbers govern the temperature steps during the annealing, every number represents 1/(kb*t), where kb is the Boltzmann constant and t the temperature of one step.'
    self.tempEntry = Entry(frame, text=map(str, self.acceptanceConstantList), width=64,
                           grid=(row,1), isArray=True, returnCallback=self.updateAcceptanceConstantList,
                           tipText=tipText, sticky= 'nsew')

    row += 1

    label = Label(frame, text='Amount of attempts per temperature:', grid=(row,0))
    tipText = 'The amount of attempts to switch the position of two spinsystems in the sequence are performed for each temperature point'
    self.NAStepEntry = IntEntry(frame, grid=(row,1), width=7, text=10000,
                                      returnCallback=self.updateStepEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.NAStepEntry.bind('<Leave>', self.updateStepEntry, '+')

    row += 1

    label = Label(frame, text='Fraction of peaks to leave out:', grid=(row,0))
    tipText = 'In each run a fraction of the peaks can be left out of the optimization, thereby increasing the variability in the outcome and reducing false negatives. In each run this will be different randomly chosen sub-set of all peaks. 0.1 (10%) can be a good value.'
    self.leaveOutPeaksEntry = FloatEntry(frame, grid=(row,1), width=7, text=0.0,
                                      returnCallback=self.updateLeavePeaksOutEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.leaveOutPeaksEntry.bind('<Leave>', self.updateLeavePeaksOutEntry , '+')

    row += 1

    label = Label(frame, text='Minmal amino acid typing score:', grid=(row,0))
    tipText = 'If automatic amino acid typing is selected, a cut-off value has to set. Every amino acid type that scores higher than the cut-off is taken as a possible type. This is the same score as can be found under resonance --> spin systems --> predict type. Value should be between 0 and 100'
    self.minTypeScoreEntry = FloatEntry(frame, grid=(row,1), width=7, text=1.0,
                                      returnCallback=self.updateMinTypeScoreEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.minTypeScoreEntry.bind('<Leave>', self.updateMinTypeScoreEntry, '+')

    row += 1

    label = Label(frame, text='Minimal colabelling fraction:', grid=(row,0))
    tipText = 'The minimal amount of colabelling the different nuclei should have in order to still give rise to a peak.'
    self.minLabelEntry = FloatEntry(frame, grid=(row,1), width=7, text=0.1,
                                      returnCallback=self.updateMinLabelEntry,
                                      tipText=tipText, sticky= 'nsew')
    self.minLabelEntry.bind('<Leave>', self.updateMinLabelEntry, '+')

    row += 1

    label= Label(frame, text = 'Use sequential assignments:', grid=(row,0))
    tipText = 'When this option is select the present sequential assignments will be kept in place'
    self.useAssignmentsCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label= Label(frame, text = 'Use tentative assignments:', grid=(row,0))
    tipText = 'If a spin system has tentative assignments this can be used to narrow down the amount of possible sequential assignments.'
    self.useTentativeCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label = Label(frame, text='Use amino acid types:', grid=(row,0))
    tipText = 'Use amino acid types of the spin systems. If this option is not checked the spin systems are re-typed, only resonance names and frequencies are used'
    self.useTypeCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label = Label(frame, text='Include untyped spin systems:', grid=(row,0))
    tipText = 'Also include spin system that have no type information. Amino acid typing will be done on the fly.'
    self.useAlsoUntypedSpinSystemsCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    label = Label(frame, text='Use dimensional assignments:', grid=(row,0))
    tipText = 'If one or more dimensions of a peak is already assigned, assume that this assignment is the only option. If not the check the program will consider all possibilities for the assignment of the dimension.'
    self.useDimenionalAssignmentsCheck = CheckButton(frame, selected=True, tipText=tipText, grid=(row,1))

    row += 1

    self.shiftListLabel    = Label(frame, text ='Shift List:', grid=(row,0), sticky='w')
    self.shiftListPulldown = PulldownList(frame, self.changeShiftList, grid=(row,1), sticky='w')

    row += 1

    label = Label(frame, text='Chain:', grid=(row,0))
    self.molPulldown = PulldownList(frame, callback=self.changeMolecule, grid=(row,1))
    self.updateChains()

    self.updateShiftLists()

    row += 1

    self.energyPlot = ScrolledGraph(frame,symbolSize=2, width=600,
                                       height=200, title='Annealing',
                                       xLabel='temperature step', yLabel='energy')
    self.energyPlot.grid(row=row, column=0, columnspan=2, sticky='nsew')

  def runCalculations(self):

    self.startButton.disable()
    self.disableIllegalButtonsAfterPrecalculations()
    self.guiParent.connector.runAllCalculations()
    self.startButton.configure(text='More runs')
    self.startButton.enable()

  def disableIllegalButtonsAfterPrecalculations(self):

    illegalButtons = [self.minTypeScoreEntry, self.minLabelEntry,
                      self.useAlsoUntypedSpinSystemsCheck, self.useAssignmentsCheck,
                      self.useTypeCheck, self.useDimenionalAssignmentsCheck,
                      self.useTentativeCheck]

    for illegalButton in illegalButtons :
      illegalButton.configure(state='disabled')

    self.molPulldown.disable()
    self.shiftListPulldown.disable()

  def getChainName(self, chain):

    return '%s:%s (%s)' % (chain.molSystem.code,chain.code,chain.molecule.molType)

  def getChains(self):

    chains = []
    if self.project:
      for molSystem in self.project.sortedMolSystems():
        for chain in molSystem.sortedChains():
          if chain.residues:
            chains.append(chain)

    return chains

  def updateChains(self, *opt):

    index  = 0
    texts  = []
    chains = self.getChains()
    chain  = self.chain

    if chains:
      if chain not in chains:
        chain = chains[0]

      texts = [self.getChainName(c) for c in chains]
      index = chains.index(chain)

    else:
      chain = None

    self.molPulldown.setup(texts,chains,index)

    if chain is not self.chain:
      self.chain = chain

  def changeMolecule(self, chain):

    if chain is not self.chain:
      self.chain = chain

  def changeShiftList(self, shiftList):

    if self.shiftList is not shiftList:
      self.shiftList = shiftList

  def updateShiftLists(self):

    index = 0
    shiftLists = getShiftLists(self.nmrProject) + [None,]
    shiftListNames = self.getShiftListNames(shiftLists[:-1]) + ['None',]

    if shiftListNames:
      self.shiftList = shiftLists[0]
      index = 0

    else:
      shiftList = None

    self.shiftListPulldown.setup(shiftListNames,shiftLists,index)

  def getShiftListNames(self, shiftLists):

    shiftListNames = []
    for shiftList in shiftLists:
      if not shiftList.name:
        shiftList.name = "ShiftList "+ str(shiftList.serial)
      shiftListNames.append(shiftList.name)

    return shiftListNames

  def updateStepEntry(self,  event =None):

    value = self.NAStepEntry.get()
    if value == self.amountOfSteps:
      return
    if value < 1:
      self.NAStepEntry.set(1)
      self.amountOfSteps = 1
    else :
      self.amountOfSteps = value
      self.NAStepEntry.set(value)

  def updateRepeatEntry(self,  event =None):

    value = self.repeatEntry.get()

    if value == self.amountOfRepeats:
      return
    if value < 1:
      self.repeatEntry.set(1)
      self.amountOfRepeats = 1
    else :
      self.amountOfRepeats = value
      self.repeatEntry.set(value)

  def updateMinTypeScoreEntry(self, event = None) :

    value = self.minTypeScoreEntry.get()

    if value == self.minTypeScore :
      return
    if value < 0:
      self.minTypeScoreEntry.set(0.0)
      self.minTypeScore = 0.0
    elif value > 100 :
      self.minTypeScoreEntry.set(100.0)
      self.minTypeScore = 100.0
    else :
      self.minTypeScoreEntry.set(value)
      self.minTypeScore = value

  def updateMinLabelEntry(self, event=None) :

    value = self.minLabelEntry.get()

    if value == self.minIsoFrac :
      return
    if value < 0 :
      self.minIsoFrac = 0.0
      self.minLabelEntry.set(0.0)
    elif value > 1 :
      self.minIsoFrac = 1.0
      self.minLabelEntry.set(1.0)
    else :
      self.minIsoFrac = value
      self.minLabelEntry.set(value)

  def updateLeavePeaksOutEntry(self, event=None) :

    value = self.leaveOutPeaksEntry.get()

    if value == self.leavePeaksOutFraction :
      return
    if value < 0 :
      self.leavePeaksOutFraction = 0.0
      self.leaveOutPeaksEntry.set(0.0)
    elif value > 1 :
      self.leavePeaksOutFraction = 1.0
      self.leaveOutPeaksEntry.set(1.0)
    else :
      self.leavePeaksOutFraction = value
      self.leaveOutPeaksEntry.set(value)

  def updateAcceptanceConstantList(self,event=None) :

    acList = self.tempEntry.get()

    newList = []

    for constant in acList :

      try :

        number = float(constant)

        newList.append(number)

      except ValueError :

        string = constant + ' in temperature constants is not a number.'

        showWarning('Not A Number', string, parent=self.guiParent)

        return False

    self.acceptanceConstantList = newList

    return True

  def addEnergyPoint(self,energy,time) :

    point = (time,energy*-1)

    if len(self.energyDataSets[-1]) / (len(self.acceptanceConstantList) + 1) :                # This means one run has finished

      self.energyDataSets.append([point])

    else :

      self.energyDataSets[-1].append(point)

    colors = ['#993366','#000000','#FF0099','#33FF00','#003300','#999999','#FF6633','#000099','#33CCFF','#FFCC00']

    Ncolors = len(colors)

    NdataSets = len(self.energyDataSets)

    colorList = (NdataSets/Ncolors)*colors + colors[:NdataSets%Ncolors]

    self.energyPlot.update(dataSets=self.energyDataSets, dataColors=colorList)

    # Forcing the graph to draw, eventhough calculations
    # are still running. Only do this with high numbers of
    # steps, otherwise drawing takes longer than annealling.
    if self.amountOfSteps >= 100000 :

      self.energyPlot.draw()
  <|endoftext|>


<commit_before>from flask import Flask
from flask.ext import restful

from reding.settings import DAEMON_CONFIG
from reding.resources import ObjectList, ObjectUsers, Object, UserList, UserObject

app = Flask(__name__)
api = restful.Api(app)

api.add_resource(ObjectList, '/objects/')
api.add_resource(ObjectUsers, '/objects/<string:object_id>/users/')
api.add_resource(Object, '/objects/<string:object_id>/')
api.add_resource(UserList, '/users/<string:user_id>/')
api.add_resource(
    UserObject,
    '/objects/<string:object_id>/users/<string:user_id>/'
)

if __name__ == '__main__':
    #app.run(debug=True)
    from cherrypy import wsgiserver

    w = wsgiserver.WSGIPathInfoDispatcher({'/': app.wsgi_app})
    server = wsgiserver.CherryPyWSGIServer(
        bind_addr=(
            DAEMON_CONFIG['host'],
            DAEMON_CONFIG['port']
        ),
        wsgi_app=w,
    )

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
<commit_msg>Information for setup.py added.<commit_after>__author__ = 'Giorgio Salluzzo <giorgio.salluzzo@gmail.com>'
__version__ = '0.1.0'
__classifiers__ = [
    'Development Status :: 4 - Beta',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Operating System :: OS Independent',
    'Programming Language :: Python :: 2.6',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python',
    'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
]
__copyright__ = "2013, Buongiorno Spa"
__license__ = """Copyright (C) %s

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" % __copyright__

__docformat__ = 'restructuredtext en'

__doc__ = """
:abstract: Rating on Redis - REST API on Flask
:version: %s
:author: %s
:contact: https://github.com/BuongiornoMIP/Reding
:date: 2013-02-01
:copyright: %s
""" % (__version__, __author__, __license__)

from flask import Flask
from flask.ext import restful

from reding.settings import DAEMON_CONFIG
from reding.resources import ObjectList, ObjectUsers, Object, UserList, UserObject

app = Flask(__name__)
api = restful.Api(app)

api.add_resource(ObjectList, '/objects/')
api.add_resource(ObjectUsers, '/objects/<string:object_id>/users/')
api.add_resource(Object, '/objects/<string:object_id>/')
api.add_resource(UserList, '/users/<string:user_id>/')
api.add_resource(
    UserObject,
    '/objects/<string:object_id>/users/<string:user_id>/'
)

if __name__ == '__main__':
    #app.run(debug=True)
    from cherrypy import wsgiserver

    w = wsgiserver.WSGIPathInfoDispatcher({'/': app.wsgi_app})
    server = wsgiserver.CherryPyWSGIServer(
        bind_addr=(
            DAEMON_CONFIG['host'],
            DAEMON_CONFIG['port']
        ),
        wsgi_app=w,
    )

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
<|endoftext|>


<commit_before>
import os
import sys
import numpy as np
import rasterio as rio
import pyproj

from l8 import BANDS

def extract(scene_directory, longitude, latitude, bands=[], neighborhood=0):
    """
    Extract pixel values at a specified geographic location.

    :param scene_directory:
        Directory point to Landsat 8 images. The path is
        is assumed to be composed of a Landsat8 scene id.

        LXSPPPRRRYYYYDDDGSIVV
        L = Landsat
        X = Sensor
        S = Satellite
        PPP = WRS path
        RRR = WRS row
        YYYY = Year
        DDD = Julian day of year
        GSI = Ground station identifier
        VV = Archive version number

    :param longitude:
        The longitude to sample in each image.

    :param latitude:
        The latitude to sample in each image.

    :param bands:
        The band(s) for which the timeseries will be extracted. Default is
        an empty list representing all bands.

    """

    if len(bands) == 0:
        bands = map(lambda d: d['name'], BANDS)

    scene = {
        "directory": scene_directory,
        "id": os.path.basename(os.path.normpath(scene_directory))
    }

    src_proj = pyproj.Proj(init='epsg:4326')
<<<<<<< Local Changes
<<<<<<< Local Changes
    b1path = os.path.join(scene_directory, "%s_B1.TIF")
    with rio.open(scene_directory, b1path) as src:
        dst_proj = pyproj.Proj(src.crs)
        s, t = pyproj.transform(src_proj, dst_proj, longitude, latitude)

        # Get the pixel corresponding to local coordinate s/t
        xc, yc = src.index(s, t)

        # Buffer the x/y point
        x0, y0 = xc - neighborhood, yc - neighborhood
        x1, y1 = xc + neighborhood + 1, yc + neighborhood + 1

    def get_value_from_band(scene, band):

        file_params = { "id": scene["id"], "bidx": band['bidx'] }
        srcpath = os.path.join(
            scene["directory"], "%(id)s_B%(bidx)s.TIF" % file_params
        )

        with rio.open(srcpath, "r") as src:

            # Get the window associated with the given longitude/latitude

            # Transform from longitude/latitude to the projection of the image
            dst_proj = pyproj.Proj(src.crs)
            s, t = pyproj.transform(src_proj, dst_proj, longitude, latitude)

            # Get the center pixel corresponding to s/t
            try:
                xc, yc = src.index(s, t)
            except ValueError:
                return np.nan

            x0, y0 = xc - neighborhood, yc - neighborhood
            x1, y1 = xc + neighborhood + 1, yc + neighborhood + 1

            s0, t0 = src.ul(x0, y0)
            s1, t1 = src.ul(x1, y1)

            smin, tmin = min(s0, s1), min(t0, t1)
            smax, tmax = max(s0, s1), max(t0, t1)

            window = src.window(smin, tmin, smax, tmax)
            return np.median(src.read_band(1, window=window))

    with rio.drivers():
        spectral_values = np.array(map(lambda band: get_value_from_band(scene, band), BANDS))
        return spectral_values
<commit_msg>rollback<commit_after>
import os
import sys
import numpy as np
import rasterio as rio
import pyproj

from l8 import BANDS

def extract(scene_directory, longitude, latitude, bands=[], neighborhood=0):
    """
    Extract pixel values at a specified geographic location.

    :param scene_directory:
        Directory point to Landsat 8 images. The path is
        is assumed to be composed of a Landsat8 scene id.

        LXSPPPRRRYYYYDDDGSIVV
        L = Landsat
        X = Sensor
        S = Satellite
        PPP = WRS path
        RRR = WRS row
        YYYY = Year
        DDD = Julian day of year
        GSI = Ground station identifier
        VV = Archive version number

    :param longitude:
        The longitude to sample in each image.

    :param latitude:
        The latitude to sample in each image.

    :param bands:
        The band(s) for which the timeseries will be extracted. Default is
        an empty list representing all bands.

    """

    if len(bands) == 0:
        bands = map(lambda d: d['name'], BANDS)

    scene = {
        "directory": scene_directory,
        "id": os.path.basename(os.path.normpath(scene_directory))
    }

    src_proj = pyproj.Proj(init='epsg:4326')

    def get_value_from_band(scene, band):

        file_params = { "id": scene["id"], "bidx": band['bidx'] }
        srcpath = os.path.join(
            scene["directory"], "%(id)s_B%(bidx)s.TIF" % file_params
        )

        with rio.open(srcpath, "r") as src:

            # Get the window associated with the given longitude/latitude

            # Transform from longitude/latitude to the projection of the image
            dst_proj = pyproj.Proj(src.crs)
            s, t = pyproj.transform(src_proj, dst_proj, longitude, latitude)

            # Get the center pixel corresponding to s/t
            try:
                xc, yc = src.index(s, t)
            except ValueError:
                return np.nan

            x0, y0 = xc - neighborhood, yc - neighborhood
            x1, y1 = xc + neighborhood + 1, yc + neighborhood + 1

            s0, t0 = src.ul(x0, y0)
            s1, t1 = src.ul(x1, y1)

            smin, tmin = min(s0, s1), min(t0, t1)
            smax, tmax = max(s0, s1), max(t0, t1)

            window = src.window(smin, tmin, smax, tmax)
            return np.median(src.read_band(1, window=window))

    with rio.drivers():
        spectral_values = np.array(map(lambda band: get_value_from_band(scene, band), BANDS))
        return spectral_values<|endoftext|>


<commit_before>"""
Tests for discrete models

Notes
-----
DECIMAL_3 is used because it seems that there is a loss of precision
in the Stata *.dta -> *.csv output, NOT the estimator for the Poisson
tests.
"""

import numpy as np
from numpy.testing import *
from scikits.statsmodels.discretemod import *
import scikits.statsmodels as sm
from sys import platform
from nose import SkipTest

DECIMAL_4 = 4
DECIMAL_3 = 3
DECIMAL_2 = 2
DECIMAL_1 = 1
DECIMAL_0 = 0
iswindows = 'win' in platform.lower()

class CheckModelResults(object):
    """
    res2 should be the test results from RModelWrap
    or the results as defined in model_results_data
    """
    def test_params(self):
        assert_almost_equal(self.res1.params, self.res2.params, DECIMAL_4)

    def test_conf_int(self):
        assert_almost_equal(self.res1.conf_int(), self.res2.conf_int, DECIMAL_4)

    def test_zstat(self):
        assert_almost_equal(self.res1.t(), self.res2.z, DECIMAL_4)

    def pvalues(self):
        assert_almost_equal(self.res1.pvalues, self.res2.pvalues, DECIMAL_4)

#    def test_cov_params(self):
#        assert_almost_equal(self.res1.cov_params(), self.res2.cov_params,
#                DECIMAL_4)

    def test_llf(self):
        assert_almost_equal(self.res1.llf, self.res2.llf, DECIMAL_4)

    def test_llnull(self):
        assert_almost_equal(self.res1.llnull, self.res2.llnull, DECIMAL_4)

    def test_llr(self):
        assert_almost_equal(self.res1.llr, self.res2.llr, DECIMAL_3)

    def test_llr_pvalue(self):
        assert_almost_equal(self.res1.llr_pvalue, self.res2.llr_pvalue,
                DECIMAL_4)

    def test_margeff(self):
        pass
    # this probably needs it's own test class?

    def test_normalized_cov_params(self):
        pass

    def test_bse(self):
        assert_almost_equal(self.res1.bse, self.res2.bse, DECIMAL_4)

    def test_dof(self):
        assert_equal(self.res1.df_model, self.res2.df_model)
        assert_equal(self.res1.df_resid, self.res2.df_resid)

    def test_aic(self):
        assert_almost_equal(self.res1.aic, self.res2.aic, DECIMAL_3)

    def test_bic(self):
        assert_almost_equal(self.res1.bic, self.res2.bic, DECIMAL_3)

class CheckMargEff():
    """
    Test marginal effects (margeff) and its options
    """

    def test_nodummy_dydxoverall(self):
        assert_almost_equal(self.res1.margeff(),
                self.res2.margeff_nodummy_dydx, DECIMAL_4)

    def test_nodummy_dydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean'),
                self.res2.margeff_nodummy_dydxmean, DECIMAL_4)

    def test_nodummy_dydxmedian(self):
        assert_almost_equal(self.res1.margeff(at='median'),
                self.res2.margeff_nodummy_dydxmedian, DECIMAL_4)

    def test_nodummy_dydxzero(self):
        assert_almost_equal(self.res1.margeff(at='zero'),
                self.res2.margeff_nodummy_dydxzero, DECIMAL_4)

    def test_nodummy_dyexoverall(self):
        assert_almost_equal(self.res1.margeff(method='dyex'),
                self.res2.margeff_nodummy_dyex, DECIMAL_4)

    def test_nodummy_dyexmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='dyex'),
                self.res2.margeff_nodummy_dyexmean, DECIMAL_4)

    def test_nodummy_dyexmedian(self):
        assert_almost_equal(self.res1.margeff(at='median', method='dyex'),
                self.res2.margeff_nodummy_dyexmedian, DECIMAL_4)

    def test_nodummy_dyexzero(self):
        assert_almost_equal(self.res1.margeff(at='zero', method='dyex'),
                self.res2.margeff_nodummy_dyexzero, DECIMAL_4)

    def test_nodummy_eydxoverall(self):
        assert_almost_equal(self.res1.margeff(method='eydx'),
                self.res2.margeff_nodummy_eydx, DECIMAL_4)

    def test_nodummy_eydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='eydx'),
                self.res2.margeff_nodummy_eydxmean, DECIMAL_4)

    def test_nodummy_eydxmedian(self):
        assert_almost_equal(self.res1.margeff(at='median', method='eydx'),
                self.res2.margeff_nodummy_eydxmedian, DECIMAL_4)

    def test_nodummy_eydxzero(self):
        assert_almost_equal(self.res1.margeff(at='zero', method='eydx'),
                self.res2.margeff_nodummy_eydxzero, DECIMAL_4)

    def test_nodummy_eyexoverall(self):
        assert_almost_equal(self.res1.margeff(method='eyex'),
                self.res2.margeff_nodummy_eyex, DECIMAL_4)

    def test_nodummy_eyexmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='eyex'),
                self.res2.margeff_nodummy_eyexmean, DECIMAL_4)

    def test_nodummy_eyexmedian(self):
        assert_almost_equal(self.res1.margeff(at='median', method='eyex'),
                self.res2.margeff_nodummy_eyexmedian, DECIMAL_4)

    def test_nodummy_eyexzero(self):
        assert_almost_equal(self.res1.margeff(at='zero', method='eyex'),
                self.res2.margeff_nodummy_eyexzero, DECIMAL_4)

    def test_dummy_dydxoverall(self):
        assert_almost_equal(self.res1.margeff(dummy=True),
                self.res2.margeff_dummy_dydx, DECIMAL_4)

    def test_dummy_dydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', dummy=True),
                self.res2.margeff_dummy_dydxmean, DECIMAL_4)

    @dec.knownfailureif(True, "The discrete change elasticity is not correct")
    def test_dummy_eydxoverall(self):
        assert_almost_equal(self.res1.margeff(method='eydx', dummy=True),
                self.res2.margeff_dummy_eydx, DECIMAL_4)

    @dec.knownfailureif(True, "The discrete change elasticity is not correct")
    def test_dummy_eydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='eydx',
            dummy=True), self.res2.margeff_dummy_eydxmean, DECIMAL_4)

class TestProbitNewton(CheckModelResults):
    def __init__(self):
        from results.results_discrete import Spector
        data = sm.datasets.spector.load()
        data.exog = sm.add_constant(data.exog)
        self.data = data
        self.res1 = Probit(data.endog, data.exog).fit(method="newton", disp=0)
        res2 = Spector()
        res2.probit()
        self.res2 = res2

    def test_predict(self):
        assert_almost_equal(self.res1.model.predict(self.data.exog),
                self.res2.predict, DECIMAL_4)

    def test_resid(self):
        assert_almost_equal(self.res1.resid, self.res2.resid, DECIMAL_4)

class TestProbitBFGS(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="bfgs",
            disp=0)

class TestProbitNM(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="nm",
            disp=0, maxiter=500)

class TestProbitPowell(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="powell",
            disp=0, ftol=1e-8)

class TestProbitCG(TestProbitNewton):
    def setup(self):
        if iswindows:
            raise SkipTest("fmin_cg sometimes fails to converge on windows")
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="cg",
            disp=0, maxiter=250)

class TestProbitNCG(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="ncg",
            disp=0, avextol=1e-8)

class TestLogitNewton(CheckModelResults, CheckMargEff):
    def __init__(self):
        from results.results_discrete import Spector
        data = sm.datasets.spector.load()
        data.exog = sm.add_constant(data.exog)
        self.data = data
        self.res1 = Logit(data.endog, data.exog).fit(method="newton", disp=0)
        res2 = Spector()
        res2.logit()
        self.res2 = res2

    def test_nodummy_exog1(self):
        assert_almost_equal(self.res1.margeff(atexog={0 : 2.0, 2 : 1.}),
                self.res2.margeff_nodummy_atexog1, DECIMAL_4)

    def test_nodummy_exog2(self):
        assert_almost_equal(self.res1.margeff(atexog={1 : 21., 2 : 0}, at='mean'),
                self.res2.margeff_nodummy_atexog2, DECIMAL_4)

class TestLogitBFGS(TestLogitNewton):
    def setup(self):
        self.res1 = Logit(self.data.endog, self.data.exog).fit(method="bfgs",
            disp=0)

class TestPoissonNewton(CheckModelResults):
    def __init__(self):
        from results.results_discrete import RandHIE
        data = sm.datasets.randhie.load()
        nobs = len(data.endog)
        exog = sm.add_constant(data.exog.view(float).reshape(nobs,-1))
        self.res1 = Poisson(data.endog, exog).fit(method='newton', disp=0)
        res2 = RandHIE()
        res2.poisson()
        self.res2 = res2

class TestMNLogitNewtonBaseZero(CheckModelResults):
    def __init__(self):
        from results.results_discrete import Anes
        data = sm.datasets.anes96.load()
        exog = data.exog
        exog[:,0] = np.log(exog[:,0] + .1)
        exog = np.column_stack((exog[:,0],exog[:,2],
            exog[:,5:8]))
        exog = sm.add_constant(exog)
        self.res1 = MNLogit(data.endog, exog).fit(method="newton", disp=0)
        res2 = Anes()
        res2.mnlogit_basezero()
        self.res2 = res2

    def test_j(self):
        assert_equal(self.res1.model.J, self.res2.J)

    def test_k(self):
        assert_equal(self.res1.model.K, self.res2.K)

if __name__ == "__main__":
    import nose
    nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb'],
            exit=False)
<commit_msg>test_discrete.py add object as class type<commit_after>"""
Tests for discrete models

Notes
-----
DECIMAL_3 is used because it seems that there is a loss of precision
in the Stata *.dta -> *.csv output, NOT the estimator for the Poisson
tests.
"""

import numpy as np
from numpy.testing import *
from scikits.statsmodels.discretemod import *
import scikits.statsmodels as sm
from sys import platform
from nose import SkipTest

DECIMAL_4 = 4
DECIMAL_3 = 3
DECIMAL_2 = 2
DECIMAL_1 = 1
DECIMAL_0 = 0
iswindows = 'win' in platform.lower()

class CheckModelResults(object):
    """
    res2 should be the test results from RModelWrap
    or the results as defined in model_results_data
    """
    def test_params(self):
        assert_almost_equal(self.res1.params, self.res2.params, DECIMAL_4)

    def test_conf_int(self):
        assert_almost_equal(self.res1.conf_int(), self.res2.conf_int, DECIMAL_4)

    def test_zstat(self):
        assert_almost_equal(self.res1.t(), self.res2.z, DECIMAL_4)

    def pvalues(self):
        assert_almost_equal(self.res1.pvalues, self.res2.pvalues, DECIMAL_4)

#    def test_cov_params(self):
#        assert_almost_equal(self.res1.cov_params(), self.res2.cov_params,
#                DECIMAL_4)

    def test_llf(self):
        assert_almost_equal(self.res1.llf, self.res2.llf, DECIMAL_4)

    def test_llnull(self):
        assert_almost_equal(self.res1.llnull, self.res2.llnull, DECIMAL_4)

    def test_llr(self):
        assert_almost_equal(self.res1.llr, self.res2.llr, DECIMAL_3)

    def test_llr_pvalue(self):
        assert_almost_equal(self.res1.llr_pvalue, self.res2.llr_pvalue,
                DECIMAL_4)

    def test_margeff(self):
        pass
    # this probably needs it's own test class?

    def test_normalized_cov_params(self):
        pass

    def test_bse(self):
        assert_almost_equal(self.res1.bse, self.res2.bse, DECIMAL_4)

    def test_dof(self):
        assert_equal(self.res1.df_model, self.res2.df_model)
        assert_equal(self.res1.df_resid, self.res2.df_resid)

    def test_aic(self):
        assert_almost_equal(self.res1.aic, self.res2.aic, DECIMAL_3)

    def test_bic(self):
        assert_almost_equal(self.res1.bic, self.res2.bic, DECIMAL_3)

class CheckMargEff(object):
    """
    Test marginal effects (margeff) and its options
    """

    def test_nodummy_dydxoverall(self):
        assert_almost_equal(self.res1.margeff(),
                self.res2.margeff_nodummy_dydx, DECIMAL_4)

    def test_nodummy_dydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean'),
                self.res2.margeff_nodummy_dydxmean, DECIMAL_4)

    def test_nodummy_dydxmedian(self):
        assert_almost_equal(self.res1.margeff(at='median'),
                self.res2.margeff_nodummy_dydxmedian, DECIMAL_4)

    def test_nodummy_dydxzero(self):
        assert_almost_equal(self.res1.margeff(at='zero'),
                self.res2.margeff_nodummy_dydxzero, DECIMAL_4)

    def test_nodummy_dyexoverall(self):
        assert_almost_equal(self.res1.margeff(method='dyex'),
                self.res2.margeff_nodummy_dyex, DECIMAL_4)

    def test_nodummy_dyexmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='dyex'),
                self.res2.margeff_nodummy_dyexmean, DECIMAL_4)

    def test_nodummy_dyexmedian(self):
        assert_almost_equal(self.res1.margeff(at='median', method='dyex'),
                self.res2.margeff_nodummy_dyexmedian, DECIMAL_4)

    def test_nodummy_dyexzero(self):
        assert_almost_equal(self.res1.margeff(at='zero', method='dyex'),
                self.res2.margeff_nodummy_dyexzero, DECIMAL_4)

    def test_nodummy_eydxoverall(self):
        assert_almost_equal(self.res1.margeff(method='eydx'),
                self.res2.margeff_nodummy_eydx, DECIMAL_4)

    def test_nodummy_eydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='eydx'),
                self.res2.margeff_nodummy_eydxmean, DECIMAL_4)

    def test_nodummy_eydxmedian(self):
        assert_almost_equal(self.res1.margeff(at='median', method='eydx'),
                self.res2.margeff_nodummy_eydxmedian, DECIMAL_4)

    def test_nodummy_eydxzero(self):
        assert_almost_equal(self.res1.margeff(at='zero', method='eydx'),
                self.res2.margeff_nodummy_eydxzero, DECIMAL_4)

    def test_nodummy_eyexoverall(self):
        assert_almost_equal(self.res1.margeff(method='eyex'),
                self.res2.margeff_nodummy_eyex, DECIMAL_4)

    def test_nodummy_eyexmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='eyex'),
                self.res2.margeff_nodummy_eyexmean, DECIMAL_4)

    def test_nodummy_eyexmedian(self):
        assert_almost_equal(self.res1.margeff(at='median', method='eyex'),
                self.res2.margeff_nodummy_eyexmedian, DECIMAL_4)

    def test_nodummy_eyexzero(self):
        assert_almost_equal(self.res1.margeff(at='zero', method='eyex'),
                self.res2.margeff_nodummy_eyexzero, DECIMAL_4)

    def test_dummy_dydxoverall(self):
        assert_almost_equal(self.res1.margeff(dummy=True),
                self.res2.margeff_dummy_dydx, DECIMAL_4)

    def test_dummy_dydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', dummy=True),
                self.res2.margeff_dummy_dydxmean, DECIMAL_4)

    @dec.knownfailureif(True, "The discrete change elasticity is not correct")
    def test_dummy_eydxoverall(self):
        assert_almost_equal(self.res1.margeff(method='eydx', dummy=True),
                self.res2.margeff_dummy_eydx, DECIMAL_4)

    @dec.knownfailureif(True, "The discrete change elasticity is not correct")
    def test_dummy_eydxmean(self):
        assert_almost_equal(self.res1.margeff(at='mean', method='eydx',
            dummy=True), self.res2.margeff_dummy_eydxmean, DECIMAL_4)

class TestProbitNewton(CheckModelResults):
    def __init__(self):
        from results.results_discrete import Spector
        data = sm.datasets.spector.load()
        data.exog = sm.add_constant(data.exog)
        self.data = data
        self.res1 = Probit(data.endog, data.exog).fit(method="newton", disp=0)
        res2 = Spector()
        res2.probit()
        self.res2 = res2

    def test_predict(self):
        assert_almost_equal(self.res1.model.predict(self.data.exog),
                self.res2.predict, DECIMAL_4)

    def test_resid(self):
        assert_almost_equal(self.res1.resid, self.res2.resid, DECIMAL_4)

class TestProbitBFGS(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="bfgs",
            disp=0)

class TestProbitNM(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="nm",
            disp=0, maxiter=500)

class TestProbitPowell(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="powell",
            disp=0, ftol=1e-8)

class TestProbitCG(TestProbitNewton):
    def setup(self):
        if iswindows:
            raise SkipTest("fmin_cg sometimes fails to converge on windows")
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="cg",
            disp=0, maxiter=250)

class TestProbitNCG(TestProbitNewton):
    def setup(self):
        self.res1 = Probit(self.data.endog, self.data.exog).fit(method="ncg",
            disp=0, avextol=1e-8)

class TestLogitNewton(CheckModelResults, CheckMargEff):
    def __init__(self):
        from results.results_discrete import Spector
        data = sm.datasets.spector.load()
        data.exog = sm.add_constant(data.exog)
        self.data = data
        self.res1 = Logit(data.endog, data.exog).fit(method="newton", disp=0)
        res2 = Spector()
        res2.logit()
        self.res2 = res2

    def test_nodummy_exog1(self):
        assert_almost_equal(self.res1.margeff(atexog={0 : 2.0, 2 : 1.}),
                self.res2.margeff_nodummy_atexog1, DECIMAL_4)

    def test_nodummy_exog2(self):
        assert_almost_equal(self.res1.margeff(atexog={1 : 21., 2 : 0}, at='mean'),
                self.res2.margeff_nodummy_atexog2, DECIMAL_4)

class TestLogitBFGS(TestLogitNewton):
    def setup(self):
        self.res1 = Logit(self.data.endog, self.data.exog).fit(method="bfgs",
            disp=0)

class TestPoissonNewton(CheckModelResults):
    def __init__(self):
        from results.results_discrete import RandHIE
        data = sm.datasets.randhie.load()
        nobs = len(data.endog)
        exog = sm.add_constant(data.exog.view(float).reshape(nobs,-1))
        self.res1 = Poisson(data.endog, exog).fit(method='newton', disp=0)
        res2 = RandHIE()
        res2.poisson()
        self.res2 = res2

class TestMNLogitNewtonBaseZero(CheckModelResults):
    def __init__(self):
        from results.results_discrete import Anes
        data = sm.datasets.anes96.load()
        exog = data.exog
        exog[:,0] = np.log(exog[:,0] + .1)
        exog = np.column_stack((exog[:,0],exog[:,2],
            exog[:,5:8]))
        exog = sm.add_constant(exog)
        self.res1 = MNLogit(data.endog, exog).fit(method="newton", disp=0)
        res2 = Anes()
        res2.mnlogit_basezero()
        self.res2 = res2

    def test_j(self):
        assert_equal(self.res1.model.J, self.res2.J)

    def test_k(self):
        assert_equal(self.res1.model.K, self.res2.K)

if __name__ == "__main__":
    import nose
    nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb'],
            exit=False)
<|endoftext|>


<commit_before>"""

File: harmonic_context.py

Purpose: Defines a tonality and chord that serves as a reference point for harmonic analysis of a section of music.

"""
from timemodel.duration import Duration
from timemodel.position import Position
from misc.interval import Interval

class HarmonicContext(object):
    """
    Class model for harmonic conext that references a chord and tonality.
    """

    def __init__(self, tonality, chord, duration, position=Position(0)):
        """
        Constructor.
        :param tonality: Tonality
        :param chord: Chord
        :param duration: Duration
        :param position: Position
        """
        self._tonality = tonality
        self._chord = chord
        self._duration = Duration(duration.duration)
        self._position = Position(position.position)

    @property
    def tonality(self):
        return self._tonality

    @property
    def chord(self):
        return self._chord

    @property
    def duration(self):
        return self._duration

    @duration.setter
    def duration(self, new_duration):
        self._duration = new_duration

    @property
    def position(self):
        return self._position

    @position.setter
    def position(self, new_position):
        self._position = new_position

    @property
    def extent(self):
        return Interval(self.position.position, self.position.position + self.duration.duration)

    def is_equal(self, other):
        if not other or not isinstance(other, HarmonicContext):
            return False

        if str(self.tonality) != str(other.tonality) or \
                str(self.chord) != str(other.chord) or self.duration != other.duration:
            return False

        return True

    def __str__(self):
        return 'h.c.[{0}, {1}, {2}]'.format(self.tonality, self.chord, self.duration)
<commit_msg>add is_same_harmony() method.<commit_after>"""

File: harmonic_context.py

Purpose: Defines a tonality and chord that serves as a reference point for harmonic analysis of a section of music.

"""
from timemodel.duration import Duration
from timemodel.position import Position
from misc.interval import Interval

class HarmonicContext(object):
    """
    Class model for harmonic conext that references a chord and tonality.
    """

    def __init__(self, tonality, chord, duration, position=Position(0)):
        """
        Constructor.
        :param tonality: Tonality
        :param chord: Chord
        :param duration: Duration
        :param position: Position
        """
        self._tonality = tonality
        self._chord = chord
        self._duration = Duration(duration.duration)
        self._position = Position(position.position)

    @property
    def tonality(self):
        return self._tonality

    @property
    def chord(self):
        return self._chord

    @property
    def duration(self):
        return self._duration

    @duration.setter
    def duration(self, new_duration):
        self._duration = new_duration

    @property
    def position(self):
        return self._position

    @position.setter
    def position(self, new_position):
        self._position = new_position

    @property
    def extent(self):
        return Interval(self.position.position, self.position.position + self.duration.duration)

    def is_equal(self, other):
        if not other or not isinstance(other, HarmonicContext):
            return False

        if str(self.tonality) != str(other.tonality) or \
                str(self.chord) != str(other.chord) or self.duration != other.duration:
            return False

        return True

    def is_same_harmony(self, other):
        if not other or not isinstance(other, HarmonicContext):
            return False

        if str(self.tonality) != str(other.tonality) or str(self.chord) != str(other.chord):
            return False

        return True

    def __str__(self):
        return 'h.c.[{0}, {1}, {2}]'.format(self.tonality, self.chord, self.duration)
<|endoftext|>


<commit_before>#!/usr/bin/env pytnon3

import xml.etree.ElementTree as etree
import sys
import re

exclude_interface = ["wl_registry", "wl_resource"]

header_preamble = """// Generated by create_interface.py
#pragma once

#include <wayland-server.h>

#include "client.h"
#include "resource_ref.h"
#include "impl_interface.h"
#include "array.h"
"""

header_body = """
namespace karuta {{
namespace protocol {{
{interface_define}
}}
}}
"""

source_preamble = """// Generated by create_interface.py
#include "{0}"
"""

source_body = """
namespace karuta {{
namespace protocol {{
{interface_instance}
}}
}}
"""

class_format = """
class {classname} : public karuta::ImplInterface {{
private:
{member_funcs}
public:
{member_event_funcs}
{static_funcs}
{get_interface}
{get_wl_interface}
{version}
}};
"""

static_function = """
    static void {reqname}_(
        struct wl_client* client,
        struct wl_resource* resource{args}) {{

        Client client_(client);
        ResourceRef resource_(resource);{to_class}

        auto p = static_cast<{classname}*>(wl_resource_get_user_data(resource));
        p->{reqname}(client_, resource_ {call_args});
    }}"""

def usage():
    print("""
usage: create_interface.py input_file output_prefix
""")

type_map = {
    "uint": "uint32_t",
    "string": "const char *",
    "fd": "int32_t",
    "int": "int32_t",
    "new_id": "uint32_t"
}

acceptable_interface = ["wl_client", "wl_resource"]

def to_c_type(arg):
    t = type_map.get(arg.attrib['type'], None)
    if t: return t
    if (arg.attrib['type'] == 'object'):
        if arg.attrib['interface'] not in acceptable_interface:
            return 'struct wl_resource *'
        return 'struct ' + arg.attrib['interface'] + ' *'

def to_cpp_type(arg):
    t = type_map.get(arg.attrib['type'], None)
    if t: return t
    if (arg.attrib['type'] == 'object'):
        return 'ResourceRef&'

send_type_name = {
    "uint": "uint32_t",
    "string": "const char *",
    "fd": "int32_t",
    "int": "int32_t",
    "fixed": "int32_t", # FIXME:
}

def to_send_cpp_type(arg):
    t = send_type_name.get(arg.attrib['type'], None)
    if t: return t
    if arg.attrib['type'] == 'object':
        return 'ResourceRef&'
    if arg.attrib['type'] == 'array':
        return 'ArrayRef&'
    if arg.attrib['type'] == 'new_id':
        return 'ResourceRef&'

    print("Unknown type: " + arg.attrib['type'])

def conv_arg_for_send(arg):
    t = send_type_name.get(arg.attrib['type'], None)
    if t: return arg.attrib['name']
    if arg.attrib['type'] == 'object':
        return arg.attrib['name'] + '.get_wl_resource()'
    if arg.attrib['type'] == 'array':
        return arg.attrib['name'] + '.get_wl_array()'
    if arg.attrib['type'] == 'new_id':
        return arg.attrib['name'] + '.get_wl_resource()'

    print("Unknown type: " + arg.attrib['type'])

def to_class_name(name):
    return ''.join(map(lambda s: s.title(), name.split('_')))

def to_member_funcs(reqs):
    return ''.join(['\n' + to_member_func(*req) for req in reqs])

def to_member_func(name, args):
    s = '    virtual void ' + name + '(Client& client, ResourceRef& resource'
    s += ''.join([',\n        ' + to_cpp_type(arg) + ' ' + arg.attrib['name'] for arg in args])
    s += ') = 0;\n'
    return s

def to_member_event_funcs(ifname, evs):
    return ''.join(['\n' + to_member_event_func(ifname, name, args)
                    for (name, args) in evs])

def to_member_event_func(ifname, name, args):
    s = '    static void send_' + name + '(ResourceRef& resource_'
    s += ''.join([',\n        ' + to_send_cpp_type(arg) + ' ' + arg.attrib['name'] for arg in args])
    s += ') {\n'
    s += '        {}_send_{}(resource_.get_wl_resource()'.format(ifname, name)
    s += ''.join([', ' + conv_arg_for_send(arg) for arg in args])
    s += ');\n'
    s += '    }\n'
    return s

def to_static_funcs(ifname, reqs):
    return ''.join(['\n' + to_static_func(ifname, *req) for req in reqs])

def to_static_func(ifname, name, args):
    classname = to_class_name(ifname)

    args_str = ''.join([',\n        ' + to_c_type(arg) + ' ' + arg.attrib['name'] for arg in args])

    to_class = ''
    for arg in args:
        if arg.attrib['type'] == 'object' and arg.attrib['interface'] not in acceptable_interface:
            to_class += '\n        ResourceRef {0}_({0});'.format(arg.attrib['name'])

    def to_arg_name(arg):
        if arg.attrib['type'] == 'object' and arg.attrib['interface'] not in acceptable_interface:
            return arg.attrib['name'] + '_'
        else:
            return arg.attrib['name']

    call_args = ''.join([' ,' + to_arg_name(arg) for arg in args])

    return static_function.format(reqname=name,
                                  args=args_str,
                                  classname=classname,
                                  to_class=to_class,
                                  call_args=call_args)

def parse_request(req):
    return (req.attrib['name'], [child for child in req if child.tag == 'arg'])

def parse_event(ev):
    return (ev.attrib['name'], [child for child in ev if child.tag == 'arg'])

def parse_interface(intf):
    name = intf.attrib['name']
    version = intf.attrib.get('version', 0)
    reqs = [parse_request(child) for child in intf if child.tag == 'request']
    evs = [parse_event(child) for child in intf
           if child.tag == 'event' and child.attrib['name'] != 'error' and child.attrib['name'] != 'delete_id']
    return (name, version, reqs, evs)

def create_interface_instance(name, version, reqs, _):
    if len(reqs) == 0: return ""
    s = 'struct {ifname}_interface {ifname}_interface_instance = {{'.format(ifname=name)
    for (funcname, args) in reqs:
        s += '\n    &{classname}::{funcname}_,'.format(classname=to_class_name(name), funcname=funcname)
    s += '\n};'
    return s

def to_get_interface(name):
    return """\
    void* get_interface() override {{
        extern struct {name}_interface {name}_interface_instance;
        return static_cast<void*>(&{name}_interface_instance);
    }}""".format(name=name)

def to_get_wl_interface(name):
    return """\
    static const struct wl_interface* get_wl_interface() {{
        extern const struct wl_interface {name}_interface;
        return &::{name}_interface;
    }}""".format(name=name)

def to_version(ver):
    return """\
    static const uint32_t version = {version};
    """.format(version=ver)

def create_interface(ns, intf):
    (name, version, reqs, evs) = intf
    s = ""
    s += class_format.format(classname=to_class_name(name),
                             member_funcs=to_member_funcs(reqs),
                             member_event_funcs=to_member_event_funcs(name, evs),
                             static_funcs=to_static_funcs(name, reqs),
                             get_interface="" if len(reqs) == 0 else to_get_interface(name),
                             get_wl_interface=to_get_wl_interface(name),
                             version=to_version(version)
    )
    return s

def main():
    if len(sys.argv) < 2:
        usage()
        sys.exit(1)

    from os.path import basename, splitext
    tree = etree.parse(sys.argv[1])
    root = tree.getroot()

    #proto_name = root.attrib['name']
    proto_name = splitext(basename(sys.argv[1]))[0]
    header_name = proto_name + '_karuta_server.h'
    header_file = open(header_name, 'w')
    source_file = open(proto_name + '_karuta_server.cpp', 'w')

    header_str = ""
    source_str = ""

    print(header_preamble, file=header_file)
    print("#include \"" + proto_name + "-server-protocol.h\"", file=header_file)

    for child in root:
        if child.tag == 'interface' and child.attrib['name'] not in exclude_interface:
            interface = parse_interface(child)
            print(header_body.format(interface_define=create_interface(proto_name, interface)),
                  file=header_file)

    print(source_preamble.format(header_name), file=source_file)

    for child in root:
        if child.tag == 'interface' and child.attrib['name'] not in exclude_interface:
            interface = parse_interface(child)

            print(source_body.format(namespace=proto_name,
                                     interface_instance=create_interface_instance(*interface)),
                  file=source_file)

if __name__ == '__main__':
    main()
<commit_msg>create_interface.py: Add enum parser.<commit_after>#!/usr/bin/env pytnon3

import xml.etree.ElementTree as etree
import sys
import re

exclude_interface = ["wl_registry", "wl_resource"]

header_preamble = """// Generated by create_interface.py
#pragma once

#include <wayland-server.h>

#include "client.h"
#include "resource_ref.h"
#include "impl_interface.h"
#include "array.h"
"""

header_body = """
namespace karuta {{
namespace protocol {{
{interface_define}
}}
}}
"""

source_preamble = """// Generated by create_interface.py
#include "{0}"
"""

source_body = """
namespace karuta {{
namespace protocol {{
{interface_instance}
}}
}}
"""

class_format = """
class {classname} : public karuta::ImplInterface {{
private:
{member_funcs}
public:
{enums}
{member_event_funcs}
{static_funcs}
{get_interface}
{get_wl_interface}
{version}
}};
"""

static_function = """
    static void {reqname}_(
        struct wl_client* client,
        struct wl_resource* resource{args}) {{

        Client client_(client);
        ResourceRef resource_(resource);{to_class}

        auto p = static_cast<{classname}*>(wl_resource_get_user_data(resource));
        p->{reqname}(client_, resource_ {call_args});
    }}"""

def usage():
    print("""
usage: create_interface.py input_file output_prefix
""")

type_map = {
    "uint": "uint32_t",
    "string": "const char *",
    "fd": "int32_t",
    "int": "int32_t",
    "new_id": "uint32_t"
}

acceptable_interface = ["wl_client", "wl_resource"]

def to_c_type(arg):
    t = type_map.get(arg.attrib['type'], None)
    if t: return t
    if (arg.attrib['type'] == 'object'):
        if arg.attrib['interface'] not in acceptable_interface:
            return 'struct wl_resource *'
        return 'struct ' + arg.attrib['interface'] + ' *'

def to_cpp_type(arg):
    t = type_map.get(arg.attrib['type'], None)
    if t: return t
    if (arg.attrib['type'] == 'object'):
        return 'ResourceRef&'

send_type_name = {
    "uint": "uint32_t",
    "string": "const char *",
    "fd": "int32_t",
    "int": "int32_t",
    "fixed": "int32_t", # FIXME:
}

def to_send_cpp_type(arg):
    t = send_type_name.get(arg.attrib['type'], None)
    if t: return t
    if arg.attrib['type'] == 'object':
        return 'ResourceRef&'
    if arg.attrib['type'] == 'array':
        return 'ArrayRef&'
    if arg.attrib['type'] == 'new_id':
        return 'ResourceRef&'

    print("Unknown type: " + arg.attrib['type'])

def conv_arg_for_send(arg):
    t = send_type_name.get(arg.attrib['type'], None)
    if t: return arg.attrib['name']
    if arg.attrib['type'] == 'object':
        return arg.attrib['name'] + '.get_wl_resource()'
    if arg.attrib['type'] == 'array':
        return arg.attrib['name'] + '.get_wl_array()'
    if arg.attrib['type'] == 'new_id':
        return arg.attrib['name'] + '.get_wl_resource()'

    print("Unknown type: " + arg.attrib['type'])

def to_class_name(name):
    return ''.join(map(lambda s: s.title(), name.split('_')))

def to_member_funcs(reqs):
    return ''.join(['\n' + to_member_func(*req) for req in reqs])

def to_member_func(name, args):
    s = '    virtual void ' + name + '(Client& client, ResourceRef& resource'
    s += ''.join([',\n        ' + to_cpp_type(arg) + ' ' + arg.attrib['name'] for arg in args])
    s += ') = 0;\n'
    return s

def to_enum_defs(enums):
    return ''.join(['\n' + to_enum_def(*enum) for enum in enums])

def to_enum_def(name, entries):
    s = '    enum {} {{'.format(name.title())
    s += ''.join(['\n        {}_{} = {},'.format(name.title(), entry.attrib['name'], entry.attrib['value'])
                  for entry in entries])
    s += '\n    };\n'
    return s

def to_member_event_funcs(ifname, evs):
    return ''.join(['\n' + to_member_event_func(ifname, name, args)
                    for (name, args) in evs])

def to_member_event_func(ifname, name, args):
    s = '    static void send_' + name + '(ResourceRef& resource_'
    s += ''.join([',\n        ' + to_send_cpp_type(arg) + ' ' + arg.attrib['name'] for arg in args])
    s += ') {\n'
    s += '        {}_send_{}(resource_.get_wl_resource()'.format(ifname, name)
    s += ''.join([', ' + conv_arg_for_send(arg) for arg in args])
    s += ');\n'
    s += '    }\n'
    return s

def to_static_funcs(ifname, reqs):
    return ''.join(['\n' + to_static_func(ifname, *req) for req in reqs])

def to_static_func(ifname, name, args):
    classname = to_class_name(ifname)

    args_str = ''.join([',\n        ' + to_c_type(arg) + ' ' + arg.attrib['name'] for arg in args])

    to_class = ''
    for arg in args:
        if arg.attrib['type'] == 'object' and arg.attrib['interface'] not in acceptable_interface:
            to_class += '\n        ResourceRef {0}_({0});'.format(arg.attrib['name'])

    def to_arg_name(arg):
        if arg.attrib['type'] == 'object' and arg.attrib['interface'] not in acceptable_interface:
            return arg.attrib['name'] + '_'
        else:
            return arg.attrib['name']

    call_args = ''.join([' ,' + to_arg_name(arg) for arg in args])

    return static_function.format(reqname=name,
                                  args=args_str,
                                  classname=classname,
                                  to_class=to_class,
                                  call_args=call_args)

def parse_request(req):
    return (req.attrib['name'], [child for child in req if child.tag == 'arg'])

def parse_event(ev):
    return (ev.attrib['name'], [child for child in ev if child.tag == 'arg'])

def parse_enum(enum):
    return (enum.attrib['name'], [child for child in enum if child.tag == 'entry'])

def parse_interface(intf):
    name = intf.attrib['name']
    version = intf.attrib.get('version', 0)
    reqs = [parse_request(child) for child in intf if child.tag == 'request']
    evs = [parse_event(child) for child in intf
           if child.tag == 'event' and child.attrib['name'] != 'error' and child.attrib['name'] != 'delete_id']
    enums = [parse_enum(child) for child in intf if child.tag == 'enum']
    return (name, version, reqs, evs, enums)

def create_interface_instance(name, version, reqs, _evs, _enums):
    if len(reqs) == 0: return ""
    s = 'struct {ifname}_interface {ifname}_interface_instance = {{'.format(ifname=name)
    for (funcname, args) in reqs:
        s += '\n    &{classname}::{funcname}_,'.format(classname=to_class_name(name), funcname=funcname)
    s += '\n};'
    return s

def to_get_interface(name):
    return """\
    void* get_interface() override {{
        extern struct {name}_interface {name}_interface_instance;
        return static_cast<void*>(&{name}_interface_instance);
    }}""".format(name=name)

def to_get_wl_interface(name):
    return """\
    static const struct wl_interface* get_wl_interface() {{
        extern const struct wl_interface {name}_interface;
        return &::{name}_interface;
    }}""".format(name=name)

def to_version(ver):
    return """\
    static const uint32_t version = {version};
    """.format(version=ver)

def create_interface(ns, intf):
    (name, version, reqs, evs, enums) = intf
    s = ""
    s += class_format.format(classname          = to_class_name(name),
                             member_funcs       = to_member_funcs(reqs),
                             enums              = to_enum_defs(enums),
                             member_event_funcs = to_member_event_funcs(name, evs),
                             static_funcs       = to_static_funcs(name, reqs),
                             get_interface      = "" if len(reqs) == 0 else to_get_interface(name),
                             get_wl_interface   = to_get_wl_interface(name),
                             version            = to_version(version)
    )
    return s

def main():
    if len(sys.argv) < 2:
        usage()
        sys.exit(1)

    from os.path import basename, splitext
    tree = etree.parse(sys.argv[1])
    root = tree.getroot()

    #proto_name = root.attrib['name']
    proto_name = splitext(basename(sys.argv[1]))[0]
    header_name = proto_name + '_karuta_server.h'
    header_file = open(header_name, 'w')
    source_file = open(proto_name + '_karuta_server.cpp', 'w')

    header_str = ""
    source_str = ""

    print(header_preamble, file=header_file)
    print("#include \"" + proto_name + "-server-protocol.h\"", file=header_file)

    for child in root:
        if child.tag == 'interface' and child.attrib['name'] not in exclude_interface:
            interface = parse_interface(child)
            print(header_body.format(interface_define=create_interface(proto_name, interface)),
                  file=header_file)

    print(source_preamble.format(header_name), file=source_file)

    for child in root:
        if child.tag == 'interface' and child.attrib['name'] not in exclude_interface:
            interface = parse_interface(child)

            print(source_body.format(namespace=proto_name,
                                     interface_instance=create_interface_instance(*interface)),
                  file=source_file)

if __name__ == '__main__':
    main()
<|endoftext|>