<commit_before>from keras.layers import Activation, Convolution2D, Dropout, Conv2D
from keras.layers import AveragePooling2D, BatchNormalization
from keras.layers import GlobalAveragePooling2D
from keras.models import Sequential
from keras.layers import Flatten
from keras.models import Model
from keras.layers import Input
from keras.layers import MaxPooling2D
from keras.layers import SeparableConv2D
from keras import layers
from keras.regularizers import l2

def simple_CNN(input_shape, num_classes):

    model = Sequential()
    model.add(Convolution2D(filters=16, kernel_size=(7, 7), padding='same',
                            name='image_array', input_shape=input_shape))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=16, kernel_size=(7, 7), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=32, kernel_size=(5, 5), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=32, kernel_size=(5, 5), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=64, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=64, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=128, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=128, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=256, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=num_classes, kernel_size=(3, 3), padding='same'))
    model.add(GlobalAveragePooling2D())
    model.add(Activation('softmax',name='predictions'))
    return model

def simpler_CNN(input_shape, num_classes):

    model = Sequential()
    model.add(Convolution2D(filters=16, kernel_size=(5, 5), padding='same',
                            name='image_array', input_shape=input_shape))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=16, kernel_size=(5, 5),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=32, kernel_size=(5, 5), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=32, kernel_size=(5, 5),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=64, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=64, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=64, kernel_size=(1, 1), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=128, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=256, kernel_size=(1, 1), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=128, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))

    model.add(Convolution2D(filters=256, kernel_size=(1, 1), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=num_classes, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))

    model.add(Flatten())
    #model.add(GlobalAveragePooling2D())
    model.add(Activation('softmax',name='predictions'))
    return model

