<commit_before>'''
ExpSettingsValidator

Created on April 17, 2015

Original Author: Brian Donovan

Copyright 2015 Raytheon BBN Technologies

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

import h5py
import Libraries
import QGL.Channels

channels = None
instruments = None
measurements = None
sweeps = None

channels = Libraries.channelLib.channelDict
instruments = Libraries.instrumentLib.instrDict
measurements = Libraries.measLib.filterDict
sweeps = Libraries.sweepLib.sweepDict

def is_logicalmarker_channel(name):
	return is_channel_type(name, QGL.Channels.LogicalMarkerChannel)

def is_physicalmarker_channel(name):
	return is_channel_type(name, QGL.Channels.PhysicalMarkerChannel)

def is_qubit_channel(name):
	return is_channel_type(name, QGL.Channels.Qubit)

def is_measurement_channel(name):
	return is_channel_type(name, QGL.Channels.Measurement)

def requires_physical_channel(name):
	return (is_channel_type(name, QGL.Channels.Qubit) or
	        is_channel_type(name, QGL.Channels.LogicalMarkerChannel) or
	        is_channel_type(name, QGL.Channels.Measurement))

def is_channel_type(name, channelType):
	channels = Libraries.channelLib.channelDict
	return isinstance(channels[name], channelType)

def test_logical_channels():
	errors = []
	channels = Libraries.channelLib.channelDict
	logicalChannels = [channelName for channelName in channels.keys() if is_logicalmarker_channel(channelName)]

	for channel in logicalChannels:
		if not is_logicalmarker_channel(channel):
			continue
		errorHeader = 'LogicalMarkerChannel "{0}" requires a Physical Marker Channel'.format(channel)
		if channels[channel].physChan is not None:
			physicalChannelName = channels[channel].physChan.label
			if physicalChannelName not in channels.keys():
				print errorHeader
				print '\tPhysical Channel "{0}" not found'.format(physicalChannelName)
				errors.append(physicalChannelName)
			elif not is_physicalmarker_channel(physicalChannelName):
				print channels[channel].physChan
				print '\tChannel "{0}" is not a Physical Marker Channel'.format(physicalChannelName)
				errors.append(physicalChannelName)
	return errors

def test_physical_channels():
	errors = []
	channels = Libraries.channelLib.channelDict
	physicalChannels = [channelName for channelName in channels.keys() if is_physicalmarker_channel(channelName)]

	for channel in physicalChannels:
		awg = channels[channel].AWG.label
		if awg == '':
			print 'Physical Channel "{0}" requires an AWG assignment'.format(channel)
			errors.append(channel)
		elif awg not in instruments.keys():
			print 'Physical Channel "{0}" AWG {1} not found'.format(channel, awg)
			errors.append(channel)

		# test AWG name to channel format
		validName = True
		validName &= '-' in channel
		if validName:
			awgName, awgChan = channel.split('-')
			if awgName not in instruments.keys():
				print 'Physical Channel "{0}" Label format is invalid. It should be Name-Channel'.format(channel)
				errors.append(channel)
			if awgName != awg:
				print 'Physical Channel "{0}" Label AWGName {1} != AWG.label {2}'.format(channel, awgName, awg)
				errors.append(channel)
		else:
			print 'Physical Channel "{0}" Label format is invalid. It should be Name-Channel'.format(channel)
			errors.append(channel)

	return errors

def test_require_physical():
	errors = []
	channels = Libraries.channelLib.channelDict
	testChannels = [channelName for channelName in channels.keys() if requires_physical_channel(channelName)]

	for channel in testChannels:
		physicalChannel = channels[channel].physChan
		if physicalChannel is None:
			print '"{0}" channel "{1}" Physical Channel is not defined'.format(channels[channel].__class__.__name__, channel)
			errors.append(channel)

	return errors

def test_measurement_channels():
	errors = []
	channels = Libraries.channelLib.channelDict
	measurementChannels = [channelName for channelName in channels.keys() if is_measurement_channel(channelName)]

	for channel in measurementChannels:
		physicalChannel = channels[channel].physChan
		if physicalChannel is None:
			print 'Measurement channel "{0}" Physical Channel is not defined'.format(channel)
			errors.append(channel)

	return errors

def lint_channelLib():
	errors = []
	if 'digitizerTrig' not in channels.keys():
		print 'A LogicalMarkerChannel named digitizerTrig is required'
		errors.append('digitizerTrig')

	# test gate pulses

	if 'slaveTrig' not in channels.keys():
		print 'A LogicalMarkerChannel named slaveTrig is required'
		errors.append('slaveTrig')

	# test map_logical_to_physical
	rp_errors = test_require_physical()
	pc_errors = test_physical_channels()
	lc_errors = test_logical_channels()

	if pc_errors != []:
		errors.append(pc_errors)
	if lc_errors != []:
		errors.append(lc_errors)
	if rp_errors != []:
		errors.append(rp_errors)

	print errors
	return errors

def validate_lib():
	if lint_channelLib() != []:
		return False
	return True

def default_repr(items, item):
	return '\t{0}: {1}'.format(item,
							items[item].__class__.__name__)

def default_list_repr(items, name):
	print 'Listing available {0}:'.format(name)
	for item in items.keys():
		print default_repr(items,item)

def list_channels():
	print 'Listing available channels:'
	for channel in channels.keys():
		print '\t', repr(channels[channel])

def list_instruments():
	default_list_repr(instruments, 'instruments')

def list_measurements():
	default_list_repr(measurements, 'measurements')

def list_sweeps():
	default_list_repr(sweeps, 'sweeps')

def list_config():
	list_channels()
	print
	list_instruments()
	print
	list_measurements()
	print
	list_sweeps()

if __name__ == '__main__':
	list_config()
	validate_lib()
<commit_msg>Improved Doc Strings<commit_after>'''
ExpSettingsVal -
Validates Experimental Settings against a set of rules known to cause
the Compiler (Compiler.py) to fail if they are not followed

Created on April 17, 2015

Original Author: Brian Donovan

Copyright 2015 Raytheon BBN Technologies

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

import h5py
import Libraries
import QGL.Channels

channels = None
instruments = None
measurements = None
sweeps = None

channels = Libraries.channelLib.channelDict
instruments = Libraries.instrumentLib.instrDict
measurements = Libraries.measLib.filterDict
sweeps = Libraries.sweepLib.sweepDict

## Helper functions for list comprehension
def is_logicalmarker_channel(name):
	return is_channel_type(name, QGL.Channels.LogicalMarkerChannel)

def is_physicalmarker_channel(name):
	return is_channel_type(name, QGL.Channels.PhysicalMarkerChannel)

def is_qubit_channel(name):
	return is_channel_type(name, QGL.Channels.Qubit)

def is_measurement_channel(name):
	return is_channel_type(name, QGL.Channels.Measurement)

def requires_physical_channel(name):
	return (is_channel_type(name, QGL.Channels.Qubit) or
	        is_channel_type(name, QGL.Channels.LogicalMarkerChannel) or
	        is_channel_type(name, QGL.Channels.Measurement))

def is_channel_type(name, channelType):
	channels = Libraries.channelLib.channelDict
	return isinstance(channels[name], channelType)

### Apply global rules

def test_require_physical():
	"""Enforces rule requiring physical channels for certain logical channels

	   See requires_physical_channel() for list of Channel types requiring a
	   Physical channel.
	"""
	errors = []
	channels = Libraries.channelLib.channelDict
	testChannels = [channelName for channelName in channels.keys() if requires_physical_channel(channelName)]

	for channel in testChannels:
		physicalChannel = channels[channel].physChan

		if physicalChannel is None:
			print '"{0}" channel "{1}" Physical Channel is not defined'.format(channels[channel].__class__.__name__, channel)
			errors.append(channel)

	return errors

## Apply invidual test based on channel type
def test_logical_channels():
	"""
		Enforces rules applied against logical channels

		These are rules in addition to those applied at the global level.

		Rules:
		PhysicalChannel but be in library
		PhysicalChannel class must be PhysicalMarkerChannel
	"""
	errors = []
	channels = Libraries.channelLib.channelDict
	logicalChannels = [channelName for channelName in channels.keys() if is_logicalmarker_channel(channelName)]

	for channel in logicalChannels:
		if not is_logicalmarker_channel(channel):
			continue
		errorHeader = 'LogicalMarkerChannel "{0}" requires a Physical Marker Channel'.format(channel)
		if channels[channel].physChan is not None:
			physicalChannelName = channels[channel].physChan.label
			if physicalChannelName not in channels.keys():
				print errorHeader
				print '\tPhysical Channel "{0}" not found'.format(physicalChannelName)
				errors.append(physicalChannelName)
			elif not is_physicalmarker_channel(physicalChannelName):
				print channels[channel].physChan
				print '\tChannel "{0}" is not a Physical Marker Channel'.format(physicalChannelName)
				errors.append(physicalChannelName)
	return errors

def test_physical_channels():
	"""
		Enforces rules applied against physical channels

		Rules:
		PhysicalChannel must have an AWG assigned
		The assigned AWG must exist in the library
		The name of the PhysicalChannel channel must be of the form AWGName-AWGChannel
	"""
	errors = []
	channels = Libraries.channelLib.channelDict
	physicalChannels = [channelName for channelName in channels.keys() if is_physicalmarker_channel(channelName)]

	for channel in physicalChannels:
		awg = channels[channel].AWG.label
		if awg == '':
			print 'Physical Channel "{0}" requires an AWG assignment'.format(channel)
			errors.append(channel)
		elif awg not in instruments.keys():
			print 'Physical Channel "{0}" AWG {1} not found'.format(channel, awg)
			errors.append(channel)

		# test AWG name to channel format
		validName = True
		validName &= '-' in channel
		if validName:
			awgName, awgChan = channel.split('-')
			if awgName not in instruments.keys():
				print 'Physical Channel "{0}" Label format is invalid. It should be Name-Channel'.format(channel)
				errors.append(channel)
			if awgName != awg:
				print 'Physical Channel "{0}" Label AWGName {1} != AWG.label {2}'.format(channel, awgName, awg)
				errors.append(channel)
		else:
			print 'Physical Channel "{0}" Label format is invalid. It should be Name-Channel'.format(channel)
			errors.append(channel)

	return errors

def validate_channelLib():
	errors = []
	if 'digitizerTrig' not in channels.keys():
		print 'A LogicalMarkerChannel named digitizerTrig is required'
		errors.append('digitizerTrig')

	# test gate pulses

	if 'slaveTrig' not in channels.keys():
		print 'A LogicalMarkerChannel named slaveTrig is required'
		errors.append('slaveTrig')

	# test map_logical_to_physical
	rp_errors = test_require_physical()
	pc_errors = test_physical_channels()
	lc_errors = test_logical_channels()

	if pc_errors != []:
		errors.append(pc_errors)
	if lc_errors != []:
		errors.append(lc_errors)
	if rp_errors != []:
		errors.append(rp_errors)

	print errors
	return errors

def validate_lib():
	if validate_channelLib() != []:
		return False
	return True

def default_repr(items, item):
	return '\t{0}: {1}'.format(item,
							items[item].__class__.__name__)

def default_list_repr(items, name):
	print 'Listing available {0}:'.format(name)
	for item in items.keys():
		print default_repr(items,item)

def list_channels():
	print 'Listing available channels:'
	for channel in channels.keys():
		print '\t', repr(channels[channel])

def list_instruments():
	default_list_repr(instruments, 'instruments')

def list_measurements():
	default_list_repr(measurements, 'measurements')

def list_sweeps():
	default_list_repr(sweeps, 'sweeps')

def list_config():
	list_channels()
	print
	list_instruments()
	print
	list_measurements()
	print
	list_sweeps()

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


<commit_before>#!/usr/bin/env python3.5
# coding: utf-8
import sys
from os.path import dirname, join, realpath
from siebenapp.goaltree import Goals
from siebenapp.system import save, load, dot_export
from subprocess import run
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import (
    QApplication,
    QDockWidget,
    QLabel,
    QLineEdit,
    QMainWindow,
    QScrollArea,
    QSizePolicy
)
from PyQt5.uic import loadUi

class SiebenApp(QMainWindow):
    refresh = pyqtSignal()
    quit_app = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.refresh.connect(self.reload_image)
        self.quit_app.connect(QApplication.instance().quit)
        self.view  = 'open'
        self.goals = load()
        self.first_run = True

    def setup(self):
        self.action_About.triggered.connect(lambda: self.about.show())
        self.refresh.emit()

    def reload_image(self):
        if not self.goals.events and not self.first_run:
            return
        self.first_run = False
        save(self.goals)
        with open('work.dot', 'w') as f:
            f.write(dot_export(self.goals, self.view))
        run(['dot', '-Tpng', '-o', 'work.png', 'work.dot'])
        img = QImage('work.png')
        self.label.setPixmap(QPixmap.fromImage(img))
        self.label.resize(img.size().width(), img.size().height())

    def keyPressEvent(self, event):
        key_handlers = {
            Qt.Key_1: lambda: self.select_number(1),
            Qt.Key_2: lambda: self.select_number(2),
            Qt.Key_3: lambda: self.select_number(3),
            Qt.Key_4: lambda: self.select_number(4),
            Qt.Key_5: lambda: self.select_number(5),
            Qt.Key_6: lambda: self.select_number(6),
            Qt.Key_7: lambda: self.select_number(7),
            Qt.Key_8: lambda: self.select_number(8),
            Qt.Key_9: lambda: self.select_number(9),
            Qt.Key_0: lambda: self.select_number(0),
            Qt.Key_A: self.start_edit(self.goals.add, 'Add new goal'),
            Qt.Key_C: self.with_refresh(self.goals.toggle_close),
            Qt.Key_D: self.with_refresh(self.goals.delete),
            Qt.Key_I: self.start_edit(self.goals.insert, 'Insert new goal'),
            Qt.Key_L: self.with_refresh(self.goals.toggle_link),
            Qt.Key_Q: self.quit_app.emit,
            Qt.Key_R: self.start_edit(self.goals.rename, 'Rename goal'),
            Qt.Key_S: self.with_refresh(self.goals.swap_goals),
            Qt.Key_V: self.toggle_view,
            Qt.Key_Space: self.with_refresh(self.goals.hold_select),
        }
        if event.key() in key_handlers:
            key_handlers[event.key()]()
        else:
            super().keyPressEvent(event)

    def start_edit(self, fn, dock_label):
        def inner():
            self.dockWidget.setWindowTitle(dock_label)
            self.input.setEnabled(True)
            self.input.setFocus(True)
            self.input.returnPressed.connect(self.finish_edit(fn))
        return inner

    def finish_edit(self, fn):
        def inner():
            self.dockWidget.setWindowTitle('')
            self.input.returnPressed.disconnect()
            fn(self.input.text())
            self.input.setEnabled(False)
            self.input.setText('')
            self.refresh.emit()
        return inner

    def with_refresh(self, fn):
        def inner():
            fn()
            self.refresh.emit()
        return inner

    def select_number(self, num):
        self.goals.select(num)
        self.refresh.emit()

    def toggle_view(self):
        next_view = {
            'full': 'open',
            'open': 'top',
            'top': 'full',
        }
        self.view = next_view[self.view]
        self.refresh.emit()

def main(root_script):
    app = QApplication(sys.argv)
    root = dirname(realpath(root_script))
    w = loadUi(join(root, 'ui', 'main.ui'), SiebenApp())
    w.about = loadUi(join(root, 'ui', 'about.ui'))
    w.setup()
    w.showMaximized()
    sys.exit(app.exec_())
<commit_msg>Fix: always refresh image after view change<commit_after>#!/usr/bin/env python3.5
# coding: utf-8
import sys
from os.path import dirname, join, realpath
from siebenapp.goaltree import Goals
from siebenapp.system import save, load, dot_export
from subprocess import run
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import (
    QApplication,
    QDockWidget,
    QLabel,
    QLineEdit,
    QMainWindow,
    QScrollArea,
    QSizePolicy
)
from PyQt5.uic import loadUi