def mini_XCEPTION(input_shape, num_classes, l2_regularization=0.01):
    regularization = l2(l2_regularization)

    # base
    img_input = Input(input_shape)
    x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
                                            use_bias=False)(img_input)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
                                            use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)

    # module 1
    residual = Conv2D(16, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(16, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(16, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 2
    residual = Conv2D(32, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(32, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(32, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 3
    residual = Conv2D(64, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(64, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(64, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 4
    residual = Conv2D(128, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(128, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(128, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    x = Conv2D(num_classes, (3, 3),
            #kernel_regularizer=regularization,
            padding='same')(x)
    x = GlobalAveragePooling2D()(x)
    output = Activation('softmax',name='predictions')(x)

    model = Model(img_input, output)
    return model

def big_XCEPTION(input_shape, num_classes):
    img_input = Input(input_shape)
    x = Conv2D(32, (3, 3), strides=(2, 2), use_bias=False)(img_input)
    x = BatchNormalization(name='block1_conv1_bn')(x)
    x = Activation('relu', name='block1_conv1_act')(x)
    x = Conv2D(64, (3, 3), use_bias=False)(x)
    x = BatchNormalization(name='block1_conv2_bn')(x)
    x = Activation('relu', name='block1_conv2_act')(x)

    residual = Conv2D(128, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(128, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block2_sepconv1_bn')(x)
    x = Activation('relu', name='block2_sepconv2_act')(x)
    x = SeparableConv2D(128, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block2_sepconv2_bn')(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    residual = Conv2D(256, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = Activation('relu', name='block3_sepconv1_act')(x)
    x = SeparableConv2D(256, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block3_sepconv1_bn')(x)
    x = Activation('relu', name='block3_sepconv2_act')(x)
    x = SeparableConv2D(256, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block3_sepconv2_bn')(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])
    x = Conv2D(num_classes, (3, 3),
            #kernel_regularizer=regularization,
            padding='same')(x)
    x = GlobalAveragePooling2D()(x)
    output = Activation('softmax',name='predictions')(x)

    model = Model(img_input, output)
    return model

if __name__ == "__main__":
    model = mini_XCEPTION((48, 48, 1), 7)
    model.summary()
    model = big_XCEPTION((64, 64, 1), 7)
    model.summary()
<commit_msg>Added new tiny XCEPTION inspired model<commit_after>from keras.layers import Activation, Convolution2D, Dropout, Conv2D
from keras.layers import AveragePooling2D, BatchNormalization
from keras.layers import GlobalAveragePooling2D
from keras.models import Sequential
from keras.layers import Flatten
from keras.models import Model
from keras.layers import Input
from keras.layers import MaxPooling2D
from keras.layers import SeparableConv2D
from keras import layers
from keras.regularizers import l2

def simple_CNN(input_shape, num_classes):

    model = Sequential()
    model.add(Convolution2D(filters=16, kernel_size=(7, 7), padding='same',
                            name='image_array', input_shape=input_shape))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=16, kernel_size=(7, 7), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=32, kernel_size=(5, 5), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=32, kernel_size=(5, 5), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=64, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=64, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=128, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=128, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))
    model.add(Dropout(.5))

    model.add(Convolution2D(filters=256, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=num_classes, kernel_size=(3, 3), padding='same'))
    model.add(GlobalAveragePooling2D())
    model.add(Activation('softmax',name='predictions'))
    return model

def simpler_CNN(input_shape, num_classes):

    model = Sequential()
    model.add(Convolution2D(filters=16, kernel_size=(5, 5), padding='same',
                            name='image_array', input_shape=input_shape))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=16, kernel_size=(5, 5),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=32, kernel_size=(5, 5), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=32, kernel_size=(5, 5),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=64, kernel_size=(3, 3), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=64, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=64, kernel_size=(1, 1), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=128, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(.25))

    model.add(Convolution2D(filters=256, kernel_size=(1, 1), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=128, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))

    model.add(Convolution2D(filters=256, kernel_size=(1, 1), padding='same'))
    model.add(BatchNormalization())
    model.add(Convolution2D(filters=num_classes, kernel_size=(3, 3),
                            strides=(2, 2), padding='same'))

    model.add(Flatten())
    #model.add(GlobalAveragePooling2D())
    model.add(Activation('softmax',name='predictions'))
    return model

def tiny_XCEPTION(input_shape, num_classes, l2_regularization=0.01):
    regularization = l2(l2_regularization)

    # base
    img_input = Input(input_shape)
    x = Conv2D(5, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
                                            use_bias=False)(img_input)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = Conv2D(5, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
                                            use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)

    # module 1
    residual = Conv2D(8, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(8, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(8, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 2
    residual = Conv2D(16, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(16, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(16, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 3
    residual = Conv2D(32, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(32, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(32, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 4
    residual = Conv2D(64, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(64, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(64, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    x = Conv2D(num_classes, (3, 3),
            #kernel_regularizer=regularization,
            padding='same')(x)
    x = GlobalAveragePooling2D()(x)
    output = Activation('softmax',name='predictions')(x)

    model = Model(img_input, output)
    return model

def mini_XCEPTION(input_shape, num_classes, l2_regularization=0.01):
    regularization = l2(l2_regularization)

    # base
    img_input = Input(input_shape)
    x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
                                            use_bias=False)(img_input)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = Conv2D(8, (3, 3), strides=(1, 1), kernel_regularizer=regularization,
                                            use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)

    # module 1
    residual = Conv2D(16, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(16, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(16, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 2
    residual = Conv2D(32, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(32, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(32, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 3
    residual = Conv2D(64, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(64, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(64, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 4
    residual = Conv2D(128, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(128, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(128, (3, 3), padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    x = Conv2D(num_classes, (3, 3),
            #kernel_regularizer=regularization,
            padding='same')(x)
    x = GlobalAveragePooling2D()(x)
    output = Activation('softmax',name='predictions')(x)

    model = Model(img_input, output)
    return model

def big_XCEPTION(input_shape, num_classes):
    img_input = Input(input_shape)
    x = Conv2D(32, (3, 3), strides=(2, 2), use_bias=False)(img_input)
    x = BatchNormalization(name='block1_conv1_bn')(x)
    x = Activation('relu', name='block1_conv1_act')(x)
    x = Conv2D(64, (3, 3), use_bias=False)(x)
    x = BatchNormalization(name='block1_conv2_bn')(x)
    x = Activation('relu', name='block1_conv2_act')(x)

    residual = Conv2D(128, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(128, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block2_sepconv1_bn')(x)
    x = Activation('relu', name='block2_sepconv2_act')(x)
    x = SeparableConv2D(128, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block2_sepconv2_bn')(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    residual = Conv2D(256, (1, 1), strides=(2, 2),
                      padding='same', use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = Activation('relu', name='block3_sepconv1_act')(x)
    x = SeparableConv2D(256, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block3_sepconv1_bn')(x)
    x = Activation('relu', name='block3_sepconv2_act')(x)
    x = SeparableConv2D(256, (3, 3), padding='same', use_bias=False)(x)
    x = BatchNormalization(name='block3_sepconv2_bn')(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])
    x = Conv2D(num_classes, (3, 3),
            #kernel_regularizer=regularization,
            padding='same')(x)
    x = GlobalAveragePooling2D()(x)
    output = Activation('softmax',name='predictions')(x)

    model = Model(img_input, output)
    return model

if __name__ == "__main__":
    input_shape = (64, 64, 1)
    num_classes = 7
    model = tiny_XCEPTION(input_shape, num_classes)
    model.summary()
    model = mini_XCEPTION(input_shape, num_classes)
    model.summary()
    model = big_XCEPTION(input_shape, num_classes)
    model.summary()
<|endoftext|>


<commit_before>#
# Calculates the co-ordinates along great arcs between two specified points
# which are assumed to be on disk.
#
from __future__ import absolute_import, division, print_function

import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from sunpy.coordinates import frames

class GreatArc:
    """
    Calculate a user-specified number of points on a great arc between a start
    and end point on a sphere.

    Parameters
    ----------
    start : `~astropy.coordinates.SkyCoord`
        Start point.

    end : `~astropy.coordinates.SkyCoord`
        End point.

    center : `~astropy.coordinates.SkyCoord`
        Center of the sphere.

    points : None | int | numpy.ndarray
        Number of points along the great arc.

    Returns
    -------
    arc : `~astropy.coordinates.SkyCoord`
        Co-ordinates along the great arc in the co-ordinate frame of the
        start point.

    Example
    -------
    >>> import matplotlib.pyplot as plt
    >>> from astropy.coordinates import SkyCoord
    >>> import astropy.units as u
    >>> from sunpy.coordinates.great_arc import GreatArc
    >>> import sunpy.map
    >>> from sunpy.data.sample import AIA_171_IMAGE
    >>> m = sunpy.map.Map(AIA_171_IMAGE)
    >>> a = SkyCoord(600*u.arcsec, -600*u.arcsec, frame=m.coordinate_frame)
    >>> b = SkyCoord(-100*u.arcsec, 800*u.arcsec, frame=m.coordinate_frame)
    >>> v = GreatArc(a, b)
    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(1, 1, 1, projection=m)
    >>> m.plot(axes=ax)
    >>> ax.plot_coord(v.coordinates(), color='c')
    >>> plt.show()

    """
    def __init__(self, start, end, center=None, points=None):
        # Start point of the great arc
        self.start = start

        # End point of the great arc
        self.end = end

        # Parameterized location of points between the start and the end of the
        # great arc.
        # Default parameterized points location.
        self._default_points = np.linspace(0, 1, 100)

        # If the user requests a different set of default parameterized points
        # on initiation of the object, then these become the default.  This
        # allows the user to use the methods without having to specify their
        # choice of points over and over again, while also allowing the
        # flexibility in the methods to calculate other values.
        self._default_points = self._points_handler(points)

        # Units of the start point
        self.distance_unit = self.start.transform_to(frames.Heliocentric).cartesian.xyz.unit

        # Co-ordinate frame
        self.start_frame = self.start.frame

        #
        self.observer = self.start.observer

        # Set the center of the sphere
        if center is None:
            self.center = SkyCoord(0*self.distance_unit,
                                   0*self.distance_unit,
                                   0*self.distance_unit, frame=frames.Heliocentric)

        # Convert the start, end and center points to their Cartesian values
        self.start_cartesian = self.start.transform_to(frames.Heliocentric).cartesian.xyz.to(self.distance_unit).value
        self.end_cartesian = self.end.transform_to(frames.Heliocentric).cartesian.xyz.to(self.distance_unit).value
        self.center_cartesian = self.center.transform_to(frames.Heliocentric).cartesian.xyz.to(self.distance_unit).value

        # Great arc properties calculation
        # Vector from center to first point
        self.v1 = self.start_cartesian - self.center_cartesian

        # Distance of the first point from the center
        self.r = np.linalg.norm(self.v1)

        # Vector from center to second point
        self.v2 = self.end_cartesian - self.center_cartesian

        # The v3 vector lies in plane of v1 & v2 and is orthogonal to v1
        self.v3 = np.cross(np.cross(self.v1, self.v2), self.v1)
        self.v3 = self.r * self.v3 / np.linalg.norm(self.v3)

        # Inner angle between v1 and v2 in radians
        self._inner_angle = np.arctan2(np.linalg.norm(np.cross(self.v1, self.v2)),
                                      np.dot(self.v1, self.v2))

        # Inner angle between v1 and v2 in degrees
        self.inner_angle = np.rad2deg(self._inner_angle) * u.degree

        # Distance on the sphere between the start point and the end point.
        self.distance = self.r * self._inner_angle * self.distance_unit

    def _points_handler(self, points):
        """
        Interprets the points keyword.
        """
        if points is None:
            return self._default_points
        elif isinstance(points, int):
            return np.linspace(0, 1, points)
        elif isinstance(points, np.ndarray):
            if points.ndim > 1:
                return ValueError('One dimensional numpy ndarrays only.')
            if np.any(points < 0) or np.any(points) > 1:
                return ValueError('All value in points array must be strictly >=0 and <=1.')
            return points

    def _calculate_inner_angles(self, points=None):
        """
        Calculates the inner angles for the parameterized points along the arc
        and returns the value in radians, from the start co-ordinate to the
        end.
        """
        these_points = self._points_handler(points)
        return these_points.reshape(len(these_points), 1)*self._inner_angle

    def inner_angles(self, points=None):
        """
        Calculates the inner angles from the start co-ordinate to the end, for
        the parameterized points along the arc.  Values are returned in
        degrees.
        """
        return np.rad2deg(self._calculate_inner_angles(points=points)) * u.degree

    def distances(self, points=None):
        """
        Calculates the distance from the start co-ordinate to the end
        co-ordinate on the sphere for all the parameterized points.
        """
        return self.r * self._calculate_inner_angles(points=points) * self.distance_unit

    def coordinates(self, points=None):
        """
        Calculates the co-ordinates on the sphere from the start to the end
        co-ordinate for all the parameterized points.  Co-ordinates are
        returned in the frame of the start coordinate.
        """
        # Calculate the inner angles
        these_inner_angles = self._calculate_inner_angles(points=points)

        # Calculate the Cartesian locations from the first to second points
        great_arc_points_cartesian = (self.v1[np.newaxis, :] * np.cos(these_inner_angles) +
                                      self.v3[np.newaxis, :] * np.sin(these_inner_angles) +
                                      self.center_cartesian) * self.distance_unit

        # Return the coordinates of the great arc between the start and end
        # points
        return SkyCoord(great_arc_points_cartesian[:, 0],
                        great_arc_points_cartesian[:, 1],
                        great_arc_points_cartesian[:, 2],
                        frame=frames.Heliocentric, observer=self.observer).transform_to(self.start_frame)
<commit_msg>using radians as units cleans up code<commit_after>#
# Calculates the co-ordinates along great arcs between two specified points
# which are assumed to be on disk.
#
from __future__ import absolute_import, division, print_function

import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from sunpy.coordinates import frames

class GreatArc:
    """
    Calculate a user-specified number of points on a great arc between a start
    and end point on a sphere.

    Parameters
    ----------
    start : `~astropy.coordinates.SkyCoord`
        Start point.

    end : `~astropy.coordinates.SkyCoord`
        End point.

    center : `~astropy.coordinates.SkyCoord`
        Center of the sphere.

    points : None | int | numpy.ndarray
        Number of points along the great arc.

    Returns
    -------
    arc : `~astropy.coordinates.SkyCoord`
        Co-ordinates along the great arc in the co-ordinate frame of the
        start point.

    Example
    -------
    >>> import matplotlib.pyplot as plt
    >>> from astropy.coordinates import SkyCoord
    >>> import astropy.units as u
    >>> from sunpy.coordinates.great_arc import GreatArc
    >>> import sunpy.map
    >>> from sunpy.data.sample import AIA_171_IMAGE
    >>> m = sunpy.map.Map(AIA_171_IMAGE)
    >>> a = SkyCoord(600*u.arcsec, -600*u.arcsec, frame=m.coordinate_frame)
    >>> b = SkyCoord(-100*u.arcsec, 800*u.arcsec, frame=m.coordinate_frame)
    >>> v = GreatArc(a, b)
    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(1, 1, 1, projection=m)
    >>> m.plot(axes=ax)
    >>> ax.plot_coord(v.coordinates(), color='c')
    >>> plt.show()

    """
    def __init__(self, start, end, center=None, points=None):
        # Start point of the great arc
        self.start = start

        # End point of the great arc
        self.end = end

        # Parameterized location of points between the start and the end of the
        # great arc.
        # Default parameterized points location.
        self._default_points = np.linspace(0, 1, 100)

        # If the user requests a different set of default parameterized points
        # on initiation of the object, then these become the default.  This
        # allows the user to use the methods without having to specify their
        # choice of points over and over again, while also allowing the
        # flexibility in the methods to calculate other values.
        self._default_points = self._points_handler(points)

        # Units of the start point
        self.distance_unit = self.start.transform_to(frames.Heliocentric).cartesian.xyz.unit

        # Co-ordinate frame
        self.start_frame = self.start.frame

        #
        self.observer = self.start.observer

        # Set the center of the sphere
        if center is None:
            self.center = SkyCoord(0*self.distance_unit,
                                   0*self.distance_unit,
                                   0*self.distance_unit, frame=frames.Heliocentric)

        # Convert the start, end and center points to their Cartesian values
        self.start_cartesian = self.start.transform_to(frames.Heliocentric).cartesian.xyz.to(self.distance_unit).value
        self.end_cartesian = self.end.transform_to(frames.Heliocentric).cartesian.xyz.to(self.distance_unit).value
        self.center_cartesian = self.center.transform_to(frames.Heliocentric).cartesian.xyz.to(self.distance_unit).value

        # Great arc properties calculation
        # Vector from center to first point
        self.v1 = self.start_cartesian - self.center_cartesian

        # Distance of the first point from the center
        self.r = np.linalg.norm(self.v1)

        # Vector from center to second point
        self.v2 = self.end_cartesian - self.center_cartesian

        # The v3 vector lies in plane of v1 & v2 and is orthogonal to v1
        self.v3 = np.cross(np.cross(self.v1, self.v2), self.v1)
        self.v3 = self.r * self.v3 / np.linalg.norm(self.v3)

        # Inner angle between v1 and v2 in radians
        self.inner_angle = np.arctan2(np.linalg.norm(np.cross(self.v1, self.v2)),
                                      np.dot(self.v1, self.v2)) * u.rad

        # Distance on the sphere between the start point and the end point.
        self.distance = self.r * self.inner_angle.value * self.distance_unit

    def _points_handler(self, points):
        """
        Interprets the points keyword.
        """
        if points is None:
            return self._default_points
        elif isinstance(points, int):
            return np.linspace(0, 1, points)
        elif isinstance(points, np.ndarray):
            if points.ndim > 1:
                return ValueError('One dimensional numpy ndarrays only.')
            if np.any(points < 0) or np.any(points) > 1:
                return ValueError('All value in points array must be strictly >=0 and <=1.')
            return points

    def _calculate_inner_angles(self, points=None):
        """
        Calculates the inner angles for the parameterized points along the arc
        and returns the value in radians, from the start co-ordinate to the
        end.
        """
        these_points = self._points_handler(points)
        return these_points.reshape(len(these_points), 1)*self.inner_angle

    def inner_angles(self, points=None):
        """
        Calculates the inner angles from the start co-ordinate to the end, for
        the parameterized points along the arc.  Values are returned in
        degrees.
        """
        return self._calculate_inner_angles(points=points)

    def distances(self, points=None):
        """
        Calculates the distance from the start co-ordinate to the end
        co-ordinate on the sphere for all the parameterized points.
        """
        return self.r * self._calculate_inner_angles(points=points).value * self.distance_unit

    def coordinates(self, points=None):
        """
        Calculates the co-ordinates on the sphere from the start to the end
        co-ordinate for all the parameterized points.  Co-ordinates are
        returned in the frame of the start coordinate.
        """
        # Calculate the inner angles
        these_inner_angles = self._calculate_inner_angles(points=points)

        # Calculate the Cartesian locations from the first to second points
        great_arc_points_cartesian = (self.v1[np.newaxis, :] * np.cos(these_inner_angles) +
                                      self.v3[np.newaxis, :] * np.sin(these_inner_angles) +
                                      self.center_cartesian) * self.distance_unit

        # Return the coordinates of the great arc between the start and end
        # points
        return SkyCoord(great_arc_points_cartesian[:, 0],
                        great_arc_points_cartesian[:, 1],
                        great_arc_points_cartesian[:, 2],
                        frame=frames.Heliocentric, observer=self.observer).transform_to(self.start_frame)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from lettuce import *
from splinter import Browser
from lettuce.django import django_url
from django.core.management import call_command
from survey.models import Backend
from django.conf import settings
from django.contrib.auth.models import User, Group, Permission
from django.template.defaultfilters import slugify
import glob, os

@before.each_scenario
def flush_database(step):
    call_command('flush', interactive=False)
    create_backends()

@before.all
def clear_screenshots():
    screenshots = glob.glob('./screenshots/*.png')
    for screenshot in screenshots:
        os.remove(screenshot)
    open_browser()

def open_browser():
    world.browser = Browser("chrome")

@after.each_scenario
def take_screenshot(scenario):
    if scenario.failed:
        world.browser.driver.save_screenshot('screenshots/%s.png' % slugify(scenario.name))

@after.each_scenario
def clear_cookies(scenario):
    world.browser.cookies.delete()

@after.all
def close_browser(total):
    world.browser.quit()

def create_backends():
    for backend in settings.INSTALLED_BACKENDS.keys():
        Backend.objects.get_or_create(name=backend)<commit_msg>reverted to phantomjs<commit_after># -*- coding: utf-8 -*-
from lettuce import *
from splinter import Browser
from lettuce.django import django_url
from django.core.management import call_command
from survey.models import Backend
from django.conf import settings
from django.contrib.auth.models import User, Group, Permission
from django.template.defaultfilters import slugify
import glob, os

@before.each_scenario
def flush_database(step):
    call_command('flush', interactive=False)
    create_backends()

@before.all
def clear_screenshots():
    screenshots = glob.glob('./screenshots/*.png')
    for screenshot in screenshots:
        os.remove(screenshot)
    open_browser()

def open_browser():
    world.browser = Browser("phantomjs")

@after.each_scenario
def take_screenshot(scenario):
    if scenario.failed:
        world.browser.driver.save_screenshot('screenshots/%s.png' % slugify(scenario.name))

@after.each_scenario
def clear_cookies(scenario):
    world.browser.cookies.delete()

@after.all
def close_browser(total):
    world.browser.quit()

def create_backends():
    for backend in settings.INSTALLED_BACKENDS.keys():
        Backend.objects.get_or_create(name=backend)<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Daniel Zhang (張道博)'

import sys
import logging

class MSGLogger(object):
    """
    This class provides logging functionality.
    """

    def __init__(self, caller, level):
        """
        Constructor.

        :params caller: Calling class.
        """

        self.logger = logging.getLogger(caller)

        # Messages equal to and above the logging level will be logged.
        self.logger.setLevel(logging.DEBUG)

        self.streamHandler = logging.StreamHandler(sys.stderr)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.streamHandler.setFormatter(formatter)

        self.loggerLevel = None
        if level == 'info':
            self.loggerLevel = logging.INFO
        elif level == 'error':
            self.loggerLevel = logging.ERROR
        elif level == 'silent':
            self.loggerLevel = None
        elif level == 'debug':
            self.loggerLevel = logging.DEBUG
        else:
            self.loggerLevel = None

        recordedLog = ''

    def logAndWrite(self, message):
        """
        With a given string, write it to stderr and return its value for
        appending to a running log.

        Nothing is added to the message. Therefore, if linefeeds are desired
        they should be included explicitly.

        :param message: A string message to be logged.
        :returns: The message.
        """

        sys.stderr.write(message)
        return message

    def log(self, message, level = None):
        """
        Write a log message.

        Logging levels are

        * info
        * debug
        * error
        * silent

        :params message: A message to be logged.
        :params level: (optional) Logging level.
        """

        self.logger.addHandler(self.streamHandler)
        loggerLevel = None
        if level == 'info':
            loggerLevel = logging.INFO
        elif level == 'debug':
            loggerLevel = logging.DEBUG
        elif level == 'error':
            loggerLevel = logging.ERROR
        elif level == 'silent':
            loggerLevel = None
        else:
            loggerLevel = self.loggerLevel

        if loggerLevel != None:
            self.logger.log(loggerLevel, message)
            self.logger.removeHandler(self.streamHandler)
            # self.streamHandler.flush()

    def startRecording(self):
        pass

    def endRecording(self):
        pass
<commit_msg>make logger parameter case insensitive<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Daniel Zhang (張道博)'

import sys
import logging

class MSGLogger(object):
    """
    This class provides logging functionality.
    """

    def __init__(self, caller, level):
        """
        Constructor.

        :params caller: Calling class.
        """

        self.logger = logging.getLogger(caller)

        # Messages equal to and above the logging level will be logged.
        self.logger.setLevel(logging.DEBUG)

        self.streamHandler = logging.StreamHandler(sys.stderr)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.streamHandler.setFormatter(formatter)

        self.loggerLevel = None
        level = level.lower()
        if level == 'info':
            self.loggerLevel = logging.INFO
        elif level == 'error':
            self.loggerLevel = logging.ERROR
        elif level == 'silent':
            self.loggerLevel = None
        elif level == 'debug':
            self.loggerLevel = logging.DEBUG
        else:
            self.loggerLevel = None

        recordedLog = ''

    def logAndWrite(self, message):
        """
        With a given string, write it to stderr and return its value for
        appending to a running log.

        Nothing is added to the message. Therefore, if linefeeds are desired
        they should be included explicitly.

        :param message: A string message to be logged.
        :returns: The message.
        """

        sys.stderr.write(message)
        return message

    def log(self, message, level = None):
        """
        Write a log message.

        Logging levels are

        * info
        * debug
        * error
        * silent

        :params message: A message to be logged.
        :params level: (optional) Logging level.
        """

        self.logger.addHandler(self.streamHandler)
        loggerLevel = None
        if level == 'info':
            loggerLevel = logging.INFO
        elif level == 'debug':
            loggerLevel = logging.DEBUG
        elif level == 'error':
            loggerLevel = logging.ERROR
        elif level == 'silent':
            loggerLevel = None
        else:
            loggerLevel = self.loggerLevel

        if loggerLevel != None:
            self.logger.log(loggerLevel, message)
            self.logger.removeHandler(self.streamHandler)
            # self.streamHandler.flush()

    def startRecording(self):
        pass

    def endRecording(self):
        pass
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    naivebayes.py
    naivebayes classifier
"""
from logging import getLogger, StreamHandler, DEBUG
#
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import scale
from janome.tokenizer import Tokenizer
#
from serializer import Serializer
from ocrengine import OCREngine

# pylint: disable=C0103
logger = getLogger('myapp.tweetbot')
if __name__ == "__main__":
    handler = StreamHandler()
    handler.setLevel(DEBUG)
    logger.setLevel(DEBUG)
    logger.addHandler(handler)

class ModelValidator(object):
    def __init__(self, data, target):
        self.data = data
        self.target = target
        self.cv = 2
    def search_BestParameter(self, test_model, params):
        """
            model search_best_parameter
            @param  test_model
            @return {dict}best_params_
        """
        grid = GridSearchCV(test_model, params, cv=self.cv)
        grid.fit(self.data, self.target)
        logger.info('best %s', grid.best_estimator_)
        return grid.best_params_
    def cross_validation(self, test_model):
        """
            model cross validation check
            @param  test_model
        """
        #raise DeprecationWarning()
        scores = cross_val_score(test_model, self.data, self.target, cv=self.cv)
        logger.info('cross_validation:%s', np.mean(scores))
        return

class NaiveBayes(object):
    """
        NaiveBayes Classifier.
        use sklearn.naive_bayes.MultinomialNB
        << preprocessing >>
            corpus => NaiveBayes#tokenizer
            NaiveBayes#tokenizer := word => {Word segmentation}token
        □model　training
            token => vectorizer#fit_transform => model#fit
        □predict
            token => vectorizer#transform => model#predict
    """
    def __init__(self, skip_tokenize=5):
        self.skip_tokenize = skip_tokenize
        self.skip_count = 0
        self.t = Tokenizer()
       # self.pipeline = Pipeline([
       #         ('vectorizer', TfidfVectorizer(tokenizer=self.tokenizer)),
       #         ('classifier', MultinomialNB(0.3))])
        self.pipeline = Pipeline([
                ('vectorizer', TfidfVectorizer(tokenizer=self.tokenizer)),
                ('classifier', self.create_Model())])

        corpus = Serializer.load_csv('../resource/corpus.tsv')
        self.data = []
        target = []
        for row in corpus:
            self.data.append(str(row[0]))
            target.append(int(row[1]))
        self.labels = np.array(target, dtype=np.uint8, ndmin=1)
        self.pipeline.fit(self.data, self.labels)
        #logger.debug(self.vectorizer.get_feature_names())
    def tokenizer(self, word):
        """
            caller fit_transform / transform
            @param {string} word
            @yield {list.<string>}
                    result := token | space | token
        """
        if self.skip_count < self.skip_tokenize:
            self.skip_count += 1
            print(word)
            yield word
            return
        tokens = []
        for token in self.t.tokenize(word):
            if not str(token.part_of_speech).startswith('名詞'):
                pass
            tokens.append(token.surface)
        yield " ".join(tokens)
    @property
    def model(self):
        """
            @return {Classifier}
        """
        return self.pipeline.named_steps['classifier']
    @property
    def vectorizer(self):
        """
            @return {Vectorizer}
        """
        return self.pipeline.named_steps['vectorizer']
    def predict(self, x):
        """
            predict params x
            @param {string},{np.array} x
            @return result
        """
        if isinstance(x, str):
            x = self.vectorizer.transform([x])

        #logger.debug(self.model.predict_proba(x))
        return self.model.predict(x)
    def predict_all(self, x_list, pair):
        """
            mapping
            @param {list} x_list
                   {dict} pair
            @return {list} value
        """
        result = []
        for x in x_list:
            predicted = self.predict(x)[0]
            value = pair[str(predicted)]
            result.append(value)
            logger.debug('%s -> 推定: %s', x, value)
        assert len(result) == len(x_list)
        return result
    def model_validation(self):
        x_train = self.vectorizer.fit_transform(self.data)
        validator = ModelValidator(x_train, self.labels)
        validator.cross_validation(self.model)
        test_params = self.model.get_params
        params = {}
        params['alpha'] = np.logspace(-1, 2, 30)
        params['fit_prior'] = [True, False]
        best_params = validator.search_BestParameter(self.create_Model(), params)
        validator.cross_validation(self.create_Model(best_params))
    def create_Model(self, params=None):
        model = MultinomialNB()
        #model = LinearSVC(C=0.1)
        if params is not None:
            model.set_params(**params)
        return model
def main():
    ocr = OCREngine()
    temp_file_name = '../base_binary.png'
    doc = ocr.recognize(temp_file_name)
    doc.dump()
    x_list = doc.names()
    x_list.append('エルソード王国')
    logger.info(x_list)
    #np.set_printoptions(precision=4)
    naivebayes = NaiveBayes()
    out = naivebayes.predict_all(x_list, doc.countries)
    logger.info('out:%s', out)
    x_list = ['ホルデイン王国', '力セドー丿ア連合王国', 'ゲブ「ラン ド帝国']
    out = naivebayes.predict_all(x_list, doc.countries)
    logger.info('out:%s', out)
    naivebayes.model_validation()
if __name__ == "__main__":
    main()
<commit_msg>add GridSearchCV#n_jobs<commit_after># -*- coding: utf-8 -*-
"""
    naivebayes.py
    naivebayes classifier
"""
from logging import getLogger, StreamHandler, DEBUG
#
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import scale
from janome.tokenizer import Tokenizer
#
from serializer import Serializer
from ocrengine import OCREngine

# pylint: disable=C0103
logger = getLogger('myapp.tweetbot')
if __name__ == "__main__":
    handler = StreamHandler()
    handler.setLevel(DEBUG)
    logger.setLevel(DEBUG)
    logger.addHandler(handler)

class ModelValidator(object):
    def __init__(self, data, target):
        self.data = data
        self.target = target
        self.cv = 4
        self.n_jobs = -1
    def search_BestParameter(self, test_model, params):
        """
            model search_best_parameter
            @param  test_model
            @return {dict}best_params_
        """
        grid = GridSearchCV(test_model, params, cv=self.cv, n_jobs=self.n_jobs)
        grid.fit(self.data, self.target)
        logger.info('best %s', grid.best_estimator_)
        return grid.best_params_
    def cross_validation(self, test_model):
        """
            model cross validation check
            @param  test_model
        """
        #raise DeprecationWarning()
        scores = cross_val_score(test_model, self.data, self.target, cv=self.cv)
        logger.info('cross_validation:%s', np.mean(scores))
        return

class NaiveBayes(object):
    """
        NaiveBayes Classifier.
        use sklearn.naive_bayes.MultinomialNB
        << preprocessing >>
            corpus => NaiveBayes#tokenizer
            NaiveBayes#tokenizer := word => {Word segmentation}token
        □model　training
            token => vectorizer#fit_transform => model#fit
        □predict
            token => vectorizer#transform => model#predict
    """
    def __init__(self, skip_tokenize=5):
        self.skip_tokenize = skip_tokenize
        self.skip_count = 0
        self.t = Tokenizer()
       # self.pipeline = Pipeline([
       #         ('vectorizer', TfidfVectorizer(tokenizer=self.tokenizer)),
       #         ('classifier', MultinomialNB(0.3))])
        self.pipeline = Pipeline([
                ('vectorizer', TfidfVectorizer(tokenizer=self.tokenizer)),
                ('classifier', self.create_Model())])

        corpus = Serializer.load_csv('../resource/corpus.tsv')
        self.data = []
        target = []
        for row in corpus:
            self.data.append(str(row[0]))
            target.append(int(row[1]))
        self.labels = np.array(target, dtype=np.uint8, ndmin=1)
        self.pipeline.fit(self.data, self.labels)
        #logger.debug(self.vectorizer.get_feature_names())
    def tokenizer(self, word):
        """
            caller fit_transform / transform
            @param {string} word
            @yield {list.<string>}
                    result := token | space | token
        """
        if self.skip_count < self.skip_tokenize:
            self.skip_count += 1
            print(word)
            yield word
            return
        tokens = []
        for token in self.t.tokenize(word):
            if not str(token.part_of_speech).startswith('名詞'):
                pass
            tokens.append(token.surface)
        yield " ".join(tokens)
    @property
    def model(self):
        """
            @return {Classifier}
        """
        return self.pipeline.named_steps['classifier']
    @property
    def vectorizer(self):
        """
            @return {Vectorizer}
        """
        return self.pipeline.named_steps['vectorizer']
    def predict(self, x):
        """
            predict params x
            @param {string},{np.array} x
            @return result
        """
        if isinstance(x, str):
            x = self.vectorizer.transform([x])

        #logger.debug(self.model.predict_proba(x))
        return self.model.predict(x)
    def predict_all(self, x_list, pair):
        """
            mapping
            @param {list} x_list
                   {dict} pair
            @return {list} value
        """
        result = []
        for x in x_list:
            predicted = self.predict(x)[0]
            value = pair[str(predicted)]
            result.append(value)
            logger.debug('%s -> 推定: %s', x, value)
        assert len(result) == len(x_list)
        return result
    def model_validation(self):
        x_train = self.vectorizer.fit_transform(self.data)
        validator = ModelValidator(x_train, self.labels)
        validator.cross_validation(self.model)
        test_params = self.model.get_params

        params = {}

        params['alpha'] = np.arange(0.01, 3.,step=0.01,dtype=np.float64)
        #params['alpha'] = np.logspace(-1, 2, 30)
        params['fit_prior'] = [True, False]
        best_params = validator.search_BestParameter(self.create_Model(), params)
        validator.cross_validation(self.create_Model(best_params))
    def create_Model(self, params=None):
        model = MultinomialNB(1)
        #model = LinearSVC(C=0.1)
        if params is not None:
            model.set_params(**params)
        return model
def main():
    ocr = OCREngine()
    temp_file_name = '../base_binary.png'
    doc = ocr.recognize(temp_file_name)
    doc.dump()
    x_list = doc.names()
    x_list.append('エルソード王国')
    logger.info(x_list)
    #np.set_printoptions(precision=4)
    naivebayes = NaiveBayes()
    out = naivebayes.predict_all(x_list, doc.countries)
    logger.info('out:%s', out)
    x_list = ['ホルデイン王国', '力セドー丿ア連合王国', 'ゲブ「ラン ド帝国']
    out = naivebayes.predict_all(x_list, doc.countries)
    logger.info('out:%s', out)
    naivebayes.model_validation()
if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>
import json

from tagging.models import Tag

from django.shortcuts import get_object_or_404, render, redirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required, permission_required
from django.http import HttpResponse, HttpResponseForbidden
from django.views.generic import DetailView

from extensions import models
from extensions.forms import UploadScreenshotForm, UploadForm, ExtensionDataForm

def manifest(request, uuid, ver):
    version = get_object_or_404(models.ExtensionVersion, pk=ver)

    url = reverse('extensions-download', kwargs=dict(uuid=uuid, ver=ver))

    manifestdata = version.make_metadata_json()
    manifestdata['__installer'] = request.build_absolute_uri(url)

    return HttpResponse(json.dumps(manifestdata),
                        content_type="application/json")

def download(request, uuid, ver):
    version = get_object_or_404(models.ExtensionVersion, pk=ver)
    return redirect(version.source.url)

class ExtensionLatestVersionView(DetailView):
    model = models.Extension
    context_object_name = "version"
    template_name = "extensions/detail.html"

    def get(self, request, **kwargs):
        # Redirect if we don't match the slug.
        slug = self.kwargs.get('slug')
        self.object = self.get_object()
        if slug == self.object.extension.slug:
            context = self.get_context_data(object=self.object)
            return self.render_to_response(context)

        kwargs = dict(self.kwargs)
        kwargs.update(dict(slug=self.object.extension.slug))
        return redirect('extensions-detail', **kwargs)

    def get_object(self):
        extension = super(ExtensionLatestVersionView, self).get_object()
        return extension.latest_version

class ExtensionVersionView(DetailView):
    model = models.ExtensionVersion
    context_object_name = "version"
    template_name = "extensions/detail.html"

@login_required
def upload_screenshot(request, pk):
    extension = get_object_or_404(models.Extension, pk=pk)
    if request.user.has_perm('extensions.can-modify-data') or extension.creator == request.user:
        pass
    else:
        return HttpResponseForbidden()

    if request.method == 'POST':
        form = UploadScreenshotForm(request.POST, request.FILES)
        if form.is_valid():
            screenshot = form.save(commit=False)
            screenshot.extension = extension
            screenshot.save()

        return redirect('extensions-detail', pk=extension.pk)
    else:
        form = UploadScreenshotForm(initial=dict(extension="FOO"))

    return render(request, 'extensions/upload-screenshot.html', dict(form=form))

@permission_required('extensions.can-modify-tags')
def modify_tag(request, tag):
    uuid = request.GET.get('uuid')
    action = request.GET.get('action')
    extension = get_object_or_404(models.Extension, uuid=uuid)

    if action == 'add':
        Tag.objects.add_tag(extension, tag)
    elif action == 'rm':
        Tag.objects.update_tags(extension, [t for t in extension.tags if t.name != tag])

    return HttpResponse("true" if extension.is_featured() else "false")

@login_required
def upload_file(request, pk):
    if pk is None:
        extension = None
    else:
        extension = models.Extension.objects.get(pk=pk)
        if extension.creator != request.user:
            return HttpResponseForbidden()

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            file_source = form.cleaned_data['source']
            extension, version = models.ExtensionVersion.from_zipfile(file_source, extension)
            extension.creator = request.user
            extension.save()

            version.extension = extension
            version.source = file_source
            version.status = models.STATUS_NEW
            version.save()

            return redirect('extensions-edit-data', pk=version.pk)
    else:
        form = UploadForm()

    return render(request, 'extensions/upload-file.html', dict(form=form))

@login_required
def upload_edit_data(request, pk):
    try:
        version = models.ExtensionVersion.objects.get(pk=pk)
    except models.ExtensionVersion.DoesNotExist:
        return HttpResponseForbidden()

    extension = version.extension
    if version.status in models.REVIEWED_STATUSES:
        return HttpResponseForbidden()

    if (extension.creator != request.user and not \
        request.user.has_perm('extensions.can-modify-data')):
        return HttpResponseForbidden()

    if request.method == 'POST':
        form = ExtensionDataForm(request.POST)
        if form.is_valid():
            extension.name = form.cleaned_data['name']
            extension.description = form.cleaned_data['description']
            extension.url = form.cleaned_data['url']
            extension.save()

            version.replace_metadata_json()
            # XXX: for now until code review happens
            version.status = models.STATUS_ACTIVE
            version.save()

            return redirect('extensions-detail', pk=extension.pk)
    else:
        initial = dict(name=extension.name,
                       description=extension.description,
                       url=extension.url)

        form = ExtensionDataForm(initial=initial)

    return render(request, 'extensions/upload-edit-data.html', dict(form=form))
<commit_msg>Fix a leftover debugging measure.<commit_after>
import json

from tagging.models import Tag

from django.shortcuts import get_object_or_404, render, redirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required, permission_required
from django.http import HttpResponse, HttpResponseForbidden
from django.views.generic import DetailView

from extensions import models
from extensions.forms import UploadScreenshotForm, UploadForm, ExtensionDataForm

def manifest(request, uuid, ver):
    version = get_object_or_404(models.ExtensionVersion, pk=ver)

    url = reverse('extensions-download', kwargs=dict(uuid=uuid, ver=ver))

    manifestdata = version.make_metadata_json()
    manifestdata['__installer'] = request.build_absolute_uri(url)

    return HttpResponse(json.dumps(manifestdata),
                        content_type="application/json")

def download(request, uuid, ver):
    version = get_object_or_404(models.ExtensionVersion, pk=ver)
    return redirect(version.source.url)

class ExtensionLatestVersionView(DetailView):
    model = models.Extension
    context_object_name = "version"
    template_name = "extensions/detail.html"

    def get(self, request, **kwargs):
        # Redirect if we don't match the slug.
        slug = self.kwargs.get('slug')
        self.object = self.get_object()
        if slug == self.object.extension.slug:
            context = self.get_context_data(object=self.object)
            return self.render_to_response(context)

        kwargs = dict(self.kwargs)
        kwargs.update(dict(slug=self.object.extension.slug))
        return redirect('extensions-detail', **kwargs)

    def get_object(self):
        extension = super(ExtensionLatestVersionView, self).get_object()
        return extension.latest_version

class ExtensionVersionView(DetailView):
    model = models.ExtensionVersion
    context_object_name = "version"
    template_name = "extensions/detail.html"

@login_required
def upload_screenshot(request, pk):
    extension = get_object_or_404(models.Extension, pk=pk)
    if request.user.has_perm('extensions.can-modify-data') or extension.creator == request.user:
        pass
    else:
        return HttpResponseForbidden()

    if request.method == 'POST':
        form = UploadScreenshotForm(request.POST, request.FILES)
        if form.is_valid():
            screenshot = form.save(commit=False)
            screenshot.extension = extension
            screenshot.save()

        return redirect('extensions-detail', pk=extension.pk)
    else:
        form = UploadScreenshotForm(initial=dict(extension=extension))

    return render(request, 'extensions/upload-screenshot.html', dict(form=form))

@permission_required('extensions.can-modify-tags')
def modify_tag(request, tag):
    uuid = request.GET.get('uuid')
    action = request.GET.get('action')
    extension = get_object_or_404(models.Extension, uuid=uuid)

    if action == 'add':
        Tag.objects.add_tag(extension, tag)
    elif action == 'rm':
        Tag.objects.update_tags(extension, [t for t in extension.tags if t.name != tag])

    return HttpResponse("true" if extension.is_featured() else "false")

@login_required
def upload_file(request, pk):
    if pk is None:
        extension = None
    else:
        extension = models.Extension.objects.get(pk=pk)
        if extension.creator != request.user:
            return HttpResponseForbidden()

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            file_source = form.cleaned_data['source']
            extension, version = models.ExtensionVersion.from_zipfile(file_source, extension)
            extension.creator = request.user
            extension.save()

            version.extension = extension
            version.source = file_source
            version.status = models.STATUS_NEW
            version.save()

            return redirect('extensions-edit-data', pk=version.pk)
    else:
        form = UploadForm()

    return render(request, 'extensions/upload-file.html', dict(form=form))

@login_required
def upload_edit_data(request, pk):
    try:
        version = models.ExtensionVersion.objects.get(pk=pk)
    except models.ExtensionVersion.DoesNotExist:
        return HttpResponseForbidden()

    extension = version.extension
    if version.status in models.REVIEWED_STATUSES:
        return HttpResponseForbidden()

    if (extension.creator != request.user and not \
        request.user.has_perm('extensions.can-modify-data')):
        return HttpResponseForbidden()

    if request.method == 'POST':
        form = ExtensionDataForm(request.POST)
        if form.is_valid():
            extension.name = form.cleaned_data['name']
            extension.description = form.cleaned_data['description']
            extension.url = form.cleaned_data['url']
            extension.save()

            version.replace_metadata_json()
            # XXX: for now until code review happens
            version.status = models.STATUS_ACTIVE
            version.save()

            return redirect('extensions-detail', pk=extension.pk)
    else:
        initial = dict(name=extension.name,
                       description=extension.description,
                       url=extension.url)

        form = ExtensionDataForm(initial=initial)

    return render(request, 'extensions/upload-edit-data.html', dict(form=form))
<|endoftext|>


<commit_before>import numpy as np

from .results import Results
from .sequences import InfiniteSequence
from .seed import get_seed

class ProbabilitySpace:
    """Defines a probability space.

    Attributes:
      draw (function): A function explaining how to draw one
        outcome from the probability space.
    """

    def __init__(self, draw):
        self.draw = draw

    def sim(self, n):
        """Simulate n draws from probability space.

        Args:
          n (int): How many draws to make.

        Returns:
          Results: A list-like object containing the simulation results.
        """
        return Results(self.draw() for _ in range(n))

    def check_same(self, other):
        if isinstance(other, ArbitrarySpace):
            return
        elif self != other:
            raise Exception("Events must be defined on same probability space.")

    def __mul__(self, other):
        def draw():
            a = self.draw() if type(self.draw()) == tuple else (self.draw(),)
            b = other.draw() if type(other.draw()) == tuple else (other.draw(),)
            return a + b
        return ProbabilitySpace(draw)

    def __pow__(self, exponent):
        if exponent == float("inf"):
            def draw():
                seed = get_seed()
                def x(n):
                    np.random.seed(seed)
                    for _ in range(int(n)):
                        self.draw()
                    return self.draw()
                return InfiniteSequence(x)
        else:
            def draw():
                return tuple(self.draw() for _ in range(exponent))
        return ProbabilitySpace(draw)

class ArbitrarySpace(ProbabilitySpace):
    """Defines an arbitrary probability space for
         deterministic phenomena, which is
         compatible with any other probability space.
    """

    def __init__(self):
        self.draw = lambda: 1

    def check_same(self, other):
        pass

class Event:

    def __init__(self, probSpace, fun):
        self.probSpace = probSpace
        self.fun = fun

    def check_same_probSpace(self, other):
        self.probSpace.check_same(other.probSpace)

    # define the event (A & B)
    def __and__(self, other):
        self.check_same_probSpace(other)
        if isinstance(other, Event):
            return Event(self.probSpace,
                         lambda x: self.fun(x) and other.fun(x))

    # define the event (A | B)
    def __or__(self, other):
        self.check_same_probSpace(other)
        if isinstance(other, Event):
            return Event(self.probSpace,
                         lambda x: self.fun(x) or other.fun(x))

    # This prevents users from writing expressions like 2 < X < 5,
    # which evaluate to ((2 < X) and (X < 5)). This unfortunately
    # is not well-defined in Python and cannot be overloaded.
    def __bool__(self):
        raise Exception("I do not know how to cast " +
                        "an event to a boolean. " +
                        "If you wrote an expression " +
                        "like (2 < X < 5), try writing " +
                        "((2 < X) & (X < 5)) instead."
                    )

class BoxModel(ProbabilitySpace):
    """Defines a probability space from a box model.

    Attributes:
      box (list): The box to sample from.
      size (int): How many draws to make.
      replace (bool): Sample with replacement or without?
      probs (list): Probabilities of sampling each ticket
        (by default, all tickets are equally likely)
      order_matters (bool): Should we count different
        orderings of the same tickets as different outcomes?
        Essentially, this determines whether the draws are
        sorted before returning or not.
    """

    def __init__(self, box, size=None, replace=True, probs=None, order_matters=True):
        self.box = box
        self.size = None if size == 1 else size
        self.replace = replace
        self.probs = probs
        self.order_matters = order_matters

    def draw(self):
        def draw_inds(size):
            return np.random.choice(len(self.box), size, self.replace, self.probs)
        if self.size is None:
            return self.box[draw_inds(None)]
        elif self.size == float("inf"):
            if self.replace == False:
                raise Exception("Cannot draw an infinite number of tickets without replacement.")
            seed = get_seed()
            def x(n):
                np.random.seed(seed)
                for _ in range(int(n)):
                    draw_inds(None)
                return self.box[draw_inds(None)]
            return InfiniteSequence(x)
        else:
            draws = [self.box[i] for i in draw_inds(self.size)]
            if not self.order_matters:
                draws.sort()
            return tuple(draws)

class DeckOfCards(BoxModel):
    """Defines the probability space for drawing from a deck of cards.

    Attributes:
      size (int): How many draws to make.
      replace (bool): Sample with replacement or without?
    """

    def __init__(self, size=None, replace=False):
        self.box = []
        for rank in list(range(2, 11)) + ["J", "Q", "K", "A"]:
            for suit in ["Diamonds", "Hearts", "Clubs", "Spades"]:
                self.box.append((rank, suit))
        self.size = size
        self.replace = replace
        self.probs = None
<commit_msg>fixed DeckOfCards<commit_after>import numpy as np

from .results import Results
from .sequences import InfiniteSequence
from .seed import get_seed

class ProbabilitySpace:
    """Defines a probability space.

    Attributes:
      draw (function): A function explaining how to draw one
        outcome from the probability space.
    """

    def __init__(self, draw):
        self.draw = draw

    def sim(self, n):
        """Simulate n draws from probability space.

        Args:
          n (int): How many draws to make.

        Returns:
          Results: A list-like object containing the simulation results.
        """
        return Results(self.draw() for _ in range(n))

    def check_same(self, other):
        if isinstance(other, ArbitrarySpace):
            return
        elif self != other:
            raise Exception("Events must be defined on same probability space.")

    def __mul__(self, other):
        def draw():
            a = self.draw() if type(self.draw()) == tuple else (self.draw(),)
            b = other.draw() if type(other.draw()) == tuple else (other.draw(),)
            return a + b
        return ProbabilitySpace(draw)

    def __pow__(self, exponent):
        if exponent == float("inf"):
            def draw():
                seed = get_seed()
                def x(n):
                    np.random.seed(seed)
                    for _ in range(int(n)):
                        self.draw()
                    return self.draw()
                return InfiniteSequence(x)
        else:
            def draw():
                return tuple(self.draw() for _ in range(exponent))
        return ProbabilitySpace(draw)

class ArbitrarySpace(ProbabilitySpace):
    """Defines an arbitrary probability space for
         deterministic phenomena, which is
         compatible with any other probability space.
    """

    def __init__(self):
        self.draw = lambda: 1

    def check_same(self, other):
        pass

class Event:

    def __init__(self, probSpace, fun):
        self.probSpace = probSpace
        self.fun = fun

    def check_same_probSpace(self, other):
        self.probSpace.check_same(other.probSpace)

    # define the event (A & B)
    def __and__(self, other):
        self.check_same_probSpace(other)
        if isinstance(other, Event):
            return Event(self.probSpace,
                         lambda x: self.fun(x) and other.fun(x))

    # define the event (A | B)
    def __or__(self, other):
        self.check_same_probSpace(other)
        if isinstance(other, Event):
            return Event(self.probSpace,
                         lambda x: self.fun(x) or other.fun(x))

    # This prevents users from writing expressions like 2 < X < 5,
    # which evaluate to ((2 < X) and (X < 5)). This unfortunately
    # is not well-defined in Python and cannot be overloaded.
    def __bool__(self):
        raise Exception("I do not know how to cast " +
                        "an event to a boolean. " +
                        "If you wrote an expression " +
                        "like (2 < X < 5), try writing " +
                        "((2 < X) & (X < 5)) instead."
                    )

class BoxModel(ProbabilitySpace):
    """Defines a probability space from a box model.

    Attributes:
      box (list): The box to sample from.
      size (int): How many draws to make.
      replace (bool): Sample with replacement or without?
      probs (list): Probabilities of sampling each ticket
        (by default, all tickets are equally likely)
      order_matters (bool): Should we count different
        orderings of the same tickets as different outcomes?
        Essentially, this determines whether the draws are
        sorted before returning or not.
    """

    def __init__(self, box, size=None, replace=True, probs=None, order_matters=True):
        self.box = box
        self.size = None if size == 1 else size
        self.replace = replace
        self.probs = probs
        self.order_matters = order_matters

    def draw(self):
        def draw_inds(size):
            return np.random.choice(len(self.box), size, self.replace, self.probs)
        if self.size is None:
            return self.box[draw_inds(None)]
        elif self.size == float("inf"):
            if self.replace == False:
                raise Exception("Cannot draw an infinite number of tickets without replacement.")
            seed = get_seed()
            def x(n):
                np.random.seed(seed)
                for _ in range(int(n)):
                    draw_inds(None)
                return self.box[draw_inds(None)]
            return InfiniteSequence(x)
        else:
            draws = [self.box[i] for i in draw_inds(self.size)]
            if not self.order_matters:
                draws.sort()
            return tuple(draws)

class DeckOfCards(BoxModel):
    """Defines the probability space for drawing from a deck of cards.

    Attributes:
      size (int): How many draws to make.
      replace (bool): Sample with replacement or without?
    """

    def __init__(self, size=None, replace=False, order_matters=True):
        self.box = []
        for rank in list(range(2, 11)) + ["J", "Q", "K", "A"]:
            for suit in ["Diamonds", "Hearts", "Clubs", "Spades"]:
                self.box.append((rank, suit))
        self.size = None if size == 1 else size
        self.replace = replace
        self.probs = None
        self.order_matters = order_matters

<|endoftext|>


<commit_before>from django.http import Http404
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext

from django.contrib import messages
from django.contrib.auth.decorators import login_required

from symposion.sponsorship.forms import SponsorApplicationForm, SponsorDetailsForm, SponsorBenefitsFormSet
from symposion.sponsorship.models import Sponsor, SponsorBenefit

@login_required
def sponsor_apply(request):
    if request.method == "POST":
        form = SponsorApplicationForm(request.POST, user=request.user)
        if form.is_valid():
            sponsor = form.save()
            return redirect("sponsor_detail", pk=sponsor.pk)
    else:
        form = SponsorApplicationForm(user=request.user)

    return render_to_response("sponsorship/apply.html", {
        "form": form,
    }, context_instance=RequestContext(request))

@login_required
def sponsor_add(request):
    if not request.user.is_staff:
        raise Http404()

    if request.method == "POST":
        form = SponsorApplicationForm(request.POST, user=request.user)
        if form.is_valid():
            sponsor = form.save(commit=False)
            sponsor.active = True
            sponsor.save()
            return redirect("sponsor_detail", pk=sponsor.pk)
    else:
        form = SponsorApplicationForm(user=request.user)

    return render_to_response("sponsorship/add.html", {
        "form": form,
    }, context_instance=RequestContext(request))

@login_required
def sponsor_detail(request, pk):
    sponsor = get_object_or_404(Sponsor, pk=pk)

    if sponsor.applicant != request.user:
        return redirect("sponsor_list")

    formset_kwargs = {
        "instance": sponsor,
        "queryset": SponsorBenefit.objects.filter(active=True)
    }

    if request.method == "POST":

        form = SponsorDetailsForm(request.POST, instance=sponsor)
        formset = SponsorBenefitsFormSet(request.POST, request.FILES, **formset_kwargs)

        if form.is_valid() and formset.is_valid():
            form.save()
            formset.save()

            messages.success(request, "Sponsorship details have been updated")

            return redirect("dashboard")
    else:
        form = SponsorDetailsForm(instance=sponsor)
        formset = SponsorBenefitsFormSet(**formset_kwargs)

    return render_to_response("sponsorship/detail.html", {
        "sponsor": sponsor,
        "form": form,
        "formset": formset,
    }, context_instance=RequestContext(request))
<commit_msg>sponsor_add doesn't auto-activate sponsorship; check for user and pass user to forms in sponsor_detail<commit_after>from django.http import Http404
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext

from django.contrib import messages
from django.contrib.auth.decorators import login_required

from symposion.sponsorship.forms import SponsorApplicationForm, SponsorDetailsForm, SponsorBenefitsFormSet
from symposion.sponsorship.models import Sponsor, SponsorBenefit

@login_required
def sponsor_apply(request):
    if request.method == "POST":
        form = SponsorApplicationForm(request.POST, user=request.user)
        if form.is_valid():
            sponsor = form.save()
            return redirect("sponsor_detail", pk=sponsor.pk)
    else:
        form = SponsorApplicationForm(user=request.user)

    return render_to_response("sponsorship/apply.html", {
        "form": form,
    }, context_instance=RequestContext(request))

@login_required
def sponsor_add(request):
    if not request.user.is_staff:
        raise Http404()

    if request.method == "POST":
        form = SponsorApplicationForm(request.POST, user=request.user)
        if form.is_valid():
            sponsor = form.save(commit=False)
            sponsor.save()
            return redirect("sponsor_detail", pk=sponsor.pk)
    else:
        form = SponsorApplicationForm(user=request.user)

    return render_to_response("sponsorship/add.html", {
        "form": form,
    }, context_instance=RequestContext(request))

@login_required
def sponsor_detail(request, pk):
    sponsor = get_object_or_404(Sponsor, pk=pk)

    if not request.user.is_staff:
        if sponsor.applicant != request.user:
            return redirect("sponsor_list")

    formset_kwargs = {
        "instance": sponsor,
        "queryset": SponsorBenefit.objects.filter(active=True)
    }

    if request.method == "POST":

        form = SponsorDetailsForm(request.POST, user=request.user, instance=sponsor)
        formset = SponsorBenefitsFormSet(request.POST, request.FILES, **formset_kwargs)

        if form.is_valid() and formset.is_valid():
            form.save()
            formset.save()

            messages.success(request, "Sponsorship details have been updated")

            return redirect("dashboard")
    else:
        form = SponsorDetailsForm(user=request.user, instance=sponsor)
        formset = SponsorBenefitsFormSet(**formset_kwargs)

    return render_to_response("sponsorship/detail.html", {
        "sponsor": sponsor,
        "form": form,
        "formset": formset,
    }, context_instance=RequestContext(request))
<|endoftext|>