class SiebenApp(QMainWindow):
    refresh = pyqtSignal()
    quit_app = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.refresh.connect(self.reload_image)
        self.quit_app.connect(QApplication.instance().quit)
        self.view  = 'open'
        self.goals = load()
        self.force_refresh = True

    def setup(self):
        self.action_About.triggered.connect(lambda: self.about.show())
        self.refresh.emit()

    def reload_image(self):
        if not self.goals.events and not self.force_refresh:
            return
        self.force_refresh = False
        save(self.goals)
        with open('work.dot', 'w') as f:
            f.write(dot_export(self.goals, self.view))
        run(['dot', '-Tpng', '-o', 'work.png', 'work.dot'])
        img = QImage('work.png')
        self.label.setPixmap(QPixmap.fromImage(img))
        self.label.resize(img.size().width(), img.size().height())

    def keyPressEvent(self, event):
        key_handlers = {
            Qt.Key_1: lambda: self.select_number(1),
            Qt.Key_2: lambda: self.select_number(2),
            Qt.Key_3: lambda: self.select_number(3),
            Qt.Key_4: lambda: self.select_number(4),
            Qt.Key_5: lambda: self.select_number(5),
            Qt.Key_6: lambda: self.select_number(6),
            Qt.Key_7: lambda: self.select_number(7),
            Qt.Key_8: lambda: self.select_number(8),
            Qt.Key_9: lambda: self.select_number(9),
            Qt.Key_0: lambda: self.select_number(0),
            Qt.Key_A: self.start_edit(self.goals.add, 'Add new goal'),
            Qt.Key_C: self.with_refresh(self.goals.toggle_close),
            Qt.Key_D: self.with_refresh(self.goals.delete),
            Qt.Key_I: self.start_edit(self.goals.insert, 'Insert new goal'),
            Qt.Key_L: self.with_refresh(self.goals.toggle_link),
            Qt.Key_Q: self.quit_app.emit,
            Qt.Key_R: self.start_edit(self.goals.rename, 'Rename goal'),
            Qt.Key_S: self.with_refresh(self.goals.swap_goals),
            Qt.Key_V: self.toggle_view,
            Qt.Key_Space: self.with_refresh(self.goals.hold_select),
        }
        if event.key() in key_handlers:
            key_handlers[event.key()]()
        else:
            super().keyPressEvent(event)

    def start_edit(self, fn, dock_label):
        def inner():
            self.dockWidget.setWindowTitle(dock_label)
            self.input.setEnabled(True)
            self.input.setFocus(True)
            self.input.returnPressed.connect(self.finish_edit(fn))
        return inner

    def finish_edit(self, fn):
        def inner():
            self.dockWidget.setWindowTitle('')
            self.input.returnPressed.disconnect()
            fn(self.input.text())
            self.input.setEnabled(False)
            self.input.setText('')
            self.refresh.emit()
        return inner

    def with_refresh(self, fn):
        def inner():
            fn()
            self.refresh.emit()
        return inner

    def select_number(self, num):
        self.goals.select(num)
        self.refresh.emit()

    def toggle_view(self):
        next_view = {
            'full': 'open',
            'open': 'top',
            'top': 'full',
        }
        self.view = next_view[self.view]
        self.force_refresh = True
        self.refresh.emit()

def main(root_script):
    app = QApplication(sys.argv)
    root = dirname(realpath(root_script))
    w = loadUi(join(root, 'ui', 'main.ui'), SiebenApp())
    w.about = loadUi(join(root, 'ui', 'about.ui'))
    w.setup()
    w.showMaximized()
    sys.exit(app.exec_())
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# @Author: Patrick Bos
# @Date:   2016-10-17 18:12:26
# @Last Modified by:   Patrick Bos
# @Last Modified time: 2016-10-19 12:03:45

# as per tensorflow styleguide
# https://www.tensorflow.org/versions/r0.11/how_tos/style_guide.html
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
from tensorflow.python.platform import tf_logging as logging
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
import os

from histpdf_data import combined_raw, gaussian_raw, uniform_raw

tf.logging.set_verbosity(tf.logging.INFO)

project_dn = os.path.expanduser("~/projects/apcocsm/")

N = eventWeight = tf.constant([i['weight'] for i in combined_raw], dtype=tf.float64)

h_g = tf.constant([i['weight'] for i in gaussian_raw], dtype=tf.float64)
h_u = tf.constant([i['weight'] for i in uniform_raw], dtype=tf.float64)

# in this case all bins have equal width
binw = tf.constant([i['vol'] for i in gaussian_raw], dtype=tf.float64)

frac = tf.Variable(0.5, dtype=tf.float64, name="frac")

model = frac * h_g + (1 - frac) * h_u

mu = model * binw

nll = tf.reduce_sum(-(-mu + N * tf.log(mu) - tf.lgamma(N + 1)),
                    name="nll")

print("\nstill missing:\n - Kahan summation\n - zero/small checks\n")

"""
      // Calculate log(Poisson(N|mu) for this bin
      Double_t eventWeight = _dataClone->weight();
      Double_t N = eventWeight ;
      // EGP: getVal returnt weight (via getValV via evaluate in RooHistPdf), binw is de bin width, dus volume in de data
      Double_t mu = _binnedPdf->getVal()*_binw[i] ;

      if (mu<=0 && N>0) {

    // Catch error condition: data present where zero events are predicted
    logEvalError(Form("Observed %f events in bin %d with zero event yield",N,i)) ;

      } else if (fabs(mu)<1e-10 && fabs(N)<1e-10) {

    // Special handling of this case since log(Poisson(0,0)=0 but can't be calculated with usual log-formula
    // since log(mu)=0. No update of result is required since term=0.

        // EGP: result was initialized to 0, so doing nothing keeps it 0

      } else {

    Double_t term = -1*(-mu + N*log(mu) - TMath::LnGamma(N+1)) ;

    // Kahan summation of sumWeight
    Double_t y = eventWeight - sumWeightCarry;
    Double_t t = sumWeight + y;
    sumWeightCarry = (t - sumWeight) - y;
    sumWeight = t;

    // Kahan summation of result
    y = term - carry;
    t = result + y;
    carry = (t - result) - y;
    result = t;
"""

"""
  // If part of simultaneous PDF normalize probability over
  // number of simultaneous PDFs: -sum(log(p/n)) = -sum(log(p)) + N*log(n)
  if (_simCount>1) {
    Double_t y = sumWeight*log(1.0*_simCount) - carry;
    Double_t t = result + y;
    carry = (t - result) - y;
    result = t;
  }
"""

variables = [frac]

bounds = [(0, 1)]

max_steps = 1000
status_every = 1

def run_scipy():
    # Create an optimizer with the desired parameters.
    opt = tf.contrib.opt.ScipyOptimizerInterface(nll,
                                                 options={'maxiter': max_steps,
                                                          # 'maxls': 10,
                                                          },
                                                 bounds=bounds,
                                                 var_list=variables,  # supply with bounds to match order!
                                                 # tol=1e-14,
                                                 )

    init_op = tf.initialize_all_variables()

    # start session
    with tf.Session() as sess:
        sess.run(init_op)

        true_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            true_vars[key] = v.eval()

        print("name\t" + "\t".join([v.name.ljust(10) for v in variables]) + "\t | <nll>\t\t | step")
        print("init\t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))
        print("")

        step = 0

        nll_value_opt = sess.run(nll)

        def step_callback(var_values_opt):
            global step, sess

            if step % status_every == 0:
                print("opt\t" + "\t".join(["%6.4e" % v for v in var_values_opt]) + "\t | %f\t | %i" % (np.mean(nll_value_opt), step))

            step += 1

        def loss_callback(nll_value_opt_step, g1, *other_vars):
            global nll_value_opt
            nll_value_opt = nll_value_opt_step
            print("loss_callback:")
            print("nll:", nll_value_opt)
            print("gradients:", g1)
            ov = "\t".join([str(v) for v in other_vars])
            if ov:
                print("variables:", ov)
            print("")

        """
        start = timer()

        opt.minimize(session=sess, step_callback=step_callback,
                     loss_callback=loss_callback, fetches=[nll] + grads + variables)
        # N.B.: callbacks not supported with SLSQP!

        end = timer()

        print("Loop took %f seconds" % (end - start))

        """
        N_loops = 1
        timings = []
        tf.logging.set_verbosity(tf.logging.ERROR)

        for i in range(N_loops):
            sess.run(init_op)
            start = timer()
            opt.minimize(session=sess)
            end = timer()
            timings.append(end - start)

        tf.logging.set_verbosity(tf.logging.INFO)

        print("Timing total: %f s, average: %f s, minimum: %f s" % (np.sum(timings), np.mean(timings), np.min(timings)))

        # logging.info("get fitted variables")
        fit_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            fit_vars[key] = v.eval()

        print("fit \t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))

def run_adam():
    # Create an optimizer with the desired parameters.
    opt = tf.train.AdamOptimizer()
    opt_op = opt.minimize(nll)

    ix = tf.Variable(tf.constant(0, dtype=tf.int32))
    init_op = tf.initialize_all_variables()

    # start session
    with tf.Session() as sess:
        sess.run(init_op)

        true_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            true_vars[key] = v.eval()

        nll_cur = sess.run(nll)

        print("name\t" + "\t".join([v.name.ljust(10) for v in variables]) + "\t | <nll>\t\t | step")
        print("init\t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(nll_cur))
        print("")

        N_loops = 10
        timings = []
        tf.logging.set_verbosity(tf.logging.ERROR)

        def body(i):
            sess.run([opt_op])
            print(i)
            return i + 1

        def condition(i):
            print(i)
            return i < max_steps

        loop_run = tf.while_loop(condition, body, [ix])

        for i in range(N_loops):
            sess.run(init_op)
            nll_cur = sess.run(nll)
            start = timer()

            sess.run(loop_run)
            # for step in xrange(max_steps):
            #     nll_prev = nll_cur
            #     # print "variables 3:", sess.run(variables)
            #     sess.run([opt_op])
            #     nll_cur = sess.run(nll)

            #     if tf.abs((nll_prev - nll_cur) / (nll_prev + nll_cur) / 2).eval() < 1e-8:
            #         break

            #     # if step % status_every == 0:
            #     #     var_values_opt = sess.run(variables)
            #     #     print("opt\t" + "\t".join(["%6.4e" % v for v in var_values_opt]) + "\t | %f\t | %i" % (nll_cur, step))

            end = timer()
            timings.append(end - start)

        tf.logging.set_verbosity(tf.logging.INFO)

        print("Timing total: %f s, average: %f s, minimum: %f s" % (np.sum(timings), np.mean(timings), np.min(timings)))

        # logging.info("get fitted variables")
        fit_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            fit_vars[key] = v.eval()

        print("fit \t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))

print("\nSCIPY RUN")
run_scipy()
print("\nADAM RUN")
run_adam()
<commit_msg>Fixed while_loop implementation<commit_after># -*- coding: utf-8 -*-
# @Author: Patrick Bos
# @Date:   2016-10-17 18:12:26
# @Last Modified by:   Patrick Bos
# @Last Modified time: 2016-10-19 14:09:39

# as per tensorflow styleguide
# https://www.tensorflow.org/versions/r0.11/how_tos/style_guide.html
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
from tensorflow.python.platform import tf_logging as logging
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
import os

from histpdf_data import combined_raw, gaussian_raw, uniform_raw

tf.logging.set_verbosity(tf.logging.INFO)

project_dn = os.path.expanduser("~/projects/apcocsm/")

N = eventWeight = tf.constant([i['weight'] for i in combined_raw], dtype=tf.float64)

h_g = tf.constant([i['weight'] for i in gaussian_raw], dtype=tf.float64)
h_u = tf.constant([i['weight'] for i in uniform_raw], dtype=tf.float64)

# in this case all bins have equal width
binw = tf.constant([i['vol'] for i in gaussian_raw], dtype=tf.float64)

frac = tf.Variable(0.5, dtype=tf.float64, name="frac")

model = frac * h_g + (1 - frac) * h_u

mu = model * binw

nll = tf.reduce_sum(-(-mu + N * tf.log(mu) - tf.lgamma(N + 1)),
                    name="nll")

print("\nstill missing:\n - Kahan summation\n - zero/small checks\n")

"""
      // Calculate log(Poisson(N|mu) for this bin
      Double_t eventWeight = _dataClone->weight();
      Double_t N = eventWeight ;
      // EGP: getVal returnt weight (via getValV via evaluate in RooHistPdf), binw is de bin width, dus volume in de data
      Double_t mu = _binnedPdf->getVal()*_binw[i] ;

      if (mu<=0 && N>0) {

    // Catch error condition: data present where zero events are predicted
    logEvalError(Form("Observed %f events in bin %d with zero event yield",N,i)) ;

      } else if (fabs(mu)<1e-10 && fabs(N)<1e-10) {

    // Special handling of this case since log(Poisson(0,0)=0 but can't be calculated with usual log-formula
    // since log(mu)=0. No update of result is required since term=0.

        // EGP: result was initialized to 0, so doing nothing keeps it 0

      } else {

    Double_t term = -1*(-mu + N*log(mu) - TMath::LnGamma(N+1)) ;

    // Kahan summation of sumWeight
    Double_t y = eventWeight - sumWeightCarry;
    Double_t t = sumWeight + y;
    sumWeightCarry = (t - sumWeight) - y;
    sumWeight = t;

    // Kahan summation of result
    y = term - carry;
    t = result + y;
    carry = (t - result) - y;
    result = t;
"""

"""
  // If part of simultaneous PDF normalize probability over
  // number of simultaneous PDFs: -sum(log(p/n)) = -sum(log(p)) + N*log(n)
  if (_simCount>1) {
    Double_t y = sumWeight*log(1.0*_simCount) - carry;
    Double_t t = result + y;
    carry = (t - result) - y;
    result = t;
  }
"""

variables = [frac]

bounds = [(0, 1)]

max_steps = 1000
status_every = 1

def run_scipy():
    # Create an optimizer with the desired parameters.
    opt = tf.contrib.opt.ScipyOptimizerInterface(nll,
                                                 options={'maxiter': max_steps,
                                                          # 'maxls': 10,
                                                          },
                                                 bounds=bounds,
                                                 var_list=variables,  # supply with bounds to match order!
                                                 # tol=1e-14,
                                                 )

    init_op = tf.initialize_all_variables()

    # start session
    with tf.Session() as sess:
        sess.run(init_op)

        true_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            true_vars[key] = v.eval()

        print("name\t" + "\t".join([v.name.ljust(10) for v in variables]) + "\t | <nll>\t\t | step")
        print("init\t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))
        print("")

        step = 0

        nll_value_opt = sess.run(nll)

        def step_callback(var_values_opt):
            global step, sess

            if step % status_every == 0:
                print("opt\t" + "\t".join(["%6.4e" % v for v in var_values_opt]) + "\t | %f\t | %i" % (np.mean(nll_value_opt), step))

            step += 1

        def loss_callback(nll_value_opt_step, g1, *other_vars):
            global nll_value_opt
            nll_value_opt = nll_value_opt_step
            print("loss_callback:")
            print("nll:", nll_value_opt)
            print("gradients:", g1)
            ov = "\t".join([str(v) for v in other_vars])
            if ov:
                print("variables:", ov)
            print("")

        """
        start = timer()

        opt.minimize(session=sess, step_callback=step_callback,
                     loss_callback=loss_callback, fetches=[nll] + grads + variables)
        # N.B.: callbacks not supported with SLSQP!

        end = timer()

        print("Loop took %f seconds" % (end - start))

        """
        N_loops = 1
        timings = []
        tf.logging.set_verbosity(tf.logging.ERROR)

        for i in range(N_loops):
            sess.run(init_op)
            start = timer()
            opt.minimize(session=sess)
            end = timer()
            timings.append(end - start)

        tf.logging.set_verbosity(tf.logging.INFO)

        print("Timing total: %f s, average: %f s, minimum: %f s" % (np.sum(timings), np.mean(timings), np.min(timings)))

        # logging.info("get fitted variables")
        fit_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            fit_vars[key] = v.eval()

        print("fit \t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))

def run_adam():
    # Create an optimizer with the desired parameters.
    opt = tf.train.AdamOptimizer()
    ix = tf.Variable(0)
    max_steps_tf = tf.constant(max_steps)
    gs = tf.Variable(0)

    def body(i):
        # When using while_loop, everything except the variables and constants,
        # i.e. everything that has to be recalculated every iteration, has to
        # be inside the body!
        # See http://stackoverflow.com/a/38999135/1199693
        model = frac * h_g + (1 - frac) * h_u
        mu = model * binw
        nll = tf.reduce_sum(-(-mu + N * tf.log(mu) - tf.lgamma(N + 1)),
                            name="nll_body")
        opt_op = opt.minimize(nll, global_step=gs)
        with tf.control_dependencies([opt_op]):
            return i + 1

    def condition(i, *args):
        return i < max_steps_tf

    adam_loop = tf.while_loop(condition, body, [ix])

    init_op = tf.initialize_all_variables()

    # start session
    with tf.Session() as sess:
        sess.run(init_op)

        true_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            true_vars[key] = v.eval()

        nll_cur = sess.run(nll)

        print("name\t" + "\t".join([v.name.ljust(10) for v in variables]) + "\t | <nll>\t\t | step")
        print("init\t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(nll_cur))
        print("")

        N_loops = 10
        timings = []
        tf.logging.set_verbosity(tf.logging.ERROR)

        for i in range(N_loops):
            print('loop', i)
            sess.run(init_op)
            nll_cur = sess.run(nll)
            start = timer()

            print(sess.run(gs))
            sess.run(adam_loop)
            print(sess.run(gs))
            # for step in xrange(max_steps):
            #     nll_prev = nll_cur
            #     # print "variables 3:", sess.run(variables)
            #     sess.run([opt_op])
            #     nll_cur = sess.run(nll)

            #     if tf.abs((nll_prev - nll_cur) / (nll_prev + nll_cur) / 2).eval() < 1e-8:
            #         break

            #     # if step % status_every == 0:
            #     #     var_values_opt = sess.run(variables)
            #     #     print("opt\t" + "\t".join(["%6.4e" % v for v in var_values_opt]) + "\t | %f\t | %i" % (nll_cur, step))

            end = timer()
            timings.append(end - start)

        tf.logging.set_verbosity(tf.logging.INFO)

        print("Timing total: %f s, average: %f s, minimum: %f s" % (np.sum(timings), np.mean(timings), np.min(timings)))

        # logging.info("get fitted variables")
        fit_vars = {}
        for v in variables:
            key = v.name[:v.name.find(':')]
            fit_vars[key] = v.eval()

        print("fit \t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))

print("\nSCIPY RUN")
run_scipy()
print("\nADAM RUN")
run_adam()
<|endoftext|>


<commit_before>from django.contrib import admin

from django_monitor.admin import MonitorAdmin

from .models import StewardNotification, StewardProject

class StewardNotificationAdmin(MonitorAdmin):
    list_display = ('pk', 'name',)

class StewardProjectAdmin(admin.ModelAdmin):
    list_display = ('pk', 'name', 'address', 'organizer', 'use',)

    def address(self, obj):
        try:
            return obj.content_object.address_line1
        except Exception:
            return ''

admin.site.register(StewardNotification, StewardNotificationAdmin)
admin.site.register(StewardProject, StewardProjectAdmin)
<commit_msg>list_filter for StewardProject<commit_after>from django.contrib import admin

from django_monitor.admin import MonitorAdmin

from .models import StewardNotification, StewardProject

class StewardNotificationAdmin(MonitorAdmin):
    list_display = ('pk', 'name',)

class StewardProjectAdmin(admin.ModelAdmin):
    list_display = ('pk', 'name', 'address', 'organizer', 'use',
                    'include_on_map',)
    list_filter = ('use', 'include_on_map',)

    def address(self, obj):
        try:
            return obj.content_object.address_line1
        except Exception:
            return ''

admin.site.register(StewardNotification, StewardNotificationAdmin)
admin.site.register(StewardProject, StewardProjectAdmin)
<|endoftext|>


<commit_before># Written by Logan Rickert
# Februray 28th, 2015
# This document is in CC0 1.0 Universal (CC0 1.0)
# https://creativecommons.org/publicdomain/zero/1.0/

# This program recrusively goes through all directories and files in the C directory
# and reports back to the user the files that are duplicates.
# This program generates an MD5 sum for each file and stores it in a dictonary.

# If an error is thrown when opening up the file to generate an MD5 sum, the file
# is closed and is not added to md5_sums nor dupe_file_paths and the error is
# reported to the user.

#############################
#          imports          #
#############################
import os
import glob
import hashlib

# The initial directory you wish to start at.
# The program will not go outside of this directory.
initial_file_directory = 'C:\\'

# Holds the md5 sums for all of the files.
md5_sums = {}

# Holds the file path to all of the duplicate files.
dupe_file_paths = []

# Sources:
# http://bogdan.org.ua/2007/08/12/python-iterate-and-read-all-files-in-a-directory-folder.html#comment-103404
# http://www.pythoncentral.io/hashing-files-with-python/

#############################
#          Methods          #
#############################

def scan_dirs(path):
    """Recursively goes through each directory and adds the md5 sum
    to the md5_sums dictionary. If the md5 sum has already been added,
    it is added to dupe_file_paths.

    Most of the code came from:
    http://bogdan.org.ua/2007/08/12/python-iterate-and-read-all-files-in-a-directory-folder.html#comment-103404
    """
    for currentFile in glob.glob( os.path.join(path, '*') ):
        # If the file is a directory, scan that directory
        if os.path.isdir(currentFile):
            scan_dirs(currentFile)

        # Make sure the path is not a directory coming out of the recursion
        if not os.path.isdir(currentFile):
            current_sum = md5_sum(currentFile)
            # If the sum is 0, there was an error with the file.
            if current_sum != 0:
                if current_sum in md5_sums:
                    dupe_file_paths.append(currentFile)
                else:
                    md5_sums[md5_sum(currentFile)] = currentFile

def md5_sum(filename):
    """Figures out the md5 sum for a file given through the filename.
    If the file has an error on opening, the MD5sume comes back as 0.

    Source:
    http://www.pythoncentral.io/hashing-files-with-python/
    """
    BLOCKSIZE = 65536
    hasher = hashlib.md5()

    # Makes sure file can be read. May be come back permission denied.
    try:
        with open(filename, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher.update(buf)
                buf = afile.read(BLOCKSIZE)
        return hasher.hexdigest()
    except:
        print("Error reading the file: " + filename)
        return "0"

def print_md5_dictonary():
    """Goes through the md5 dictionary and prints out the md5 sums
    along with the complete file path for error checking.
    """
    for md5_sum, path in md5_sums.items():
        print(md5_sum + " " + path)

#############################
#   Start of the program    #
#############################

# Scans the directories and fills the md5_sums and dupe_file_paths
scan_dirs(initial_file_directory)

# Prints out all of the duplicate files
print("Duplicate files: ")
for file_path in dupe_file_paths:
    print(file_path)
<commit_msg>Removed repeativeness in scan_dirs<commit_after># Written by Logan Rickert
# Februray 28th, 2015
# This document is in CC0 1.0 Universal (CC0 1.0)
# https://creativecommons.org/publicdomain/zero/1.0/

# This program recrusively goes through all directories and files in the C directory
# and reports back to the user the files that are duplicates.
# This program generates an MD5 sum for each file and stores it in a dictonary.

# If an error is thrown when opening up the file to generate an MD5 sum, the file
# is closed and is not added to md5_sums nor dupe_file_paths and the error is
# reported to the user.

#############################
#          imports          #
#############################
import os
import glob
import hashlib

# The initial directory you wish to start at.
# The program will not go outside of this directory.
initial_file_directory = 'C:\\Users\\Logan\\Desktop\\processing-2.2.1'

# Holds the md5 sums for all of the files.
md5_sums = {}

# Holds the file path to all of the duplicate files.
dupe_file_paths = []

# Sources:
# http://bogdan.org.ua/2007/08/12/python-iterate-and-read-all-files-in-a-directory-folder.html#comment-103404
# http://www.pythoncentral.io/hashing-files-with-python/

#############################
#          Methods          #
#############################

def scan_dirs(path):
    """Recursively goes through each directory and adds the md5 sum
    to the md5_sums dictionary. If the md5 sum has already been added,
    it is added to dupe_file_paths.

    Most of the code came from:
    http://bogdan.org.ua/2007/08/12/python-iterate-and-read-all-files-in-a-directory-folder.html#comment-103404
    """
    for currentFile in glob.glob( os.path.join(path, '*') ):
        # If the file is a directory, scan that directory
        if os.path.isdir(currentFile):
            scan_dirs(currentFile)
        else:
            current_sum = md5_sum(currentFile)
            # If the sum is 0, there was an error with the file.
            if current_sum != 0:
                if current_sum in md5_sums:
                    dupe_file_paths.append(currentFile)
                else:
                    md5_sums[md5_sum(currentFile)] = currentFile

def md5_sum(filename):
    """Figures out the md5 sum for a file given through the filename.
    If the file has an error on opening, the MD5sume comes back as 0.

    Source:
    http://www.pythoncentral.io/hashing-files-with-python/
    """
    BLOCKSIZE = 65536
    hasher = hashlib.md5()

    # Makes sure file can be read. May be come back permission denied.
    try:
        with open(filename, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher.update(buf)
                buf = afile.read(BLOCKSIZE)
        return hasher.hexdigest()
    except:
        print("Error reading the file: " + filename)
        return "0"

def print_md5_dictonary():
    """Goes through the md5 dictionary and prints out the md5 sums
    along with the complete file path for error checking.
    """
    for md5_sum, path in md5_sums.items():
        print(md5_sum + " " + path)

#############################
#   Start of the program    #
#############################

# Scans the directories and fills the md5_sums and dupe_file_paths
scan_dirs(initial_file_directory)

# Prints out all of the duplicate files
print("Duplicate files: ")
for file_path in dupe_file_paths:
    print(file_path)
<|endoftext|>


<commit_before>"""siftsite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('labeller.urls')),
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
]

if False:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)
<commit_msg>reset back to working config?<commit_after>"""siftsite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('labeller.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Copyright © 2012-2015 Roberto Alsina and others.

# 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.

"""Start test server."""

from __future__ import print_function
import os
import socket
import webbrowser
try:
    from BaseHTTPServer import HTTPServer
    from SimpleHTTPServer import SimpleHTTPRequestHandler
except ImportError:
    from http.server import HTTPServer  # NOQA
    from http.server import SimpleHTTPRequestHandler  # NOQA

from nikola.plugin_categories import Command
from nikola.utils import get_logger, STDERR_HANDLER

class IPv6Server(HTTPServer):

    """An IPv6 HTTPServer."""

    address_family = socket.AF_INET6

class CommandServe(Command):

    """Start test server."""

    name = "serve"
    doc_usage = "[options]"
    doc_purpose = "start the test webserver"
    logger = None

    cmd_options = (
        {
            'name': 'port',
            'short': 'p',
            'long': 'port',
            'default': 8000,
            'type': int,
            'help': 'Port number (default: 8000)',
        },
        {
            'name': 'address',
            'short': 'a',
            'long': 'address',
            'type': str,
            'default': '',
            'help': 'Address to bind (default: 0.0.0.0 – all local IPv4 interfaces)',
        },
        {
            'name': 'detach',
            'short': 'd',
            'long': 'detach',
            'type': bool,
            'default': False,
            'help': 'Detach from TTY (work in the background)',
        },
        {
            'name': 'browser',
            'short': 'b',
            'long': 'browser',
            'type': bool,
            'default': False,
            'help': 'Open the test server in a web browser',
        },
        {
            'name': 'ipv6',
            'short': '6',
            'long': 'ipv6',
            'type': bool,
            'default': False,
            'help': 'Use IPv6',
        },
    )

    def _execute(self, options, args):
        """Start test server."""
        self.logger = get_logger('serve', STDERR_HANDLER)
        out_dir = self.site.config['OUTPUT_FOLDER']
        if not os.path.isdir(out_dir):
            self.logger.error("Missing '{0}' folder?".format(out_dir))
        else:
            os.chdir(out_dir)
            if '[' in options['address']:
                options['address'] = options['address'].strip('[').strip(']')
                ipv6 = True
                OurHTTP = IPv6Server
            elif options['ipv6']:
                ipv6 = True
                OurHTTP = IPv6Server
            else:
                ipv6 = False
                OurHTTP = HTTPServer

            httpd = OurHTTP((options['address'], options['port']),
                            OurHTTPRequestHandler)
            sa = httpd.socket.getsockname()
            self.logger.info("Serving HTTP on {0} port {1}...".format(*sa))
            if options['browser']:
                if ipv6:
                    server_url = "http://[{0}]:{1}/".format(*sa)
                else:
                    server_url = "http://{0}:{1}/".format(*sa)
                self.logger.info("Opening {0} in the default web browser...".format(server_url))
                webbrowser.open(server_url)
            if options['detach']:
                OurHTTPRequestHandler.quiet = True
                try:
                    pid = os.fork()
                    if pid == 0:
                        httpd.serve_forever()
                    else:
                        self.logger.info("Detached with PID {0}. Run `kill {0}` to stop the server.".format(pid))
                except AttributeError as e:
                    if os.name == 'nt':
                        self.logger.warning("Detaching is not available on Windows, server is running in the foreground.")
                    else:
                        raise e
            else:
                try:
                    httpd.serve_forever()
                except KeyboardInterrupt:
                    self.logger.info("Server is shutting down.")
                    return 130

class OurHTTPRequestHandler(SimpleHTTPRequestHandler):

    """A request handler, modified for Nikola."""

    extensions_map = dict(SimpleHTTPRequestHandler.extensions_map)
    extensions_map[""] = "text/plain"
    quiet = False

    def log_message(self, *args):
        """Log messages.  Or not, depending on a setting."""
        if self.quiet:
            return
        else:
            # Old-style class in Python 2.7, cannot use super()
            return SimpleHTTPRequestHandler.log_message(self, *args)

    # NOTICE: this is a patched version of send_head() to disable all sorts of
    # caching.  `nikola serve` is a development server, hence caching should
    # not happen to have access to the newest resources.
    #
    # The original code was copy-pasted from Python 2.7.  Python 3.3 contains
    # the same code, missing the binary mode comment.
    #
    # Note that it might break in future versions of Python, in which case we
    # would need to do even more magic.
    def send_head(self):
        """Common code for GET and HEAD commands.

        This sends the response code and MIME headers.

        Return value is either a file object (which has to be copied
        to the outputfile by the caller unless the command was HEAD,
        and must be closed by the caller under all circumstances), or
        None, in which case the caller has nothing further to do.

        """
        path = self.translate_path(self.path)
        f = None
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # redirect browser - doing basically what apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                # begin no-cache patch
                # For redirects.  With redirects, caching is even worse and can
                # break more.  Especially with 301 Moved Permanently redirects,
                # like this one.
                self.send_header("Cache-Control", "no-cache, no-store, "
                                 "must-revalidate")
                self.send_header("Pragma", "no-cache")
                self.send_header("Expires", "0")
                # end no-cache patch
                self.end_headers()
                return None
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    path = index
                    break
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            # Always read in binary mode. Opening files in text mode may cause
            # newline translations, making the actual size of the content
            # transmitted *less* than the content-length!
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        if os.path.splitext(path)[1] == '.svgz':
            # Special handling for svgz to make it work nice with browsers.
            self.send_header("Content-Encoding", 'gzip')
        fs = os.fstat(f.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        # begin no-cache patch
        # For standard requests.
        self.send_header("Cache-Control", "no-cache, no-store, "
                         "must-revalidate")
        self.send_header("Pragma", "no-cache")
        self.send_header("Expires", "0")
        # end no-cache patch
        self.end_headers()
        return f
<commit_msg>Re-<base> serve command on the fly<commit_after># -*- coding: utf-8 -*-

# Copyright © 2012-2015 Roberto Alsina and others.

# 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.

"""Start test server."""

from __future__ import print_function
import os
import re
import socket
import tempfile
import webbrowser
try:
    from BaseHTTPServer import HTTPServer
    from SimpleHTTPServer import SimpleHTTPRequestHandler
except ImportError:
    from http.server import HTTPServer  # NOQA
    from http.server import SimpleHTTPRequestHandler  # NOQA

try:
    from StringIO import StringIO
except ImportError:
    from io import BytesIO as StringIO  # NOQA

from nikola.plugin_categories import Command
from nikola.utils import get_logger, STDERR_HANDLER

class IPv6Server(HTTPServer):

    """An IPv6 HTTPServer."""

    address_family = socket.AF_INET6

class CommandServe(Command):

    """Start test server."""

    name = "serve"
    doc_usage = "[options]"
    doc_purpose = "start the test webserver"
    logger = None

    cmd_options = (
        {
            'name': 'port',
            'short': 'p',
            'long': 'port',
            'default': 8000,
            'type': int,
            'help': 'Port number (default: 8000)',
        },
        {
            'name': 'address',
            'short': 'a',
            'long': 'address',
            'type': str,
            'default': '',
            'help': 'Address to bind (default: 0.0.0.0 – all local IPv4 interfaces)',
        },
        {
            'name': 'detach',
            'short': 'd',
            'long': 'detach',
            'type': bool,
            'default': False,
            'help': 'Detach from TTY (work in the background)',
        },
        {
            'name': 'browser',
            'short': 'b',
            'long': 'browser',
            'type': bool,
            'default': False,
            'help': 'Open the test server in a web browser',
        },
        {
            'name': 'ipv6',
            'short': '6',
            'long': 'ipv6',
            'type': bool,
            'default': False,
            'help': 'Use IPv6',
        },
    )

    def _execute(self, options, args):
        """Start test server."""
        self.logger = get_logger('serve', STDERR_HANDLER)
        out_dir = self.site.config['OUTPUT_FOLDER']
        if not os.path.isdir(out_dir):
            self.logger.error("Missing '{0}' folder?".format(out_dir))
        else:
            os.chdir(out_dir)
            if '[' in options['address']:
                options['address'] = options['address'].strip('[').strip(']')
                ipv6 = True
                OurHTTP = IPv6Server
            elif options['ipv6']:
                ipv6 = True
                OurHTTP = IPv6Server
            else:
                ipv6 = False
                OurHTTP = HTTPServer

            httpd = OurHTTP((options['address'], options['port']),
                            OurHTTPRequestHandler)
            sa = httpd.socket.getsockname()
            self.logger.info("Serving HTTP on {0} port {1}...".format(*sa))
            if options['browser']:
                if ipv6:
                    server_url = "http://[{0}]:{1}/".format(*sa)
                else:
                    server_url = "http://{0}:{1}/".format(*sa)
                self.logger.info("Opening {0} in the default web browser...".format(server_url))
                webbrowser.open(server_url)
            if options['detach']:
                OurHTTPRequestHandler.quiet = True
                try:
                    pid = os.fork()
                    if pid == 0:
                        httpd.serve_forever()
                    else:
                        self.logger.info("Detached with PID {0}. Run `kill {0}` to stop the server.".format(pid))
                except AttributeError as e:
                    if os.name == 'nt':
                        self.logger.warning("Detaching is not available on Windows, server is running in the foreground.")
                    else:
                        raise e
            else:
                try:
                    httpd.serve_forever()
                except KeyboardInterrupt:
                    self.logger.info("Server is shutting down.")
                    return 130

class OurHTTPRequestHandler(SimpleHTTPRequestHandler):

    """A request handler, modified for Nikola."""

    extensions_map = dict(SimpleHTTPRequestHandler.extensions_map)
    extensions_map[""] = "text/plain"
    quiet = False

    def log_message(self, *args):
        """Log messages.  Or not, depending on a setting."""
        if self.quiet:
            return
        else:
            # Old-style class in Python 2.7, cannot use super()
            return SimpleHTTPRequestHandler.log_message(self, *args)

    # NOTICE: this is a patched version of send_head() to disable all sorts of
    # caching.  `nikola serve` is a development server, hence caching should
    # not happen to have access to the newest resources.
    #
    # The original code was copy-pasted from Python 2.7.  Python 3.3 contains
    # the same code, missing the binary mode comment.
    #
    # Note that it might break in future versions of Python, in which case we
    # would need to do even more magic.
    def send_head(self):
        """Common code for GET and HEAD commands.

        This sends the response code and MIME headers.

        Return value is either a file object (which has to be copied
        to the outputfile by the caller unless the command was HEAD,
        and must be closed by the caller under all circumstances), or
        None, in which case the caller has nothing further to do.

        """
        path = self.translate_path(self.path)
        f = None
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # redirect browser - doing basically what apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                # begin no-cache patch
                # For redirects.  With redirects, caching is even worse and can
                # break more.  Especially with 301 Moved Permanently redirects,
                # like this one.
                self.send_header("Cache-Control", "no-cache, no-store, "
                                 "must-revalidate")
                self.send_header("Pragma", "no-cache")
                self.send_header("Expires", "0")
                # end no-cache patch
                self.end_headers()
                return None
            for index in "index.html", "index.htm":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    path = index
                    break
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            # Always read in binary mode. Opening files in text mode may cause
            # newline translations, making the actual size of the content
            # transmitted *less* than the content-length!
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None

        filtered_bytes = None
        if ctype == 'text/html':
            """Comment out any <base> to allow local resolution of relative URLs."""
            data = f.read().decode('utf8')
            f.close()
            data = re.sub(r'<base\s([^>]*)>', '<!--base \g<1>-->', data, re.IGNORECASE)
            data = data.encode('utf8')
            f = StringIO()
            f.write(data)
            f.seek(0)
            filtered_bytes = f.tell()

        self.send_response(200)
        self.send_header("Content-type", ctype)
        if os.path.splitext(path)[1] == '.svgz':
            # Special handling for svgz to make it work nice with browsers.
            self.send_header("Content-Encoding", 'gzip')

        if filtered_bytes is None:
            fs = os.fstat(f.fileno())
            self.send_header('Content-Length', str(fs[6]))
        else:
            self.send_header('Content-Length', filtered_bytes)

        # begin no-cache patch
        # For standard requests.
        self.send_header("Cache-Control", "no-cache, no-store, "
                         "must-revalidate")
        self.send_header("Pragma", "no-cache")
        self.send_header("Expires", "0")
        # end no-cache patch
        self.end_headers()
        return f
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# @Author: Patrick Bos
# @Date:   2016-10-17 18:12:26
# @Last Modified by:   Patrick Bos
# @Last Modified time: 2016-10-19 10:06:12

# as per tensorflow styleguide
# https://www.tensorflow.org/versions/r0.11/how_tos/style_guide.html
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
from tensorflow.python.platform import tf_logging as logging
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer

from histpdf_data import combined_raw, gaussian_raw, uniform_raw

tf.logging.set_verbosity(tf.logging.INFO)

project_dn = "/home/patrick/projects/apcocsm/"
# project_dn = "/home/pbos/apcocsm/"

N = eventWeight = tf.constant([i['weight'] for i in combined_raw], dtype=tf.float64)

h_g = tf.constant([i['weight'] for i in gaussian_raw], dtype=tf.float64)
h_u = tf.constant([i['weight'] for i in uniform_raw], dtype=tf.float64)

# in this case all bins have equal width
binw = tf.constant([i['vol'] for i in gaussian_raw], dtype=tf.float64)

frac = tf.Variable(0.5, dtype=tf.float64, name="frac")

model = frac * h_g + (1 - frac) * h_u

mu = model * binw

nll = tf.reduce_sum(-(-mu + N * tf.log(mu) - tf.lgamma(N + 1)),
                    name="nll")

print("\nstill missing:\n - Kahan summation\n - zero/small checks\n")

"""
      // Calculate log(Poisson(N|mu) for this bin
      Double_t eventWeight = _dataClone->weight();
      Double_t N = eventWeight ;
      // EGP: getVal returnt weight (via getValV via evaluate in RooHistPdf), binw is de bin width, dus volume in de data
      Double_t mu = _binnedPdf->getVal()*_binw[i] ;

      if (mu<=0 && N>0) {

    // Catch error condition: data present where zero events are predicted
    logEvalError(Form("Observed %f events in bin %d with zero event yield",N,i)) ;

      } else if (fabs(mu)<1e-10 && fabs(N)<1e-10) {

    // Special handling of this case since log(Poisson(0,0)=0 but can't be calculated with usual log-formula
    // since log(mu)=0. No update of result is required since term=0.

        // EGP: result was initialized to 0, so doing nothing keeps it 0

      } else {

    Double_t term = -1*(-mu + N*log(mu) - TMath::LnGamma(N+1)) ;

    // Kahan summation of sumWeight
    Double_t y = eventWeight - sumWeightCarry;
    Double_t t = sumWeight + y;
    sumWeightCarry = (t - sumWeight) - y;
    sumWeight = t;

    // Kahan summation of result
    y = term - carry;
    t = result + y;
    carry = (t - result) - y;
    result = t;
"""

"""
  // If part of simultaneous PDF normalize probability over
  // number of simultaneous PDFs: -sum(log(p/n)) = -sum(log(p)) + N*log(n)
  if (_simCount>1) {
    Double_t y = sumWeight*log(1.0*_simCount) - carry;
    Double_t t = result + y;
    carry = (t - result) - y;
    result = t;
  }
"""

variables = [frac]

bounds = [(0, 1)]

max_steps = 1000
status_every = 1

# Create an optimizer with the desired parameters.
opt = tf.contrib.opt.ScipyOptimizerInterface(nll,
                                             options={'maxiter': max_steps,
                                                      # 'maxls': 10,
                                                      },
                                             bounds=bounds,
                                             var_list=variables,  # supply with bounds to match order!
                                             # tol=1e-14,
                                             )

init_op = tf.initialize_all_variables()

# start session
with tf.Session() as sess:
    sess.run(init_op)

    true_vars = {}
    for v in variables:
        key = v.name[:v.name.find(':')]
        true_vars[key] = v.eval()

    print("name\t" + "\t".join([v.name.ljust(10) for v in variables]) + "\t | <nll>\t\t | step")
    print("init\t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))
    print("")

    step = 0

    nll_value_opt = sess.run(nll)

    def step_callback(var_values_opt):
        global step, sess

        if step % status_every == 0:
            print("opt\t" + "\t".join(["%6.4e" % v for v in var_values_opt]) + "\t | %f\t | %i" % (np.mean(nll_value_opt), step))

        step += 1

    def loss_callback(nll_value_opt_step, g1, *other_vars):
        global nll_value_opt
        nll_value_opt = nll_value_opt_step
        print("loss_callback:")
        print("nll:", nll_value_opt)
        print("gradients:", g1)
        ov = "\t".join([str(v) for v in other_vars])
        if ov:
            print("variables:", ov)
        print("")

    """
    start = timer()

    opt.minimize(session=sess, step_callback=step_callback,
                 loss_callback=loss_callback, fetches=[nll] + grads + variables)
    # N.B.: callbacks not supported with SLSQP!

    end = timer()

    print("Loop took %f seconds" % (end - start))

    """
    N_loops = 1000
    timings = []
    tf.logging.set_verbosity(tf.logging.ERROR)

    for i in range(N_loops):
        sess.run(init_op)
        start = timer()
        opt.minimize(session=sess)
        end = timer()
        timings.append(end - start)

    tf.logging.set_verbosity(tf.logging.INFO)

    print("Timing total: %f s, average: %f s, minimum: %f s" % (np.sum(timings), np.mean(timings), np.min(timings)))

    # logging.info("get fitted variables")
    fit_vars = {}
    for v in variables:
        key = v.name[:v.name.find(':')]
        fit_vars[key] = v.eval()

    print("fit \t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))
<commit_msg>expanduser for path here as well<commit_after># -*- coding: utf-8 -*-
# @Author: Patrick Bos
# @Date:   2016-10-17 18:12:26
# @Last Modified by:   Patrick Bos
# @Last Modified time: 2016-10-19 11:01:32

# as per tensorflow styleguide
# https://www.tensorflow.org/versions/r0.11/how_tos/style_guide.html
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
from tensorflow.python.platform import tf_logging as logging
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
import os

from histpdf_data import combined_raw, gaussian_raw, uniform_raw

tf.logging.set_verbosity(tf.logging.INFO)

project_dn = os.path.expanduser("~/projects/apcocsm/")

N = eventWeight = tf.constant([i['weight'] for i in combined_raw], dtype=tf.float64)

h_g = tf.constant([i['weight'] for i in gaussian_raw], dtype=tf.float64)
h_u = tf.constant([i['weight'] for i in uniform_raw], dtype=tf.float64)

# in this case all bins have equal width
binw = tf.constant([i['vol'] for i in gaussian_raw], dtype=tf.float64)

frac = tf.Variable(0.5, dtype=tf.float64, name="frac")

model = frac * h_g + (1 - frac) * h_u

mu = model * binw

nll = tf.reduce_sum(-(-mu + N * tf.log(mu) - tf.lgamma(N + 1)),
                    name="nll")

print("\nstill missing:\n - Kahan summation\n - zero/small checks\n")

"""
      // Calculate log(Poisson(N|mu) for this bin
      Double_t eventWeight = _dataClone->weight();
      Double_t N = eventWeight ;
      // EGP: getVal returnt weight (via getValV via evaluate in RooHistPdf), binw is de bin width, dus volume in de data
      Double_t mu = _binnedPdf->getVal()*_binw[i] ;

      if (mu<=0 && N>0) {

    // Catch error condition: data present where zero events are predicted
    logEvalError(Form("Observed %f events in bin %d with zero event yield",N,i)) ;

      } else if (fabs(mu)<1e-10 && fabs(N)<1e-10) {

    // Special handling of this case since log(Poisson(0,0)=0 but can't be calculated with usual log-formula
    // since log(mu)=0. No update of result is required since term=0.

        // EGP: result was initialized to 0, so doing nothing keeps it 0

      } else {

    Double_t term = -1*(-mu + N*log(mu) - TMath::LnGamma(N+1)) ;

    // Kahan summation of sumWeight
    Double_t y = eventWeight - sumWeightCarry;
    Double_t t = sumWeight + y;
    sumWeightCarry = (t - sumWeight) - y;
    sumWeight = t;

    // Kahan summation of result
    y = term - carry;
    t = result + y;
    carry = (t - result) - y;
    result = t;
"""

"""
  // If part of simultaneous PDF normalize probability over
  // number of simultaneous PDFs: -sum(log(p/n)) = -sum(log(p)) + N*log(n)
  if (_simCount>1) {
    Double_t y = sumWeight*log(1.0*_simCount) - carry;
    Double_t t = result + y;
    carry = (t - result) - y;
    result = t;
  }
"""

variables = [frac]

bounds = [(0, 1)]

max_steps = 1000
status_every = 1

# Create an optimizer with the desired parameters.
opt = tf.contrib.opt.ScipyOptimizerInterface(nll,
                                             options={'maxiter': max_steps,
                                                      # 'maxls': 10,
                                                      },
                                             bounds=bounds,
                                             var_list=variables,  # supply with bounds to match order!
                                             # tol=1e-14,
                                             )

init_op = tf.initialize_all_variables()

# start session
with tf.Session() as sess:
    sess.run(init_op)

    true_vars = {}
    for v in variables:
        key = v.name[:v.name.find(':')]
        true_vars[key] = v.eval()

    print("name\t" + "\t".join([v.name.ljust(10) for v in variables]) + "\t | <nll>\t\t | step")
    print("init\t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))
    print("")

    step = 0

    nll_value_opt = sess.run(nll)

    def step_callback(var_values_opt):
        global step, sess

        if step % status_every == 0:
            print("opt\t" + "\t".join(["%6.4e" % v for v in var_values_opt]) + "\t | %f\t | %i" % (np.mean(nll_value_opt), step))

        step += 1

    def loss_callback(nll_value_opt_step, g1, *other_vars):
        global nll_value_opt
        nll_value_opt = nll_value_opt_step
        print("loss_callback:")
        print("nll:", nll_value_opt)
        print("gradients:", g1)
        ov = "\t".join([str(v) for v in other_vars])
        if ov:
            print("variables:", ov)
        print("")

    """
    start = timer()

    opt.minimize(session=sess, step_callback=step_callback,
                 loss_callback=loss_callback, fetches=[nll] + grads + variables)
    # N.B.: callbacks not supported with SLSQP!

    end = timer()

    print("Loop took %f seconds" % (end - start))

    """
    N_loops = 1000
    timings = []
    tf.logging.set_verbosity(tf.logging.ERROR)

    for i in range(N_loops):
        sess.run(init_op)
        start = timer()
        opt.minimize(session=sess)
        end = timer()
        timings.append(end - start)

    tf.logging.set_verbosity(tf.logging.INFO)

    print("Timing total: %f s, average: %f s, minimum: %f s" % (np.sum(timings), np.mean(timings), np.min(timings)))

    # logging.info("get fitted variables")
    fit_vars = {}
    for v in variables:
        key = v.name[:v.name.find(':')]
        fit_vars[key] = v.eval()

    print("fit \t" + "\t".join(["%6.4e" % v for v in sess.run(variables)]) + "\t | %f" % np.mean(sess.run(nll)))
<|endoftext|>


<commit_before>__all__ = ["AskString"]

import objc
from Foundation import *
from AppKit import *

# class defined in AskString.xib
class AskStringWindowController(NSWindowController):
    questionLabel = objc.IBOutlet()
    textField = objc.IBOutlet()

    def __new__(cls, question, resultCallback, default="", parentWindow=None):
        self = cls.alloc().initWithWindowNibName_("AskString")
        self.question = question
        self.resultCallback = resultCallback
        self.default = default
        self.parentWindow = parentWindow
        if self.parentWindow is None:
            self.window().setFrameUsingName_("AskStringPanel")
            self.setWindowFrameAutosaveName_("AskStringPanel")
            self.showWindow_(self)
        else:
            NSApp().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(
                self.window(), self.parentWindow, None, None, 0)
        self.retain()
        return self

    def windowWillClose_(self, notification):
        self.autorelease()

    def awakeFromNib(self):
        self.questionLabel.setStringValue_(self.question)
        self.textField.setStringValue_(self.default)

    def done(self):
        if self.parentWindow is None:
            self.close()
        else:
            sheet = self.window()
            NSApp().endSheet_(sheet)
            sheet.orderOut_(self)

    def ok_(self, sender):
        value = self.textField.stringValue()
        self.done()
        self.resultCallback(value)

    def cancel_(self, sender):
        self.done()
        self.resultCallback(None)

def AskString(question, resultCallback, default="", parentWindow=None):
    AskStringWindowController(question, resultCallback, default, parentWindow)
<commit_msg>Killed (last?) 'from AppKit/Foundation import *' instance.<commit_after>__all__ = ["AskString"]

import objc

import Foundation

import AppKit
NSApp = AppKit.NSApp
# class defined in AskString.xib
class AskStringWindowController(AppKit.NSWindowController):
    questionLabel = objc.IBOutlet()
    textField = objc.IBOutlet()

    def __new__(cls, question, resultCallback, default="", parentWindow=None):
        self = cls.alloc().initWithWindowNibName_("AskString")
        self.question = question
        self.resultCallback = resultCallback
        self.default = default
        self.parentWindow = parentWindow
        if self.parentWindow is None:
            self.window().setFrameUsingName_("AskStringPanel")
            self.setWindowFrameAutosaveName_("AskStringPanel")
            self.showWindow_(self)
        else:
            NSApp().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(
                self.window(), self.parentWindow, None, None, 0)
        self.retain()
        return self

    def windowWillClose_(self, notification):
        self.autorelease()

    def awakeFromNib(self):
        self.questionLabel.setStringValue_(self.question)
        self.textField.setStringValue_(self.default)

    def done(self):
        if self.parentWindow is None:
            self.close()
        else:
            sheet = self.window()
            NSApp().endSheet_(sheet)
            sheet.orderOut_(self)

    def ok_(self, sender):
        value = self.textField.stringValue()
        self.done()
        self.resultCallback(value)

    def cancel_(self, sender):
        self.done()
        self.resultCallback(None)

def AskString(question, resultCallback, default="", parentWindow=None):
    AskStringWindowController(question, resultCallback, default, parentWindow)
<|endoftext|>