Datasets:
AI4M
/

text
stringlengths
0
3.34M
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Contains the definition for inception v3 classification network.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import inception_utils import numpy as np import cv2 FLAGS = tf.app.flags.FLAGS slim = tf.contrib.slim trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) def inception_v3_bap_base(inputs, final_endpoint='Mixed_6e', min_depth=16, depth_multiplier=1.0, scope=None): """Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints registered by this function although they build the same network. Here is a mapping from the old_names to the new names: Old name | New name ======================================= conv0 | Conv2d_1a_3x3 conv1 | Conv2d_2a_3x3 conv2 | Conv2d_2b_3x3 pool1 | MaxPool_3a_3x3 conv3 | Conv2d_3b_1x1 conv4 | Conv2d_4a_3x3 pool2 | MaxPool_5a_3x3 mixed_35x35x256a | Mixed_5b mixed_35x35x288a | Mixed_5c mixed_35x35x288b | Mixed_5d mixed_17x17x768a | Mixed_6a mixed_17x17x768b | Mixed_6b mixed_17x17x768c | Mixed_6c mixed_17x17x768d | Mixed_6d mixed_17x17x768e | Mixed_6e mixed_8x8x1280a | Mixed_7a mixed_8x8x2048a | Mixed_7b mixed_8x8x2048b | Mixed_7c Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0 """ # end_points will collect relevant activations for external use, for example # summaries or losses. end_points = {} if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV3', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='VALID'): # 299 x 299 x 3 end_point = 'Conv2d_1a_3x3' net = slim.conv2d(inputs, depth(32), [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 149 x 149 x 32 end_point = 'Conv2d_2a_3x3' net = slim.conv2d(net, depth(32), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 32 end_point = 'Conv2d_2b_3x3' net = slim.conv2d(net, depth(64), [3, 3], padding='SAME', scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 64 end_point = 'MaxPool_3a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 64 end_point = 'Conv2d_3b_1x1' net = slim.conv2d(net, depth(80), [1, 1], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 80. end_point = 'Conv2d_4a_3x3' net = slim.conv2d(net, depth(192), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 71 x 71 x 192. end_point = 'MaxPool_5a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 35 x 35 x 192. # Inception blocks with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # mixed: 35 x 35 x 256. end_point = 'Mixed_5b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(32), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_1: 35 x 35 x 288. end_point = 'Mixed_5c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0b_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv_1_0c_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_2: 35 x 35 x 288. end_point = 'Mixed_5d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_3: 17 x 17 x 768. end_point = 'Mixed_6a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(384), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') end_points[end_point + '_b1'] = branch_1 branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed4: 17 x 17 x 768. end_point = 'Mixed_6b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(128), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(128), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_5: 17 x 17 x 768. end_point = 'Mixed_6c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_6: 17 x 17 x 768. end_point = 'Mixed_6d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_7: 17 x 17 x 768. end_point = 'Mixed_6e' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') end_points[end_point + '_b0'] = branch_0 with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_8: 8 x 8 x 1280. end_point = 'Mixed_7a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') end_points[end_point + '_b0'] = branch_0 branch_0 = slim.conv2d(branch_0, depth(320), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') end_points[end_point + '_b1'] = branch_1 branch_1 = slim.conv2d(branch_1, depth(192), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_9: 8 x 8 x 2048. end_point = 'Mixed_7b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0b_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_10: 8 x 8 x 2048. end_point = 'Mixed_7c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') end_points[end_point + '_b0'] = branch_0 with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0c_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def inception_v3_bap_head(net,end_points, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None, ): if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV3', [net], reuse=tf.AUTO_REUSE): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # mixed_8: 8 x 8 x 1280. end_point = 'Mixed_7a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, depth(320), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') branch_1 = slim.conv2d(branch_1, depth(192), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_9: 8 x 8 x 2048. end_point = 'Mixed_7b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0b_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_10: 8 x 8 x 2048. end_point = 'Mixed_7c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') end_points[end_point + '_b0'] = branch_0 with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0c_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) return net, end_points def attention_pooling(attention_maps, feature_maps): attention_features = [] for attention_map in tf.unstack(attention_maps, axis=-1): attention_map = tf.expand_dims(attention_map, 3) part_feature = attention_map * feature_maps attention_features.append(part_feature) attention_features = tf.concat(attention_features, axis=0) return attention_features def bilinear_attention_pooling(feature_maps, attention_maps, end_points, name): feature_shape = feature_maps.get_shape().as_list() attention_shape = attention_maps.get_shape().as_list() phi_I = tf.einsum('ijkm,ijkn->imn', attention_maps, feature_maps) phi_I = tf.divide(phi_I, tf.to_float(attention_shape[1] * attention_shape[2])) phi_I = tf.multiply(tf.sign(phi_I), tf.sqrt(tf.abs(phi_I) + 1e-12)) raw_features = tf.nn.l2_normalize(phi_I, axis=[1, 2]) raw_features = tf.reshape(raw_features, [-1, 1, 1, attention_shape[-1] * feature_shape[-1]]) end_points[name] = raw_features pooling_features = raw_features * 100.0 return pooling_features, end_points def wsddn_pooling(feature_maps, attention_maps, keep_prob, end_points, name): feature_shape = feature_maps.get_shape().as_list() attention_shape = attention_maps.get_shape().as_list() phi_I = tf.einsum('ijkm,ijkn->imn', attention_maps, feature_maps) phi_I = tf.divide(phi_I, tf.to_float(attention_shape[1] * attention_shape[2])) phi_I = tf.multiply(tf.sign(phi_I), tf.sqrt(tf.abs(phi_I) + 1e-12)) phi_attention = phi_I / tf.reduce_sum(phi_I + 1e-12, axis=1, keepdims=True) phi_feature = phi_I / tf.reduce_sum(phi_I + 1e-12, axis=2, keepdims=True) phi_I = phi_attention * phi_feature pooling_features = tf.reduce_sum(phi_I, axis=1) pooling_features = tf.nn.l2_normalize(pooling_features, axis=-1) end_points[name] = tf.reshape(pooling_features, [-1, 1, 1, feature_shape[-1]]) pooling_features = tf.reshape(pooling_features * 100.0, [-1, 1, 1, feature_shape[-1]]) return pooling_features, end_points def aspp_residual(attention_maps): scale1 = attention_maps scale2 = slim.conv2d(attention_maps, 192, [3, 3], rate=6) scale3 = slim.conv2d(attention_maps, 192, [3, 3], rate=12) scale4 = slim.conv2d(attention_maps, 192, [3, 3], rate=18) attention_maps = scale1 + scale2 + scale3 + scale4 return attention_maps def generate_attention_image(image, attention_map): h, w, _ = image.shape mask = np.mean(attention_map, axis=-1, keepdims=True) mask = (mask / np.max(mask) * 255.0).astype(np.uint8) mask = cv2.resize(mask, (w, h)) image = (image / 2.0 + 0.5) * 255.0 image = image.astype(np.uint8) color_map = cv2.applyColorMap(mask.astype(np.uint8), cv2.COLORMAP_JET) attention_image = cv2.addWeighted(image, 0.5, color_map.astype(np.uint8), 0.5, 0) attention_image = cv2.cvtColor(attention_image, cv2.COLOR_BGR2RGB) return attention_image def inception_v3_bap(inputs, num_classes=1000, is_training=True, min_depth=16, depth_multiplier=1.0, reuse=False, scope='InceptionV3'): with tf.variable_scope(scope, 'InceptionV3', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = inception_v3_bap_base( inputs, final_endpoint='Mixed_7c', scope=scope, min_depth=min_depth, depth_multiplier=depth_multiplier) with tf.variable_scope('bilinear_attention_pooling'): feature_maps = end_points[FLAGS.feature_maps] attention_maps = end_points[FLAGS.attention_maps] num_parts = FLAGS.num_parts attention_maps = attention_maps[:, :, :, :num_parts] attention_image = tf.py_func(generate_attention_image, [inputs[0], attention_maps[0]], tf.uint8) tf.summary.image('attention_image', tf.expand_dims(attention_image, 0)) tf.summary.image('input_image', inputs[0:1]) if is_training: tf.summary.image('attention_maps', tf.reduce_mean(attention_maps[0:1], axis=-1, keepdims=True)) tf.summary.image('feature_maps', tf.reduce_mean(feature_maps[0:1], axis=-1, keepdims=True)) end_points['attention_maps'] = attention_maps end_points['feature_maps'] = feature_maps bap_features, end_points = bilinear_attention_pooling(feature_maps, attention_maps , end_points, 'embeddings') with tf.variable_scope('logits'): logits = slim.conv2d(bap_features, num_classes, [1, 1], activation_fn=None, normalizer_fn=None) logits = tf.squeeze(logits, [1, 2]) end_points['logits'] = logits return logits, end_points inception_v3_bap.default_image_size = 299 def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough. Args: input_tensor: input tensor of size [batch_size, height, width, channels]. kernel_size: desired kernel size of length 2: [kernel_height, kernel_width] Returns: a tensor with the kernel size. TODO(jrru): Make this function work with unknown shapes. Theoretically, this can be done with the code below. Problems are two-fold: (1) If the shape was known, it will be lost. (2) inception.slim.ops._two_element_tuple cannot handle tensors that define the kernel size. shape = tf.shape(input_tensor) return = tf.stack([tf.minimum(shape[1], kernel_size[0]), tf.minimum(shape[2], kernel_size[1])]) """ shape = input_tensor.get_shape().as_list() if shape[1] is None or shape[2] is None: kernel_size_out = kernel_size else: kernel_size_out = [min(shape[1], kernel_size[0]), min(shape[2], kernel_size[1])] return kernel_size_out inception_v3_bap_arg_scope = inception_utils.inception_arg_scope
(********************************************************************) (* *) (* The Why3 Verification Platform / The Why3 Development Team *) (* Copyright 2010-2015 -- INRIA - CNRS - Paris-Sud University *) (* *) (* This software is distributed under the terms of the GNU Lesser *) (* General Public License version 2.1, with the special exception *) (* on linking described in file LICENSE. *) (* *) (********************************************************************) (* This file is generated by Why3's Coq-realize driver *) (* Beware! Only edit allowed sections below *) Require Import BuiltIn. Require BuiltIn. Require int.Int. (* Why3 assumption *) Definition even (n:Z): Prop := exists k:Z, (n = (2%Z * k)%Z). (* Why3 assumption *) Definition odd (n:Z): Prop := exists k:Z, (n = ((2%Z * k)%Z + 1%Z)%Z). Lemma even_is_Zeven : forall n, even n <-> Zeven n. Proof. intros n. refine (conj _ (Zeven_ex n)). intros (k,H). rewrite H. apply Zeven_2p. Qed. Lemma odd_is_Zodd : forall n, odd n <-> Zodd n. Proof. intros n. refine (conj _ (Zodd_ex n)). intros (k,H). rewrite H. apply Zodd_2p_plus_1. Qed. (* Why3 goal *) Lemma even_or_odd : forall (n:Z), (even n) \/ (odd n). Proof. intros n. destruct (Zeven_odd_dec n). left. now apply <- even_is_Zeven. right. now apply <- odd_is_Zodd. Qed. (* Why3 goal *) Lemma even_not_odd : forall (n:Z), (even n) -> ~ (odd n). Proof. intros n H1 H2. apply (Zeven_not_Zodd n). now apply -> even_is_Zeven. now apply -> odd_is_Zodd. Qed. (* Why3 goal *) Lemma odd_not_even : forall (n:Z), (odd n) -> ~ (even n). Proof. intros n H1. contradict H1. now apply even_not_odd. Qed. (* Why3 goal *) Lemma even_odd : forall (n:Z), (even n) -> (odd (n + 1%Z)%Z). Proof. intros n H. apply <- odd_is_Zodd. apply Zeven_plus_Zodd. now apply -> even_is_Zeven. easy. Qed. (* Why3 goal *) Lemma odd_even : forall (n:Z), (odd n) -> (even (n + 1%Z)%Z). Proof. intros n H. apply <- even_is_Zeven. apply Zodd_plus_Zodd. now apply -> odd_is_Zodd. easy. Qed. (* Why3 goal *) Lemma even_even : forall (n:Z), (even n) -> (even (n + 2%Z)%Z). Proof. intros n H. apply <- even_is_Zeven. apply Zeven_plus_Zeven. now apply -> even_is_Zeven. easy. Qed. (* Why3 goal *) Lemma odd_odd : forall (n:Z), (odd n) -> (odd (n + 2%Z)%Z). Proof. intros n H. apply <- odd_is_Zodd. apply Zodd_plus_Zeven. now apply -> odd_is_Zodd. easy. Qed. (* Why3 goal *) Lemma even_2k : forall (k:Z), (even (2%Z * k)%Z). Proof. intros k. now exists k. Qed. (* Why3 goal *) Lemma odd_2k1 : forall (k:Z), (odd ((2%Z * k)%Z + 1%Z)%Z). Proof. intros k. now exists k. Qed.
''' Dada a função f(x)=A.sen(x)/x onde A = 10. Calcule \int_0^\pi f(x) dx 1. Use o método de tentativa e erro 2. Use o método de amostragem média ''' import numpy as np import matplotlib.pyplot as plt import random as rand def montecarlotnterr(fx, sup, inf, esq, dir, n): xs = list(rand.uniform(esq, dir) for i in range(n)) ys = list(rand.uniform(inf, sup) for i in range(n)) ni = 0 for x, y in zip(xs, ys): if y <= fx(x): ni += 1 return (ni/n)*((dir-esq)*(sup-inf)) def montecarlomed(fx, esq, dir, n): xs = np.array(list(rand.uniform(esq, dir) for i in range(n))) ym = sum(fx(xs))/n return (dir - esq) * ym a = 10 n = 1000 fx = lambda x: a * np.sin(x)/x # Atividade print('Integração por Monte Carlo') print(f'N = {n}') print(f'Tentativa e Erro = {montecarlotnterr(fx, 10, 0, 0, np.pi, n)}') print(f'Amostragem Média = {montecarlomed(fx, 0, np.pi, n)}') ns = np.arange(1, n) itent = [] imed = [] for i in ns: itent.append(montecarlotnterr(fx, 10, 0, 0, np.pi, i)) imed.append(montecarlomed(fx, 0, np.pi, i)) plt.plot(ns, itent, label='Tentativa e Erro') plt.plot(ns, imed, label='Amostragem Média') plt.xlabel('N') plt.ylabel('Integral') plt.legend() plt.grid() plt.savefig("funcaomontecarlo.png")
{-# OPTIONS --safe --warning=error --without-K #-} open import LogicalFormulae open import Groups.Homomorphisms.Definition open import Groups.Definition open import Setoids.Setoids open import Sets.EquivalenceRelations open import Rings.Definition open import Lists.Lists open import Rings.Homomorphisms.Definition module Rings.Polynomial.Evaluation {a b : _} {A : Set a} {S : Setoid {a} {b} A} {_+_ _*_ : A → A → A} (R : Ring S _+_ _*_) where open Ring R open Setoid S open Equivalence eq open Group additiveGroup open import Groups.Polynomials.Definition additiveGroup open import Groups.Polynomials.Addition additiveGroup open import Rings.Polynomial.Ring R open import Rings.Polynomial.Multiplication R inducedFunction : NaivePoly → A → A inducedFunction [] a = 0R inducedFunction (x :: p) a = x + (a * inducedFunction p a) inducedFunctionMult : (as : NaivePoly) (b c : A) → inducedFunction (map (_*_ b) as) c ∼ (inducedFunction as c) * b inducedFunctionMult [] b c = symmetric (transitive *Commutative timesZero) inducedFunctionMult (x :: as) b c = transitive (transitive (+WellDefined reflexive (transitive (transitive (*WellDefined reflexive (inducedFunctionMult as b c)) *Associative) *Commutative)) (symmetric *DistributesOver+)) *Commutative inducedFunctionWellDefined : {a b : NaivePoly} → polysEqual a b → (c : A) → inducedFunction a c ∼ inducedFunction b c inducedFunctionWellDefined {[]} {[]} a=b c = reflexive inducedFunctionWellDefined {[]} {x :: b} (fst ,, snd) c = symmetric (transitive (+WellDefined fst (transitive (*WellDefined reflexive (symmetric (inducedFunctionWellDefined {[]} {b} snd c))) (timesZero {c}))) identRight) inducedFunctionWellDefined {a :: as} {[]} (fst ,, snd) c = transitive (+WellDefined fst reflexive) (transitive identLeft (transitive (*WellDefined reflexive (inducedFunctionWellDefined {as} {[]} snd c)) (timesZero {c}))) inducedFunctionWellDefined {a :: as} {b :: bs} (fst ,, snd) c = +WellDefined fst (*WellDefined reflexive (inducedFunctionWellDefined {as} {bs} snd c)) inducedFunctionGroupHom : {x y : NaivePoly} → (a : A) → inducedFunction (x +P y) a ∼ (inducedFunction x a + inducedFunction y a) inducedFunctionGroupHom {[]} {[]} a = symmetric identLeft inducedFunctionGroupHom {[]} {x :: y} a rewrite mapId y = symmetric identLeft inducedFunctionGroupHom {x :: xs} {[]} a rewrite mapId xs = symmetric identRight inducedFunctionGroupHom {x :: xs} {y :: ys} a = transitive (symmetric +Associative) (transitive (+WellDefined reflexive (transitive (transitive (+WellDefined reflexive (transitive (*WellDefined reflexive (transitive (inducedFunctionGroupHom {xs} {ys} a) groupIsAbelian)) *DistributesOver+)) +Associative) groupIsAbelian)) +Associative) inducedFunctionRingHom : (r s : NaivePoly) (a : A) → inducedFunction (r *P s) a ∼ (inducedFunction r a * inducedFunction s a) inducedFunctionRingHom [] s a = symmetric (transitive *Commutative timesZero) inducedFunctionRingHom (x :: xs) [] a = symmetric timesZero inducedFunctionRingHom (b :: bs) (c :: cs) a = transitive (+WellDefined reflexive (*WellDefined reflexive (inducedFunctionGroupHom {map (_*_ b) cs +P map (_*_ c) bs} {0G :: (bs *P cs)} a))) (transitive (+WellDefined reflexive (*WellDefined reflexive (+WellDefined (inducedFunctionGroupHom {map (_*_ b) cs} {map (_*_ c) bs} a) identLeft))) (transitive (transitive (transitive (+WellDefined reflexive (transitive (transitive (transitive (*WellDefined reflexive (transitive (+WellDefined (transitive groupIsAbelian (+WellDefined (inducedFunctionMult bs c a) (inducedFunctionMult cs b a))) (transitive (transitive (*WellDefined reflexive (transitive (inducedFunctionRingHom bs cs a) *Commutative)) *Associative) *Commutative)) (symmetric +Associative))) *DistributesOver+) (+WellDefined reflexive *DistributesOver+)) (+WellDefined *Associative (+WellDefined (transitive *Associative *Commutative) *Associative)))) +Associative) (+WellDefined (symmetric *DistributesOver+') (symmetric *DistributesOver+'))) (symmetric *DistributesOver+))) inducedFunctionIsHom : (a : A) → RingHom polyRing R (λ p → inducedFunction p a) RingHom.preserves1 (inducedFunctionIsHom a) = transitive (+WellDefined reflexive (timesZero {a})) identRight RingHom.ringHom (inducedFunctionIsHom a) {r} {s} = inducedFunctionRingHom r s a GroupHom.groupHom (RingHom.groupHom (inducedFunctionIsHom a)) {x} {y} = inducedFunctionGroupHom {x} {y} a GroupHom.wellDefined (RingHom.groupHom (inducedFunctionIsHom a)) x=y = inducedFunctionWellDefined x=y a
# Copyright (c) 2018-2021, Carnegie Mellon University # See LICENSE for details # Don't forget to Import(platforms.sse) #NOTE: # Bluestein breaks for SSE_2x64f -- disabled for small for now # doParSimdDft seems broken benchSSE := function() if LocalConfig.cpuinfo.SIMD().hasSSE2() then return rec( 2x32f := rec( wht := rec( small := _defaultSizes(s->doSimdWht(s, SSE_2x32f, rec(propagateNth := true, useDeref := true, verify := true, oddSizes := true, svct := true, stdTTensor := true, tsplPFA := false)), [4]), medium := _defaultSizes(s->doSimdWht(s, SSE_2x32f, rec(propagateNth := true, useDeref := true, oddSizes := false, svct := true, stdTTensor := true, tsplPFA := false)), List([2..10], i->2^i)) ), 1d := rec( dft_sc := rec( small := _defaultSizes(s->doSimdDft(s, SSE_2x32f, rec(propagateNth := true, useDeref := true, verify:=true, tsplBluestein:=false, interleavedComplex := true, PRDFT:=true, URDFT:= true, cplxVect := true, stdTTensor := false, globalUnrolling:=10000)), [ 2..32 ]), ), dft_ic := rec( small := _defaultSizes(s->doSimdDft(s, SSE_2x32f, rec(propagateNth := true, useDeref := true, verify:=true, tsplBluestein:=false, interleavedComplex := true, PRDFT:=true, URDFT:= true, cplxVect := true, stdTTensor := false, globalUnrolling:=10000)), [2..32]) ) ) ), 2x64f := rec( wht := rec( small := _defaultSizes(s->doSimdWht(s, SSE_2x64f, rec(verify := true, oddSizes := true, svct := true, stdTTensor := true, tsplPFA := false)), [4]), medium := _defaultSizes(s->doSimdWht(s, SSE_2x64f, rec(oddSizes := false, svct := true, stdTTensor := true, tsplPFA := false)), List([2..10], i->2^i)) ), 1d := rec( dft_sc := rec( small := _defaultSizes(s->doSimdDft(s, SSE_2x64f, rec(verify:=true, tsplBluestein:=false, interleavedComplex := false, PRDFT:=true, URDFT:= true, cplxVect := true, stdTTensor := false, globalUnrolling:=10000)), [ 2..32 ]), medium := _defaultSizes(s->doSimdDft(s, SSE_2x64f, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := false)), _svctSizes(1024, 16, 2)), # medium := spiral.libgen.doParSimdDft(SSE_2x64f, 1, _svctSizes(1024, 16, 4), false, true, false, false), # large := spiral.libgen.doParSimdDft(SSE_2x64f, 1, List([4..20], i->2^i), false, true, false, false) ), dft_ic := rec( small := _defaultSizes(s->doSimdDft(s, SSE_2x64f, rec(verify:=true, tsplBluestein:=false, interleavedComplex := true, PRDFT:=true, URDFT:= true, cplxVect := true, stdTTensor := false, globalUnrolling:=10000)), [2..32]), medium := _defaultSizes(s->doSimdDft(s, SSE_2x64f, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := true)), _svctSizes(1024, 16, 2)), medium_cx := _defaultSizes(s->doSimdDft(s, SSE_2x64f, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := true, cplxVect := true, realVect := false)), _svctSizes(1024, 16, 2)), # medium := spiral.libgen.doParSimdDft(SSE_2x64f, 1, _svctSizes(1024, 16, 4), false, true, false, true), # large := spiral.libgen.doParSimdDft(SSE_2x64f, 1, List([4..20], i->2^i), false, true, false, true) ), trdft := _defaultSizes(s->doSimdSymDFT(TRDFT, s, SSE_2x64f, rec( verify:=true, interleavedComplex := true, PRDFT:=true, URDFT:= true, tsplBluestein := false, cplxVect := true, realVect := true, propagateNth := true, useDeref := true, globalUnrolling:=10000)), 4*[1..32]), dht := _defaultSizes(s->doSimdSymDFT(TDHT, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), dct2 := _defaultSizes(s->doSimdSymDFT(TDCT2, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), dct3 := _defaultSizes(s->doSimdSymDFT(TDCT3, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), dct4 := _defaultSizes(s->doSimdSymDFT(TDCT4, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), dst2 := _defaultSizes(s->doSimdSymDFT(TDST2, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), dst3 := _defaultSizes(s->doSimdSymDFT(TDST3, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), dst4 := _defaultSizes(s->doSimdSymDFT(TDST4, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), mdct := _defaultSizes(s->doSimdSymDFT(TMDCT, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]), imdct := _defaultSizes(s->doSimdSymDFT(TIMDCT, s, SSE_2x64f, rec(verify :=true)), 8*[1..12]) ), 2d := rec( dft_ic := rec( medium := _defaultSizes(s->doSimdMddft(s, SSE_2x64f, rec(interleavedComplex := true, oddSizes := false, svct := true, splitL := false, pushTag := true, flipIxA := false, stdTTensor := true, tsplPFA := false)), 4*List([1..16], i->[i,i])), small := _defaultSizes(s->doSimdMddft(s, SSE_2x64f, rec(verify:=true, interleavedComplex := true, globalUnrolling:=10000, tsplPFA := false, pushTag:= false, oddSizes := true, svct := true, splitL := false)), List([2..16], i->[i,i])) ), dft_sc := rec( medium := _defaultSizes(s->doSimdMddft(s, SSE_2x64f, rec(interleavedComplex := false, oddSizes := false, svct := true, splitL := false, pushTag := true, flipIxA := false, stdTTensor := true, tsplPFA := false)), 4*List([1..16], i->[i,i])), small := _defaultSizes(s->doSimdMddft(s, SSE_2x64f, rec(verify:=true, interleavedComplex := false, globalUnrolling:=10000, tsplPFA := false, pushTag:= false, oddSizes := true, svct := true, splitL := false)), List([2..16], i->[i,i])) ), dct2 := _defaultSizes(s->doSimdSymMDDFT(DCT2, s, SSE_2x64f, rec(verify := true)), [4, 8, 12, 16]), dct3 := _defaultSizes(s->doSimdSymMDDFT(DCT3, s, SSE_2x64f, rec(verify := true)), [4, 8, 12, 16]), dct4 := _defaultSizes(s->doSimdSymMDDFT(DCT4, s, SSE_2x64f, rec(verify := true)), [4, 8, 12, 16]), dst2 := _defaultSizes(s->doSimdSymMDDFT(DST2, s, SSE_2x64f, rec(verify := true)), [4, 8, 12, 16]), dst3 := _defaultSizes(s->doSimdSymMDDFT(DST3, s, SSE_2x64f, rec(verify := true)), [4, 8, 12, 16]), dst4 := _defaultSizes(s->doSimdSymMDDFT(DST4, s, SSE_2x64f, rec(verify := true)), [4, 8, 12, 16]) ) ), 4x32i := rec( wht := rec( small := _defaultSizes(s->doSimdWht(s, SSE_4x32i, rec(verify := true, oddSizes := true, svct := true, stdTTensor := true, tsplPFA := false)), List([], i->2^i)), medium := _defaultSizes(s->doSimdWht(s, SSE_4x32i, rec(oddSizes := false, svct := true, stdTTensor := true, tsplPFA := false)), List([4..10], i->2^i)) ) ), 4x32f := rec( wht := rec( small := _defaultSizes(s->doSimdWht(s, SSE_4x32f, rec(verify := true, oddSizes := true, svct := true, stdTTensor := true, tsplPFA := false)), List([1..3], i->2^i)), medium := _defaultSizes(s->doSimdWht(s, SSE_4x32f, rec(oddSizes := false, svct := true, stdTTensor := true, tsplPFA := false)), List([4..10], i->2^i)) ), 1d := rec( dft_sc := rec( small := _defaultSizes(s->doSimdDft(s, SSE_4x32f, rec(verify:=true, interleavedComplex := false, stdTTensor := false, globalUnrolling:=10000)), [ 2..64 ]), medium := _defaultSizes(s->doSimdDft(s, SSE_4x32f, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := false)), _svctSizes(1024, 16, 4)), # medium := spiral.libgen.doParSimdDft(SSE_4x32f, 1, _svctSizes(1024, 16, 4), false, true, false, false), # large := spiral.libgen.doParSimdDft(SSE_4x32f, 1, List([4..20], i->2^i), false, true, false, false) ), dft_ic := rec( small := _defaultSizes(s->doSimdDft(s, SSE_4x32f, rec(verify:=true, interleavedComplex := true, PRDFT:=true, URDFT:= true, cplxVect := true, stdTTensor := false, globalUnrolling:=10000)), [ 2..64 ]), medium := _defaultSizes(s->doSimdDft(s, SSE_4x32f, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := true)), _svctSizes(1024, 16, 4)), medium_cx := _defaultSizes(s->doSimdDft(s, SSE_4x32f, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := true, cplxVect := true, realVect := false, PRDFT := false, URDFT := true)), _svctSizes(1024, 16, 4)) # medium := spiral.libgen.doParSimdDft(SSE_4x32f, 1, _svctSizes(1024, 16, 4), false, true, false, true), # large := spiral.libgen.doParSimdDft(SSE_4x32f, 1, List([4..20], i->2^i), false, true, false, true) ), rdft := _defaultSizes(s->doSimdSymDFT(TRDFT, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), trdft := _defaultSizes(s->doSimdSymDFT(TRDFT, s, SSE_4x32f, rec( verify:=true, interleavedComplex := true, PRDFT:=true, URDFT:= true, tsplBluestein := false, cplxVect := true, stdTTensor := false, realVect := true, propagateNth := true, useDeref := true, globalUnrolling:=10000)), 8*[1..32]), dht := _defaultSizes(s->doSimdSymDFT(TDHT, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), dct2 := _defaultSizes(s->doSimdSymDFT(TDCT2, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), dct3 := _defaultSizes(s->doSimdSymDFT(TDCT3, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), dct4 := _defaultSizes(s->doSimdSymDFT(TDCT4, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), dst2 := _defaultSizes(s->doSimdSymDFT(TDST2, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), dst3 := _defaultSizes(s->doSimdSymDFT(TDST3, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), dst4 := _defaultSizes(s->doSimdSymDFT(TDST4, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), mdct := _defaultSizes(s->doSimdSymDFT(TMDCT, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]), imdct := _defaultSizes(s->doSimdSymDFT(TIMDCT, s, SSE_4x32f, rec(verify :=true)), 32*[1..12]) ), 2d := rec( dft_ic := rec( medium := _defaultSizes(s->doSimdMddft(s, SSE_4x32f, rec(interleavedComplex := true, oddSizes := false, svct := true, splitL := false, pushTag := true, flipIxA := false, stdTTensor := true, tsplPFA := false)), 16*List([1..8], i->[i,i])), small := _defaultSizes(s->doSimdMddft(s, SSE_4x32f, rec(verify:=true, interleavedComplex := true, globalUnrolling:=10000, tsplPFA := false, pushTag:= false, oddSizes := true, svct := true, splitL := false)), List([2..16], i->[i,i])) ), dft_sc := rec( medium := _defaultSizes(s->doSimdMddft(s, SSE_4x32f, rec(interleavedComplex := false, oddSizes := false, svct := true, splitL := false, pushTag := true, flipIxA := false, stdTTensor := true, tsplPFA := false)), 16*List([1..8], i->[i,i])), small := _defaultSizes(s->doSimdMddft(s, SSE_4x32f, rec(verify:=true, interleavedComplex := false, globalUnrolling:=10000, tsplPFA := false, pushTag:= false, oddSizes := true, svct := true, splitL := false)), List([2..16], i->[i,i])) ), dct2 := _defaultSizes(s->doSimdSymMDDFT(DCT2, s, SSE_4x32f, rec(verify := true)), [4, 8, 12, 16]), dct3 := _defaultSizes(s->doSimdSymMDDFT(DCT3, s, SSE_4x32f, rec(verify := true)), [4, 8, 12, 16]), dct4 := _defaultSizes(s->doSimdSymMDDFT(DCT4, s, SSE_4x32f, rec(verify := true)), [4, 8, 12, 16]), dst2 := _defaultSizes(s->doSimdSymMDDFT(DST2, s, SSE_4x32f, rec(verify := true)), [4, 8, 12, 16]), dst3 := _defaultSizes(s->doSimdSymMDDFT(DST3, s, SSE_4x32f, rec(verify := true)), [4, 8, 12, 16]), dst4 := _defaultSizes(s->doSimdSymMDDFT(DST4, s, SSE_4x32f, rec(verify := true)), [4, 8, 12, 16]), # DO NOT USE BECAUSE IT GENERATES A NON_COMPATIBLE INIT() FUNCTION FOR USE WITH STANDARD TIMER # conv := _defaultSizes(s->doSimdMdConv(s, SSE_4x32f, rec(svct := true, oddSizes := false, # splitComplexTPrm := true, TRCDiag_VRCLR := true, globalUnrolling := 150, measureFinal := false)), # 16*[1..32]) ) ), 8x16i := rec( wht := rec( small := _defaultSizes(s->doSimdWht(s, SSE_8x16i, rec(verify := true, oddSizes := true, svct := true, stdTTensor := true, tsplPFA := false)), List([1..5], i->2^i)), medium := _defaultSizes(s->doSimdWht(s, SSE_8x16i, rec(oddSizes := false, svct := true, stdTTensor := true, tsplPFA := false)), List([6..10], i->2^i)) ), 1d := rec( dft_ic := rec( medium := _defaultSizes(s->doSimdDft(s, SSE_8x16i, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := true, verify := true)), 64*[1..4]), small := _defaultSizes(s->doSimdDft(s, SSE_8x16i, rec(verify:=true, interleavedComplex := true, stdTTensor := false, globalUnrolling:=10000)), [2..16]) ), dft_sc := rec( medium := _defaultSizes(s->doSimdDft(s, SSE_8x16i, rec(tsplRader:=false, tsplBluestein:=false, tsplPFA:=false, oddSizes:=false, interleavedComplex := false, verify := true)), 64*[1..4]), small := _defaultSizes(s->doSimdDft(s, SSE_8x16i, rec(verify:=true, interleavedComplex := false, stdTTensor := false, globalUnrolling:=10000)), [2..16]) ), rdft := _defaultSizes(s->doSimdSymDFT(TRDFT, s, SSE_8x16i, rec(verify := true)), 128*[1..4]), dht := _defaultSizes(s->doSimdSymDFT(TDHT, s, SSE_8x16i, rec(verify :=true)), 128*[1..4]), dct2 := _defaultSizes(s->doSimdSymDFT(TDCT2, s, SSE_8x16i, rec(verify := true, fracbits := 8)), [128]), dct3 := _defaultSizes(s->doSimdSymDFT(TDCT3, s, SSE_8x16i, rec(verify := true, fracbits := 8)), [128]), dct4 := _defaultSizes(s->doSimdSymDFT(TDCT4, s, SSE_8x16i, rec(verify := true)), 128*[1..4]), dst2 := _defaultSizes(s->doSimdSymDFT(TDST2, s, SSE_8x16i, rec(verify := true)), 128*[1..4]), dst3 := _defaultSizes(s->doSimdSymDFT(TDST3, s, SSE_8x16i, rec(verify := true)), 128*[1..4]), dst4 := _defaultSizes(s->doSimdSymDFT(TDST4, s, SSE_8x16i, rec(verify := true)), 128*[1..4]), mdct := _defaultSizes(s->doSimdSymDFT(TMDCT, s, SSE_8x16i, rec(verify :=true)), 128*[1..4]), imdct := _defaultSizes(s->doSimdSymDFT(TMDCT, s, SSE_8x16i, rec(verify :=true)), 128*[1..4]) ), 2d := rec( dft_ic := rec( medium := _defaultSizes(s->doSimdMddft(s, SSE_8x16i, rec(interleavedComplex := true, oddSizes := false, svct := true, splitL := false, pushTag := true, flipIxA := false, stdTTensor := true, tsplPFA := false)), 64*List([1..2], i->[i,i])), small := _defaultSizes(s->doSimdMddft(s, SSE_8x16i, rec(verify:=true, interleavedComplex := true, globalUnrolling:=10000, tsplPFA := false, pushTag:= false, oddSizes := true, svct := true, splitL := false)), List([2..16], i->[i,i])) ), dft_sc := rec( medium := _defaultSizes(s->doSimdMddft(s, SSE_8x16i, rec(interleavedComplex := false, oddSizes := false, svct := true, splitL := false, pushTag := true, flipIxA := false, stdTTensor := true, tsplPFA := false)), 64*List([1..2], i->[i,i])), small := _defaultSizes(s->doSimdMddft(s, SSE_8x16i, rec(verify:=true, interleavedComplex := false, globalUnrolling:=10000, tsplPFA := false, pushTag:= false, oddSizes := true, svct := true, splitL := false)), List([2..16], i->[i,i])) ), dct2 := _defaultSizes(s->doSimdSymMDDFT(DCT2, s, SSE_8x16i, rec(verify := true, fracbits := 10)), [8, 16]), dct3 := _defaultSizes(s->doSimdSymMDDFT(DCT3, s, SSE_8x16i, rec(verify := true, fracbits := 10)), [8, 16]), dct4 := _defaultSizes(s->doSimdSymMDDFT(DCT4, s, SSE_8x16i, rec(verify := true, fracbits := 10)), [8, 16]), dst2 := _defaultSizes(s->doSimdSymMDDFT(DST2, s, SSE_8x16i, rec(verify := true, fracbits := 10)), [8, 16]), dst3 := _defaultSizes(s->doSimdSymMDDFT(DST3, s, SSE_8x16i, rec(verify := true, fracbits := 10)), [8, 16]), dst4 := _defaultSizes(s->doSimdSymMDDFT(DST4, s, SSE_8x16i, rec(verify := true, fracbits := 10)), [8, 16]) ) ) ); else return false; fi; end;
# Tarea 5 _Tarea 5_ de _Benjamín Rivera_ para el curso de __Métodos Numéricos__ impartido por _Joaquín Peña Acevedo_. Fecha limite de entrega __4 de Octubre de 2020__. ### Como ejecutar ##### Requerimientos Este programa se ejecuto en mi computadora con la version de __Python 3.8.2__ y con estos [requerimientos](https://github.com/BenchHPZ/UG-Compu/blob/master/MN/requerimientos.txt) #### Jupyter En caso de tener acceso a un _servidor jupyter_ ,con los requerimientos antes mencionados, unicamente basta con ejecutar todas las celdas de este _notebook_. Probablemente no todas las celdas de _markdown_ produzcan el mismo resultado por las [_Nbextensions_](jupyter-contrib-nbextensions.readthedocs.io). #### Consola Habrá archivos e instrucciones para poder ejecutar cada uno de los ejercicios desde la consola. #### Si todo sale mal <a href="https://colab.research.google.com/gist/BenchHPZ/"> </a> En caso de que todo salga mal, tratare de dejar una copia disponible en __GoogleColab__ que se pueda ejecutar con la versión de __Python__ de _GoogleColab_ ```python usage = """ Programa correspondiente a la Tarea 5 de Metodos Numericos. Este programa espera leer los archivos de tipo npy Alumno: Benjamin Rivera Usage: Tarea5.py ejercicio1 <matA> <vecB> <N>[--path=<path>] Tarea5.py -h | --help Options: -h --help Show this screen. -v --version Show version. --path=<path> Directorio para buscar archivos [default: data/]. """ import sys import scipy import numpy as np import matplotlib.pyplot as plt from scipy.linalg import solve_triangular # Para backward y forward substitution NOTEBOOK = True if __name__ == "__main__" and not NOTEBOOK: import doctest from docopt import docopt doctest.testmod() args = docopt(usage, version='Tarea4, prb') if args['ejercicio3']: Ejercicio3(args['<matA>'], args['<vecB>'], args['<N>'], args['--path']) ``` ## Ejercicio 1 Considere la matriz \begin{equation*} A = \begin{pmatrix} a^2 & a & a/2 & 1 \\ a & -9 & 1 & 0 \\ a/2 & 1 & 10 & 0 \\ 1 & 0 & 0 & a \end{pmatrix} \end{equation*} Da un rango de valores para $a$ de manera que garantice la convergencia del método de Jacobi. ### Resp Por las notas del curso (ppt clase 9, diapositiva 8-41), sabemos que el método de Jacobi converge cuando la matriz $A$ es \textbf{estrictamente diagonal dominante}. Y esto es cierto cuando \begin{equation*} \forall i \in [1,\dots,n] , |a_{i,i}| > \sum_{j=1, j\neq i}^{n} |a_{i,j}| \end{equation*} si extendemos estas desigualdades para la matriz $A$ nos queda que \begin{eqnarray} sol &=& \begin{cases} |a^2| &>& |a| + |a/2| + |1| \\ |-9| &>& |a| + |1| + |0| \\ |10| &>& |a/2| + |1| + |0| \\ |a| &>& |1| + |0| + |0| \end{cases} \\ && \text{despues de simplificar queda que} \\ &=& \begin{cases} a^2 &>& |a| + |a/2| + 1 \\ 8 &>& |a| \\ 9 &>& |a/2| \\ |a| &>& 1 \end{cases} \\ && \\ &=& \begin{cases} a^2 &>& |a| + |a/2| + 1 \\ 64 &>& a^2 \\ 4*91 &>& a^2 \\ a^2 &>& 1 \end{cases} \label{eq: red}\\ && \text{realcionamos \ref{eq: red}.4 con \ref{eq: red}.3 y \ref{eq: red}.2} \\ &=& \begin{cases} a^2 &>& |a| + |a/2| + 1 \\ 8^2 &>& a^2 > 1\\ 4*9^2 &>& a^2 > 1\\ \end{cases} \label{eq: cuadrado}\\ && \text{de esto solo nos importa \ref{eq: cuadrado}.1 y \ref{eq: cuadrado}.2} \\ &=& \begin{cases} a^2 &>& 3|a|/2 + 1 \\ 8 &>& a > 1\\ \end{cases} \label{eq: final}\\ \end{eqnarray} Podemos calcular los intervalos de soluci\'on de \ref{eq: final}. Estos quedan \begin{equation} \begin{cases} a^2 > 3|a|/2 + 1 &\Rightarrow& (-\infty, -2) \cup(2, \infty) \\ 8 > a > 1 &\Rightarrow& (1, 8) \end{cases} \label{eq: casi sol} \end{equation} Y la solucion que buscamos es la interseccion de \ref{eq: casi sol}. De manera que, para que la matriz $A$ converja con el metodo de Jacobi, se necesita que $x \in (2,8)$. ## Ejercicio 2 Sea $A \in \mathbb R^{n\times n}$ una matriz tridiagonal y que las tres diagonales de interes se almacenan en un arreglo $B_{n \times 3}$. Escribe las expresiones para calcular las actualizaciones de las componentes del vector $x^{i+1} = \left( x^{i+1}_0, \dots, x^{i+1}_{n-1} \right)$ de acuerdo con \textit{Gauss-Seidel}. Especificamente escribir la expresion para actualizar $x^{i+1}_0, x^{i+1}_i$ para $i = 1,2,\dots, n-2$; ademas de $x^{i+1}_{n-1}$ usando los coeficientes $a_{i,j}$ de $A$ y $b_{ij}$ de $B$. ### Respuesta \par Sea $A$ una matriz tridiagonal con elementos $a_{i,j}$, $B$ el arreglo descrito anteriormente con elementos $b'_{i,j}$, $b$ el vector de terminos independientes con elementos $b_i$ y $x$ el vector solucion con $x_i^{(t)}$ su elemento $i$ de la iteraci\'on $t$. \par Se da que en el m\'etodo de \textit{Gauss-Seidel} original tenemos que los componentes $x^{(t+1)}$ se calculan siguiendo \verb|forwardSubstitution| \begin{equation} x_{i}^{(t+1)} = \frac{1}{a_{i,i}}\left( b_i - \sum_{j=0}^{i-1} a_{j,j}x_{j}^{(t+1)} - \sum_{j=i+1}^{n-1} a_{i,j}x_j^{(t)}\right) \label{eq: GS original} \end{equation} \noindent pero como en este ejercicio estamos trabajando con una matriz tridiagonal, lo que implica que solo habr\'a elementos distitnos de cero en las tres diagonales de interes; entonces podemos reescribir la ecuaci\'on~\ref{eq: GS original}, lo que queda como \begin{eqnarray*} x_{i}^{(t+1)} &=& \frac{1}{a_{i,i}}\left( b_i - a_{i, j-1}x_{i-1}^{t+1} - a_{i, j+1}x_{i+1}^{t}\right) \label{eq: GS tridiagonal} \\ &=& \frac{1}{b'_{1,i}}\left( b_i - b'_{i,0}x_{i-1}^{t+1} - b'_{i,2}x_{i+1}^{t}\right) \qquad\text{Usando el arreglo B} \label{eq: GS tridiagonal con B} \end{eqnarray*} \noindent esto se puede usar $\forall i = 0,1,\dots,n-1,n$ sobre el arreglo $B$. \par Espec\'ificamente podemos definir al elemento $x_0^{t+1}$ como \begin{eqnarray*} x_0^{t+1} &=& \frac{1}{a_{0,0}} \left( b_0 - a_{0, 1}x_1^{t} \right) \\ &=& \frac{1}{b_{0,1}} \left( b_0 - b'_{0, 2}x_1^{t} \right) \end{eqnarray*} \noindent y para el elemento $x_{n-1}^{i+1}$ queda que \begin{eqnarray*} x_{n-1}^{i+1} &=& \frac{1}{a_{n-1,n-1}} \left( b_{n-1} - a_{n-1, n-2}x_{n-2}^{t+1} \right) \\ &=& \frac{1}{a_{n-1,1}} \left( b_{n-1} - b'_{n-1, 0}x_{n-2}^{t+1} \right) \end{eqnarray*} ## Ejercicio 3 Programa el metodo de \textit{Gauss-Seidel} para resolver sistemas tridiagonales. ```python # Extras def data4mFile(n_file,/,path='datos/npy/', ext='npy', dtype=np.float64): """ Cargar matrices y vectores de memoria Funcion para cargar los archivos en memoria. El nombre del archivo no espera path, ni la extension, solo el nombre. Por default trata de leer los archivos .npy, pero numpy soporta leer de otros formatos. Input: n_file := nombre del archivo sin extension path := directorio para buscar el archivo ext := extension del archivo a buscar (sin punto) dtype := tipo de dato para guardar los valores Output: Regresa el una instancia np.matrix con los datos obtenidos del archivo cargado. """ try: return np.asmatrix(np.load(file=str(path+n_file+'.'+ext), allow_pickle=False), dtype=dtype) except: raise Exception("Error al cargar la informacion.") def show1D(vec,/, max_sz=8, show=True): """ Implementacion para pprint vector 1D. Funcion para generar string para poder imporimir un vector de manera reducida, dando un maximo de elementos a imprimir. Lo puede imprimir directamente si se quiere Input: vec := vector de informacion a imprimir. [opcionales] max_sz := Maximo de elementos a imprimir. show := Imprimir vector _Doctest: >>> show1D([1,2,3,4], show=False) '1, 2, 3, 4' >>> show1D([1,2,3,4,5,6,7,8,9], show=False) '1, 2, 3, 4, ..., 6, 7, 8, 9' """ n=0 # En caso de que venga de instancia de np.data try: shape = vec.shape if len(shape) < 2: raise Exception('Array 1D') else: if shape[0] == 1: get = lambda i: vec[0,i] n = shape[1] elif shape[1] == 1: get = lambda i: vec[i,0] n = shape[0] else: raise Exception('No arreglo 1D') except AttributeError: get = lambda i: vec[i] n = len(vec) except Exception('No arreglo 1D'): print(e) ret = ' ' if n <= max_sz: for i in range(n): ret += str(get(i))+', ' else: for i in range(4): ret += str(get(i))+', ' ret += '..., ' for i in range(4): ret += str(get(-(4-i)))+', ' ret = ret[2:-2] if show: print(ret) return ret ``` ```python # Parte 1 def diagonalesRelevantes(A, dtype=np.float64): """ Funcion que otiene las diagonales relevantes de A. Esta funcion, con A una matriz tridiagonal cuadrada(n) extrae_ ra las diagonales relevantes y las pondra en un arreglo B de 3xn, donde la columna 0 correspondera a la diagonal -1, la col_ umna 1 a la diagonal de A y la columna 2 a la diagonal +1 de la matriz A. Se espera, y corrobora, que A sea instancia de np.matrix para usar su metodos Input: A := Matriz tridiagonal cuadrada instancia de np.matrix Output: B := Arreglo de valores relevantes de A """ if isinstance(A, (np.matrix)): # Verificar instancia de numpy n = A.shape[0] if A.shape[0]==A.shape[1] else 0 # Verificar A es cuadrada B = np.zeros((n, 3), dtype=dtype) # Reservar memoria de B B[1:, 0] = A.diagonal(-1) # Diagonal inferior B[ :, 1] = A.diagonal( 0) # Diagonal de matriz B[:-1,2] = A.diagonal( 1) # Diagonal superior return B else: raise Exception("A no es instancia de np.matrix") ``` ```python # Parte 2 def error_GS(B, xt, b,/, dtype=np.float64): """ Funcion para calular el error || Ax^t - b|| desde B """ n = len(xt) # esperamos que las dimensiones coincidan vec = np.asmatrix(np.zeros((n,1)), dtype=dtype) # En vec generaremos Ax^t vec[0,0] = B[0,1]*xt[0,0] + B[0,2]*xt[1,0] # Calculamos el primer elemento # Calculamos hasta el penultimo for i in range(1, n-1): vec[i,0] = B[i,0]*xt[i-1,0] + B[i,1]*xt[i,0] + B[i,2]*xt[i+1,0] n = n-1 # Calculamos el ultimo vec[n,0] = B[n,0]*xt[n-1,0] + B[n,1]*xt[n,0] return np.linalg.norm(vec - b) def GaussSeidel_tridiagonal(B, xt, b, N,/, t=None, dtype=np.float64): """ Implementacion de GaussSeidel para matrices tridiagonales. Esta funcion trata de resolver un sistema de ecuaciones Ax = b con A una matriz (nxn) cuadrada tridiagonal y estas diagonales almacenadas en el arreglo B (3xn). Respecto a la tolerancia t del metodo, en caso de ser None, se tomara el epsilon para el tipo de dato dtype que se le pase a la funcion (calculado por numpy) Input: B := arreglo (3xn) de la diagonales relecantes para el metodo x0 := vector (nx1) inicial de aproximacion de respuestas b := vector (nx1) de terminos independientes N := maximo numero de iteraciones del metodo t := Tolerancia del metodo (default: None) dtype := Tipop de dato para trabajar con el metodo Output: x, n, e x := vector respuesta en la iteracion en que se detenga n := iteracion en la que se detuvo el metodo e := error al momento de detenerse """ # Inicializacion if t == None: t = np.finfo(dtype).eps # Correcion tolerancia sz = len(b) e = float('inf') # Error inicial es infinito n = 0 # Iteracion inicial while n < N: # Primer elemento de iteracion i = 0 xt[i,0] = (b[i,0] - B[i,2]*xt[i+1,0])/B[i,1] # Iteracion del metodo for i in range(1, sz-1): xt[i,0] = (b[i,0] - B[i,0]*xt[i-1,0] - B[i,2]*xt[i+1,0])/B[i,1] # Ultimo elemento de iteracion i = sz-1 xt[i,0] = (b[i,0] - B[i,0]*xt[i-1,0])/B[i,1] # avance bucle verificacion tolerancia e = error_GS(B, xt, b, dtype=dtype) if e < t: break n += 1 return xt, n, e ``` ```python # Parte 3 def Ejercicio3(mat, vecb, N,/, path='datos/npy/', show=True): """ Funcion para ejecutar la parte 3 de la tarea Esta funcion usara las funciones diagonalesRelevantes, error_GS, GaussSeidel_tridiagonal, data4mFile y show1D para tratar de resolver un sistema Ax = b mediante la variante del metodo de Gauss-Seidel para matrices tridiagonales cuadradas Input: mat := nombre del archivo que contiene una matriz tridiagonal vecb := nombre del archivo con el vector de terminos independientes N := numero maximo de iteraciones para el metodo path := directorio para buscar los archivos show := Indica si se desea imprimir los detalles """ dtype = np.float64 t = (np.finfo(dtype).eps)**(1/2) A = data4mFile(mat, dtype=dtype) b = data4mFile(vecb, dtype=dtype).transpose() x0 = np.zeros(b.shape, dtype=dtype) # Suponemos que A si es tridiagonal B = diagonalesRelevantes(A, dtype=dtype) xt, n, e = GaussSeidel_tridiagonal(B, x0, b, N, t=t, dtype=dtype) conv = True if e < t else False if show: # Segunda solucion x = np.linalg.solve(A, b) # Print __ = f'Matriz de "{mat}" con el vector de "{vecb}"' __ += f'\n\tIteraciones: {n}' __ += f'\n\tError: {e}' __ += f'\n\tSol: {show1D(xt,show=False)}\n' __ += ('El metodo converge' if e < t else 'El metodo no converge') __ += f'\nLa diferencia entre soluciones es {np.linalg.norm(x - xt)}' print(__) return e, n, conv ``` ```python # Parte 4 if NOTEBOOK: sizes = ['6', '20', '500'] data = {} for sz in sizes: data[sz] = [[],[],[]] itr = [0, 5, 10, 15, 20, 25, 35, 50] for sz in sizes: for N in itr: e, n, conv = Ejercicio3('matrizA'+sz, 'vecb'+sz, N, show=True) data[sz][0].append(e) data[sz][1].append(n) data[sz][2].append(conv) ``` Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 0 Error: inf Sol: 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 El metodo no converge La diferencia entre soluciones es 2.449489742783178 Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 5 Error: 0.00022626705409276946 Sol: 0.9999715782516367, 1.000046095638286, 0.9999528204288628, 1.000020636310501, 0.9999923716262922, 1.0000011924468593 El metodo no converge La diferencia entre soluciones es 7.51264727492206e-05 Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 9 Error: 1.8517803127045294e-09 Sol: 1.0000000003609595, 0.9999999996391488, 1.0000000003090268, 0.9999999998701277, 1.0000000000473834, 0.9999999999925931 El metodo converge La diferencia entre soluciones es 6.125110654833705e-10 Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 9 Error: 1.8517803127045294e-09 Sol: 1.0000000003609595, 0.9999999996391488, 1.0000000003090268, 0.9999999998701277, 1.0000000000473834, 0.9999999999925931 El metodo converge La diferencia entre soluciones es 6.125110654833705e-10 Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 9 Error: 1.8517803127045294e-09 Sol: 1.0000000003609595, 0.9999999996391488, 1.0000000003090268, 0.9999999998701277, 1.0000000000473834, 0.9999999999925931 El metodo converge La diferencia entre soluciones es 6.125110654833705e-10 Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 9 Error: 1.8517803127045294e-09 Sol: 1.0000000003609595, 0.9999999996391488, 1.0000000003090268, 0.9999999998701277, 1.0000000000473834, 0.9999999999925931 El metodo converge La diferencia entre soluciones es 6.125110654833705e-10 Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 9 Error: 1.8517803127045294e-09 Sol: 1.0000000003609595, 0.9999999996391488, 1.0000000003090268, 0.9999999998701277, 1.0000000000473834, 0.9999999999925931 El metodo converge La diferencia entre soluciones es 6.125110654833705e-10 Matriz de "matrizA6" con el vector de "vecb6" Iteraciones: 9 Error: 1.8517803127045294e-09 Sol: 1.0000000003609595, 0.9999999996391488, 1.0000000003090268, 0.9999999998701277, 1.0000000000473834, 0.9999999999925931 El metodo converge La diferencia entre soluciones es 6.125110654833705e-10 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 0 Error: inf Sol: 0.0, 0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0, 0.0 El metodo no converge La diferencia entre soluciones es 44.72135954999579 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 5 Error: 5.2135922638126534e+17 Sol: 10510715.21822592, 1872849342.4323115, 335161007203.7978, 30692230637880.035, ..., 4.099992817956197e+16, 4.332425697334634e+17, 3.365085604102188e+17, 6.572227164204795e+17 El metodo no converge La diferencia entre soluciones es 8.573144572254433e+17 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 10 Error: 2.1453562634774947e+30 Sol: -4.325493091370833e+19, -7.706464998382885e+21, -1.3791289121479942e+24, -1.2629315580338113e+26, ..., -1.687103028015392e+29, -1.782760425966517e+30, -1.3847085054535812e+30, -2.704424173623813e+30 El metodo no converge La diferencia entre soluciones es 3.527786386918865e+30 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 15 Error: 8.827765445581566e+42 Sol: 1.7798646821865153e+32, 3.171075432413957e+34, 5.674874034154363e+36, 5.196742264243895e+38, ..., 6.942133605708313e+41, 7.335747052314032e+42, 5.69783308475235e+42, 1.1128232022110846e+43 El metodo no converge La diferencia entre soluciones es 1.451622338717728e+43 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 20 Error: 3.6324709362165934e+55 Sol: -7.323831572435901e+44, -1.3048420255161528e+47, -2.3351113169951127e+49, -2.1383684641646873e+51, ..., -2.8565664452140027e+54, -3.0185314876376157e+55, -2.3445585643800182e+55, -4.5790726589847025e+55 El metodo no converge La diferencia entre soluciones es 5.97317179331505e+55 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 25 Error: 1.4946981978392363e+68 Sol: 3.0136284762679543e+57, 5.3691965008129655e+59, 9.608574269562953e+61, 8.799011873257374e+63, ..., 1.1754270832835685e+67, 1.242072862774836e+68, 9.647448038654873e+67, 1.8842082349289435e+68 El metodo no converge La diferencia entre soluciones es 2.4578556226939094e+68 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 35 Error: 2.5307907379234587e+93 Sol: 5.102610711852639e+82, 9.091007665622408e+84, 1.6269030631878133e+87, 1.4898297050140288e+89, ..., 1.990207775575571e+92, 2.1030509714140467e+93, 1.6334850858936836e+93, 3.190300728381666e+93 El metodo no converge La diferencia entre soluciones es 4.1615881079264364e+93 Matriz de "matrizA20" con el vector de "vecb20" Iteraciones: 50 Error: 1.7632355142337908e+131 Sol: -3.5550566420321894e+120, -6.3338257628323356e+122, -1.1334849682523423e+125, -1.0379841393747967e+127, ..., -1.3866041858041658e+130, -1.4652235388231731e+131, -1.1380707508761582e+131, -2.2227248824152343e+131 El metodo no converge La diferencia entre soluciones es 2.8994336977579156e+131 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 0 Error: inf Sol: 0.0, 0.0, 0.0, 0.0, ..., 0.0, 0.0, 0.0, 0.0 El metodo no converge La diferencia entre soluciones es 2236.06797749979 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 5 Error: 14.176187474228898 Sol: -99.63958099545093, 99.47440006331433, -99.59286032243953, 99.70598909314587, ..., -99.91668866583471, 99.9348818313726, -99.96581153196503, 99.99173629461029 El metodo no converge La diferencia entre soluciones es 5.874263087048714 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 10 Error: 0.038973335267423345 Sol: -99.99917521831776, 99.99893028154601, -99.99925001852736, 99.99948437479507, ..., -99.99998299574862, 99.99998753009527, -99.99999350241926, 99.9999984294677 El metodo no converge La diferencia entre soluciones es 0.015979939541367193 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 15 Error: 0.00010199731641958948 Sol: -99.99999855757989, 99.99999805927155, -99.99999854223792, 99.99999893159874, ..., -99.99999999646232, 99.99999999750894, -99.99999999870863, 99.99999999968786 El metodo no converge La diferencia entre soluciones es 4.2453048360324766e-05 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 20 Error: 2.970999512048245e-07 Sol: -99.99999999713852, 99.99999999618126, -99.99999999708542, 99.99999999772496, ..., -99.9999999999992, 99.99999999999949, -99.99999999999974, 99.99999999999993 El metodo no converge La diferencia entre soluciones es 1.2607776366756404e-07 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 22 Error: 9.286484050814949e-09 Sol: -99.99999999992775, 99.9999999998994, -99.99999999991924, 99.99999999993344, ..., -99.99999999999999, 100.0, -100.0, 100.0 El metodo converge La diferencia entre soluciones es 3.9575573020619025e-09 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 22 Error: 9.286484050814949e-09 Sol: -99.99999999992775, 99.9999999998994, -99.99999999991924, 99.99999999993344, ..., -99.99999999999999, 100.0, -100.0, 100.0 El metodo converge La diferencia entre soluciones es 3.9575573020619025e-09 Matriz de "matrizA500" con el vector de "vecb500" Iteraciones: 22 Error: 9.286484050814949e-09 Sol: -99.99999999992775, 99.9999999998994, -99.99999999991924, 99.99999999993344, ..., -99.99999999999999, 100.0, -100.0, 100.0 El metodo converge La diferencia entre soluciones es 3.9575573020619025e-09 ```python PLOT = True if PLOT: rng = itr fig, ax = plt.subplots(2, 2, figsize=(10,10)) ax[0,1].axis('off') for sz in sizes: if sz == '6': i,j = 0,0 elif sz == '20': i,j = 1,0 elif sz == '500': i,j = 1,1 ax[i,j].set_title(sz) a = ax[i,j].plot(rng, data[sz][0], '-x') b = ax[i,j].plot(rng, data[sz][1], '-o') c = ax[i,j].plot(rng, data[sz][2], '*') labels = ['error', 'iteraciones', 'conv'] fig.legend([e, i, c], # The line objects labels=labels, # The labels for each line loc="upper right", # Position of legend borderaxespad=0.1, # Small spacing around legend box fontsize='xx-large' ) plt.show() ``` En la figura anterior podemos ver como convergen, o no, el metodo para los distintos datos proporcionados. Se grafica el error, de manera directa; las iteraciones con las que termina el metodo; y si converge o no, donde 0 es no y 1 es si. Todos estos datos se grafican contra el limite superior de iteraciones que se le pasa al metodo. ```python ```
#' @title Read Config #' @description Read contents of configuration. Throw warning if not present and use default config. #' @importFrom config get #' @importFrom rlang warn read_config <- function(path){ if(is.null(path) || !file.exists(path)){ rlang::warn(paste0("Config file not found: ", path, collapse="")) cfg <- failed_config() }else{ cfg <-tryCatch(expr=get_config(path), error=failed_config()) } return(cfg) } #' @title Get Config #' @description Wrapper for config::get get_config <- function(path){ config::get(file=path, config = "default", use_parent = FALSE) } #' @title Failed Config #' @description handler function for config read error. Returns default config failed_config <- function(){ rlang::warn("FAILED READING CONFIG") list(clc=GOCC$DEFAULT_CFG, hbpc=GOCC$DEFAULT_CFG, dementia=GOCC$DEFAULT_CFG) }
[STATEMENT] lemma linear_eq_on: assumes l: "linear s1 s2 f" "linear s1 s2 g" assumes x: "x \<in> vs1.span B" and eq: "\<And>b. b \<in> B \<Longrightarrow> f b = g b" shows "f x = g x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f x = g x [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. f x = g x [PROOF STEP] interpret d: linear s1 s2 "\<lambda>x. f x - g x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. linear (*a) (*b) (\<lambda>x. f x - g x) [PROOF STEP] using l [PROOF STATE] proof (prove) using this: linear (*a) (*b) f linear (*a) (*b) g goal (1 subgoal): 1. linear (*a) (*b) (\<lambda>x. f x - g x) [PROOF STEP] by (intro linear_compose_sub) (auto simp: module_hom_iff_linear) [PROOF STATE] proof (state) goal (1 subgoal): 1. f x = g x [PROOF STEP] have "f x - g x = 0" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f x - g x = (0::'c) [PROOF STEP] by (rule d.eq_0_on_span[OF _ x]) (auto simp: eq) [PROOF STATE] proof (state) this: f x - g x = (0::'c) goal (1 subgoal): 1. f x = g x [PROOF STEP] then [PROOF STATE] proof (chain) picking this: f x - g x = (0::'c) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: f x - g x = (0::'c) goal (1 subgoal): 1. f x = g x [PROOF STEP] by auto [PROOF STATE] proof (state) this: f x = g x goal: No subgoals! [PROOF STEP] qed
module Main %default total data U : Type where BOOL : U NAT : U PAIR : U -> U -> U interpU : U -> Type interpU BOOL = Bool interpU NAT = Nat interpU (PAIR x y) = (interpU x, interpU y) showU : (u : U) -> interpU u -> String showU BOOL True = "Yes" showU BOOL False = "No" showU NAT Z = "Z" showU NAT (S x) = "S of " ++ showU NAT x showU (PAIR tx ty) (x , y) = "(" ++ showU tx x ++ "," ++ showU ty y ++ ")" main : IO () main = putStrLn $ showU NAT 0
# Logical Design ## Objective and Prerequisites In this example, you’ll learn how to solve a logical design problem, which involves constructing a circuit using the minimum number of NOR gates (devices with two inputs and one output) that will perform the logical function specified by a truth table. We’ll show you how to formulate this problem as a binary optimization problem using the Gurobi Python API and then use Gurobi Optimizer to automatically find the optimal solution. This model is example 12 from the fifth edition of Model Building in Mathematical Programming by H. Paul Williams on pages 266-267 and 320-321. This example is at the intermediate level, where we assume that you know Python and the Gurobi Python API and that you have some knowledge of building mathematical optimization models. **Download the Repository** <br /> You can download the repository containing this and other examples by clicking [here](https://github.com/Gurobi/modeling-examples/archive/master.zip). ## Problem Description Logical circuits have a given number of inputs and one output. Impulses may be applied to the inputs of a given logical circuit, and it will respond by giving either an output (signal 1) or no output (signal 0). The input impulses are of the same kind as the outputs - 1 (positive input) or 0 (no input). In this example, a logical circuit is to be built up of NOR gates. A NOR gate is a device with two inputs and one output. It has the property that there is positive output (signal 1) if and only if neither input is positive, that is, both inputs have the value 0. By connecting such gates together with outputs from one gate possibly being inputs into another gate, it is possible to construct a circuit to perform any desired logical function. For example, the circuit illustrated in the following figure will respond to the inputs A and B in the way indicated by the truth table. The objective is to construct a circuit using the minimum number of NOR gates that will perform the logical function specified by the following truth table. | A | B | Output | | --- | --- | --- | | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ‘Fan-in’ and ‘fan-out’ are not permitted. That is, more than one output from a NOR gate cannot lead into one input nor can one output lead into more than one input. It may be assumed throughout that the optimal design is a ‘subnet’ of the ‘maximal’ net shown in the following figure. ## Model Formulation ### Sets and Indices $i \in \text{Gates}=\{1,...,7\}$ $i \in \text{G47}=\{4,...,7\}$ $r \in \text{Rows}=\{1,...,4\}$ ### Parameters $\text{valueA}_{i,r} \in \{0,1 \}$: Value of the external input A in row $r$ of the truth table for gate $i$. $\text{valueB}_{i,r} \in \{0,1 \}$: Value of the external input B in row $r$ of the truth table for gate $i$. ### Decision Variables $\text{NOR}_{i} \in \{0,1 \}$: This binary variable is equal to 1, if NOR gate $i$ is selected, 0 otherwise. $\text{inputA}_{i} \in \{0,1 \}$: This binary variable is equal to 1, if external input A is an input to NOR gate $i$ , and 0 otherwise. $\text{inputB}_{i} \in \{0,1 \}$: This binary variable is equal to 1, if external input B is an input to NOR gate $i$ , and 0 otherwise. $\text{output}_{i,r} \in \{0,1 \}$: This binary variable is the output from gate $i$ for the combination of external input signals specified in row $r$ of the truth table. ### Constraints **External input**: A NOR gate can only have an external input if it exists. \begin{equation} \text{NOR}_{i} \geq \text{inputA}_{i} \quad \forall i \in \text{Gates} \end{equation} \begin{equation} \text{NOR}_{i} \geq \text{inputB}_{i} \quad \forall i \in \text{Gates} \end{equation} **NOR gates**:If a NOR gate has one (or two) external inputs leading into it, only one (or no) NOR gates can feed into it. \begin{equation} \text{NOR}_{2} + \text{NOR}_{3} + \text{inputA}_{1} + \text{inputB}_{2} \leq 2 \end{equation} \begin{equation} \text{NOR}_{4} + \text{NOR}_{5} + \text{inputA}_{2} + \text{inputB}_{2} \leq 2 \end{equation} \begin{equation} \text{NOR}_{6} + \text{NOR}_{7} + \text{inputA}_{3} + \text{inputB}_{3} \leq 2 \end{equation} These constraints are based on the circuit shown in the figure of the ‘maximal’ net. **Output signals**: The output signal from NOR gate $i$ must be the correct logical function (NOR) of the input signals into gate $i$, if gate $i$ exists. \begin{equation} \text{output}_{2,r} + \text{output}_{1,r} \leq 1 \quad \forall r \in \text{Rows} \end{equation} \begin{equation} \text{output}_{3,r} + \text{output}_{1,r} \leq 1 \quad \forall r \in \text{Rows} \end{equation} \begin{equation} \text{valueA}_{i,r}*\text{inputA}_{i} + \text{output}_{i,r} \leq 1 \quad \forall i \in \text{Gates}, r \in \text{Rows} \end{equation} \begin{equation} \text{valueB}_{i,r}*\text{inputB}_{i} + \text{output}_{i,r} \leq 1 \quad \forall i \in \text{Gates}, r \in \text{Rows} \end{equation} \begin{equation} \text{valueA}_{i,r}*\text{inputA}_{i} + \text{valueB}_{i,r}*\text{inputB}_{i} + \text{output}_{i,r} - \text{NOR}_{i} \geq 0 \quad \forall i \in \text{G47}, r \in \text{Rows} \end{equation} \begin{equation} \text{valueA}_{1,r}*\text{inputA}_{1} + \text{valueB}_{1,r}*\text{inputB}_{1} + \text{output}_{2,r} + \text{output}_{3,r} + \text{output}_{1,r} - \text{NOR}_{1} \geq 0 \quad \forall r \in \text{Rows} \end{equation} \begin{equation} \text{valueA}_{2,r}*\text{inputA}_{2} + \text{valueB}_{2,r}*\text{inputB}_{2} + \text{output}_{4,r} + \text{output}_{5,r} + \text{output}_{2,r} - \text{NOR}_{2} \geq 0 \quad \forall r \in \text{Rows} \end{equation} \begin{equation} \text{valueA}_{3,r}*\text{inputA}_{3} + \text{valueB}_{3,r}*\text{inputB}_{3} + \text{output}_{6,r} + \text{output}_{7,r} + \text{output}_{3,r} - \text{NOR}_{3} \geq 0 \quad \forall r \in \text{Rows} \end{equation} **Gate 1**: For NOR gate 1, the output variables are fixed at the values specified in the truth table. \begin{equation} \text{output}_{1,1} = 0, \text{output}_{1,2} = 1, \text{output}_{1,3} = 1, \text{output}_{1,4} = 0 \end{equation} To avoid a trivial solution containing no NOR gates, it is necessary to impose a constraint that selects NOR gate 1. \begin{equation} \text{NOR}_{1} \geq 1 \end{equation} **Gates and output**: If there is an output signal of 1 from a particular NOR gate for any combination of the input signals, then that gate must exist. \begin{equation} \text{NOR}_{i} - \text{output}_{i,r} \geq 0 \quad \forall i \in \text{Gates}, r \in \text{Rows} \end{equation} ### Objective Function **Number of gates**: The objective is to minimize the number of NOR gates selected. \begin{equation} \text{Minimize} \quad \sum_{i \in \text{Gates}} \text{NOR}_{i} \end{equation} ## Python Implementation We import the Gurobi Python Module. ```python %pip install gurobipy ``` ```python import gurobipy as gp from gurobipy import GRB # tested with Python 3.7.0 & Gurobi 9.0 ``` ## Input data We define all the input data for the model. ```python # List of NOR gates 1 to 7. gates = ['1','2','3','4','5','6','7'] # List of NOR gates 4 to 7. gates47 = ['4','5','6','7'] # List of rows of the truth-table in the range 1 to 4. rows = ['1','2','3','4'] # Create a dictionary to capture the value of the external input A and B in the r row of the truth table, for each # NOR gate i. gatesRows, valueA, valueB = gp.multidict({ ('1','1'): [0,0], ('1','2'): [0,1], ('1','3'): [1,0], ('1','4'): [1,1], ('2','1'): [0,0], ('2','2'): [0,1], ('2','3'): [1,0], ('2','4'): [1,1], ('3','1'): [0,0], ('3','2'): [0,1], ('3','3'): [1,0], ('3','4'): [1,1], ('4','1'): [0,0], ('4','2'): [0,1], ('4','3'): [1,0], ('4','4'): [1,1], ('5','1'): [0,0], ('5','2'): [0,1], ('5','3'): [1,0], ('5','4'): [1,1], ('6','1'): [0,0], ('6','2'): [0,1], ('6','3'): [1,0], ('6','4'): [1,1], ('7','1'): [0,0], ('7','2'): [0,1], ('7','3'): [1,0], ('7','4'): [1,1] }) ``` ## Model Deployment We create a model and the variables. The main decision is to determine the $\text{NOR}_{i}$ variables that selects the NOR gates to consider in the logical circuit. The rest of the variables ensure that the circuit generates the output of the truth table. ```python model = gp.Model('logicalDesign') # Decision variables to select NOR gate i. NOR = model.addVars(gates, vtype=GRB.BINARY, name="NORgate" ) # In order to avoid a trivial solution containing no NOR gates, it is necessary to impose a constraint # that selects NOR gate 1. NOR['1'].lb = 1 # Variables to decide if external input A is an input to NOR gate i. inputA = model.addVars(gates, vtype=GRB.BINARY, name="inputA") # Variables to decide if external input B is an input to NOR gate i. inputB = model.addVars(gates, vtype=GRB.BINARY, name="inputB") # Output decision variables. output = model.addVars(gatesRows, vtype=GRB.BINARY, name="output") # For NOR gate 1, the output variables are fixed at the values specified in the truth table. output['1','1'].ub = 0 output['1','2'].lb = 1 output['1','3'].lb = 1 output['1','4'].ub = 0 ``` Using license file c:\gurobi\gurobi.lic A NOR gate can only have an external input if it exists. ```python # External inputs constraints externalInputsA = model.addConstrs( ( NOR[i] >= inputA[i] for i in gates), name='externalInputsA') externalInputsB = model.addConstrs( ( NOR[i] >= inputB[i] for i in gates), name='externalInputsB') ``` If a NOR gate has one (or two) external inputs leading into it, only one (or no) NOR gates can feed into it. ```python # NOR gates constraints NORgate1 = model.addConstr(NOR['2'] + NOR['3'] + inputA['1'] + inputB['1'] <= 2, name='NORgate1') NORgate2 = model.addConstr(NOR['4'] + NOR['5'] + inputA['2'] + inputB['2'] <= 2, name='NORgate2') NORgate3 = model.addConstr(NOR['6'] + NOR['7'] + inputA['3'] + inputB['3'] <= 2, name='NORgate3') ``` The output signal from NOR gate i must be the correct logical function (NOR) of the input signals into gate i, if gate i exists. ```python # Output signal constraint. outputSignals1_1 = model.addConstrs( (output['2',r] + output['1',r] <= 1 for r in rows), name='outputSignals1_1' ) outputSignals1_2 = model.addConstrs( (output['3',r] + output['1',r] <= 1 for r in rows), name='outputSignals1_2' ) outputSignals2_1 = model.addConstrs( (output['4',r] + output['2',r] <= 1 for r in rows), name='outputSignals2_1' ) outputSignals2_2 = model.addConstrs( (output['5',r] + output['2',r] <= 1 for r in rows), name='outputSignals2_2' ) outputSignals3_1 = model.addConstrs( (output['6',r] + output['3',r] <= 1 for r in rows), name='outputSignals3_1' ) outputSignals3_2 = model.addConstrs( (output['7',r] + output['3',r] <= 1 for r in rows), name='outputSignals3_2' ) outputSignals4 = model.addConstrs( (valueA[i,r]*inputA[i] + output[i,r] <= 1 for i,r in gatesRows), name='outputSignals4') outputSignals5 = model.addConstrs( (valueB[i,r]*inputB[i] + output[i,r] <= 1 for i,r in gatesRows), name='outputSignals5') outputSignals6 = model.addConstrs( (valueA[i,r]*inputA[i] + valueB[i,r]*inputB[i] + output[i,r] - NOR[i] >= 0 for i,r in gatesRows if i in gates47), name='outputSignals6') outputSignals7 = model.addConstrs( (valueA['1',r]*inputA['1'] + valueB['1',r]*inputB['1'] + output['2',r] + output['3',r] + output['1',r] - NOR['1'] >= 0 for i,r in gatesRows), name='outputSignals7') outputSignals8 = model.addConstrs( (valueA['2',r]*inputA['2'] + valueB['2',r]*inputB['2'] + output['4',r] + output['5',r] + output['2',r] - NOR['2'] >= 0 for i,r in gatesRows), name='outputSignals8') outputSignals9 = model.addConstrs( (valueA['3',r]*inputA['3'] + valueB['3',r]*inputB['3'] + output['6',r] + output['7',r] + output['3',r] - NOR['3'] >= 0 for i,r in gatesRows), name='outputSignals9') ``` If there is an output signal of 1 from a particular NOR gate for any combination of the input signals, then that gate must exist. ```python # Gate and output signals constraints gateOutput = model.addConstrs( (NOR[i] - output[i,r] >= 0 for i,r in gatesRows) , name='gateOutput') ``` The objective is to minimize the number of NOR gates selected. ```python # Objective function. model.setObjective(NOR.sum(), GRB.MINIMIZE) ``` ```python # Verify model formulation model.write('logicalDesign.lp') # Run optimization engine model.optimize() ``` Gurobi Optimizer version 9.1.0 build v9.1.0rc0 (win64) Thread count: 4 physical cores, 8 logical processors, using up to 8 threads Optimize a model with 225 rows, 49 columns and 696 nonzeros Model fingerprint: 0x9adba516 Variable types: 0 continuous, 49 integer (49 binary) Coefficient statistics: Matrix range [1e+00, 1e+00] Objective range [1e+00, 1e+00] Bounds range [1e+00, 1e+00] RHS range [1e+00, 2e+00] Presolve removed 225 rows and 49 columns Presolve time: 0.00s Presolve: All rows and columns removed Explored 0 nodes (0 simplex iterations) in 0.01 seconds Thread count was 1 (of 8 available processors) Solution count 1: 5 Optimal solution found (tolerance 1.00e-04) Best objective 5.000000000000e+00, best bound 5.000000000000e+00, gap 0.0000% ```python # Output reports print("\n\n_________________________________________________________________________________") print(f"The optimal circuit design:") print("_________________________________________________________________________________") for i in gates: if (NOR[i].x > 0.5): if (inputA[i].x + inputB[i].x > 0.5): print(f"NOR gate {i} is active, with external inputs A and B values of {inputA[i].x} and {inputB[i].x}.") else: print(f"NOR gate {i} is active.") ``` _________________________________________________________________________________ The optimal circuit design: _________________________________________________________________________________ NOR gate 1 is active. NOR gate 2 is active, with external inputs A and B values of 1.0 and 1.0. NOR gate 3 is active. NOR gate 6 is active, with external inputs A and B values of 0.0 and 1.0. NOR gate 7 is active, with external inputs A and B values of 1.0 and 0.0. ## References H. Paul Williams, Model Building in Mathematical Programming, fifth edition. Copyright © 2020 Gurobi Optimization, LLC ```python ```
[STATEMENT] lemma subterms_trans [elim]: assumes "q \<in> subterms p" and "r \<in> subterms q" shows "r \<in> subterms p" [PROOF STATE] proof (prove) goal (1 subgoal): 1. r \<in> subterms p [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: q \<in> subterms p r \<in> subterms q goal (1 subgoal): 1. r \<in> subterms p [PROOF STEP] by (induction p) auto
Oh, those government spell-checkers. . . . As one guy here said when he saw the goof, “At banks, people get fired for that kind of oversight (regardless of the irrelevance).” Yes, they do. . . .
Residents and businessmen in the Washoe Valley, Pleasant Valley area generally see the Interstate 580 freeway extension as a mixed blessing. Once open, Nevada Department of Transportation officials say as much as 70 percent of the traffic on Highway 395 will move to the freeway, greatly reducing the traffic on the old road. Chris Jacobsen, who lives in what he described as a luxury home in Washoe Valley, agreed it will be a blessing for the residential areas along the current Highway 395 route. But Jacobsen, a consultant who advises businesses – primarily convenience stores – on where best to locate, said it will overall hurt the businesses in Washoe City. He said that applies especially to convenience stores, the gas station and businesses like the Chocolate Factory and Nevada Lynn Emporium which rely on impulse buyers seeing them and deciding to stop. He said Paul Marazzo, owner of Washoe Flats restaurant – formerly the Cattleman’s – may benefit because his is a destination rather than an impulse stop. Marazzo is counting on that. He said when the trucks and other through traffic move to the new freeway, it will also make it much easier and safer for drivers seeking a nice dinner at the restaurant he and his brother, Lynn, operate. And, as the valley develops, he said he’ll get more and more local business. At the same time, he said the freeway will make it easier for people to come to his restaurant because they’ll be able to take the freeway to Parker Ranch Road just south of the restaurant. And in the meantime, he said the freeway construction crews are excellent customers. She said traffic is the issue and she has been involved in efforts to get people to slow down through the valley. Tyson Petty, manager of Old Washoe Station, the gas station and mini-mart to the north, made similar comments. Couch and Petty both said their businesses may be hurt somewhat but neither thought the loss of traffic would put them out of business.
Formal statement is: lemma metric_LIM_equal2: fixes a :: "'a::metric_space" assumes "g \<midarrow>a\<rightarrow> l" "0 < R" and "\<And>x. x \<noteq> a \<Longrightarrow> dist x a < R \<Longrightarrow> f x = g x" shows "f \<midarrow>a\<rightarrow> l" Informal statement is: Suppose $f$ and $g$ are real-valued functions defined on a metric space $X$, and $a$ is a limit point of $X$. If $g$ converges to $l$ at $a$, and $f$ and $g$ agree on the punctured ball of radius $R$ around $a$, then $f$ converges to $l$ at $a$.
(* Author: Gertrud Bauer, Tobias Nipkow *) header "Summation Over Lists" theory ListSum imports ListAux begin primrec ListSum :: "'b list \<Rightarrow> ('b \<Rightarrow> 'a::comm_monoid_add) \<Rightarrow> 'a::comm_monoid_add" where "ListSum [] f = 0" | "ListSum (l#ls) f = f l + ListSum ls f" syntax "_ListSum" :: "idt \<Rightarrow> 'b list \<Rightarrow> ('a::comm_monoid_add) \<Rightarrow> ('a::comm_monoid_add)" ("\<Sum>\<^bsub>_\<in>_\<^esub> _" [0, 0, 10] 10) translations "\<Sum>\<^bsub>x\<in>xs\<^esub> f" == "CONST ListSum xs (\<lambda>x. f)" lemma ListSum_compl1: "(\<Sum>\<^bsub>x \<in> [x\<leftarrow>xs. \<not> P x]\<^esub> f x) + (\<Sum>\<^bsub>x \<in> [x\<leftarrow>xs. P x]\<^esub> f x) = (\<Sum>\<^bsub>x \<in> xs\<^esub> (f x::nat))" by (induct xs) simp_all lemma ListSum_compl2: "(\<Sum>\<^bsub>x \<in> [x\<leftarrow>xs. P x]\<^esub> f x) + (\<Sum>\<^bsub>x \<in> [x\<leftarrow>xs. \<not> P x]\<^esub> f x) = (\<Sum>\<^bsub>x \<in> xs\<^esub> (f x::nat))" by (induct xs) simp_all lemmas ListSum_compl = ListSum_compl1 ListSum_compl2 lemma ListSum_conv_setsum: "distinct xs \<Longrightarrow> ListSum xs f = setsum f (set xs)" by(induct xs) simp_all lemma listsum_cong: "\<lbrakk> xs = ys; \<And>y. y \<in> set ys ==> f y = g y \<rbrakk> \<Longrightarrow> ListSum xs f = ListSum ys g" apply simp apply(erule thin_rl) by (induct ys) simp_all lemma strong_listsum_cong[cong]: "\<lbrakk> xs = ys; \<And>y. y \<in> set ys =simp=> f y = g y \<rbrakk> \<Longrightarrow> ListSum xs f = ListSum ys g" by(auto simp:simp_implies_def intro!:listsum_cong) lemma ListSum_eq [trans]: "(\<And>v. v \<in> set V \<Longrightarrow> f v = g v) \<Longrightarrow> (\<Sum>\<^bsub>v \<in> V\<^esub> f v) = (\<Sum>\<^bsub>v \<in> V\<^esub> g v)" by(auto intro!:listsum_cong) lemma ListSum_disj_union: "distinct A \<Longrightarrow> distinct B \<Longrightarrow> distinct C \<Longrightarrow> set C = set A \<union> set B \<Longrightarrow> set A \<inter> set B = {} \<Longrightarrow> (\<Sum>\<^bsub>a \<in> C\<^esub> (f a)) = (\<Sum>\<^bsub>a \<in> A\<^esub> f a) + (\<Sum>\<^bsub>a \<in> B\<^esub> (f a::nat))" by (simp add: ListSum_conv_setsum setsum.union_disjoint) lemma listsum_const[simp]: "(\<Sum>\<^bsub>x \<in> xs\<^esub> k) = length xs * k" by (induct xs) (simp_all add: ring_distribs) lemma ListSum_add: "(\<Sum>\<^bsub>x \<in> V\<^esub> f x) + (\<Sum>\<^bsub>x \<in> V\<^esub> g x) = (\<Sum>\<^bsub>x \<in> V\<^esub> (f x + (g x::nat)))" by (induct V) auto lemma ListSum_le: "(\<And>v. v \<in> set V \<Longrightarrow> f v \<le> g v) \<Longrightarrow> (\<Sum>\<^bsub>v \<in> V\<^esub> f v) \<le> (\<Sum>\<^bsub>v \<in> V\<^esub> (g v::nat))" proof (induct V) case Nil then show ?case by simp next case (Cons v V) then have "(\<Sum>\<^bsub>v \<in> V\<^esub> f v) \<le> (\<Sum>\<^bsub>v \<in> V\<^esub> g v)" by simp moreover from Cons have "f v \<le> g v" by simp ultimately show ?case by simp qed lemma ListSum1_bound: "a \<in> set F \<Longrightarrow> (d a::nat)\<le> (\<Sum>\<^bsub>f \<in> F\<^esub> d f)" by (induct F) auto end
20071111 18:20:55 nbsp Howdy, Dan. Was Tamar Segev the Vice president back in 0506? Unless theres a factual error, it would likely be better to keep the info there just for historical reasons. As the history section grows, it can eventually be moved to a different entry to keep the main one svelte, so theres no real reason to remove information like that unless it is factually incorrect. Users/JabberWokky
section \<open>Lens Instances\<close> theory Lens_Instances imports Lens_Order Lens_Symmetric "HOL-Eisbach.Eisbach" keywords "alphabet" "statespace" :: "thy_defn" begin text \<open>In this section we define a number of concrete instantiations of the lens locales, including functions lenses, list lenses, and record lenses.\<close> subsection \<open>Function Lens\<close> text \<open>A function lens views the valuation associated with a particular domain element @{typ "'a"}. We require that range type of a lens function has cardinality of at least 2; this ensures that properties of independence are provable.\<close> definition fun_lens :: "'a \<Rightarrow> ('b::two \<Longrightarrow> ('a \<Rightarrow> 'b))" where [lens_defs]: "fun_lens x = \<lparr> lens_get = (\<lambda> f. f x), lens_put = (\<lambda> f u. f(x := u)) \<rparr>" lemma fun_vwb_lens: "vwb_lens (fun_lens x)" by (unfold_locales, simp_all add: fun_lens_def) text \<open>Two function lenses are independent if and only if the domain elements are different.\<close> lemma fun_lens_indep: "fun_lens x \<bowtie> fun_lens y \<longleftrightarrow> x \<noteq> y" proof - obtain u v :: "'a::two" where "u \<noteq> v" using two_diff by auto thus ?thesis by (auto simp add: fun_lens_def lens_indep_def) qed subsection \<open>Function Range Lens\<close> text \<open>The function range lens allows us to focus on a particular region of a function's range.\<close> definition fun_ran_lens :: "('c \<Longrightarrow> 'b) \<Rightarrow> (('a \<Rightarrow> 'b) \<Longrightarrow> '\<alpha>) \<Rightarrow> (('a \<Rightarrow> 'c) \<Longrightarrow> '\<alpha>)" where [lens_defs]: "fun_ran_lens X Y = \<lparr> lens_get = \<lambda> s. get\<^bsub>X\<^esub> \<circ> get\<^bsub>Y\<^esub> s , lens_put = \<lambda> s v. put\<^bsub>Y\<^esub> s (\<lambda> x::'a. put\<^bsub>X\<^esub> (get\<^bsub>Y\<^esub> s x) (v x)) \<rparr>" lemma fun_ran_mwb_lens: "\<lbrakk> mwb_lens X; mwb_lens Y \<rbrakk> \<Longrightarrow> mwb_lens (fun_ran_lens X Y)" by (unfold_locales, auto simp add: fun_ran_lens_def) lemma fun_ran_wb_lens: "\<lbrakk> wb_lens X; wb_lens Y \<rbrakk> \<Longrightarrow> wb_lens (fun_ran_lens X Y)" by (unfold_locales, auto simp add: fun_ran_lens_def) lemma fun_ran_vwb_lens: "\<lbrakk> vwb_lens X; vwb_lens Y \<rbrakk> \<Longrightarrow> vwb_lens (fun_ran_lens X Y)" by (unfold_locales, auto simp add: fun_ran_lens_def) subsection \<open>Map Lens\<close> text \<open>The map lens allows us to focus on a particular region of a partial function's range. It is only a mainly well-behaved lens because it does not satisfy the PutGet law when the view is not in the domain.\<close> definition map_lens :: "'a \<Rightarrow> ('b \<Longrightarrow> ('a \<rightharpoonup> 'b))" where [lens_defs]: "map_lens x = \<lparr> lens_get = (\<lambda> f. the (f x)), lens_put = (\<lambda> f u. f(x \<mapsto> u)) \<rparr>" lemma map_mwb_lens: "mwb_lens (map_lens x)" by (unfold_locales, simp_all add: map_lens_def) lemma source_map_lens: "\<S>\<^bsub>map_lens x\<^esub> = {f. x \<in> dom(f)}" by (force simp add: map_lens_def lens_source_def) subsection \<open>List Lens\<close> text \<open>The list lens allows us to view a particular element of a list. In order to show it is mainly well-behaved we need to define to additional list functions. The following function adds a number undefined elements to the end of a list.\<close> definition list_pad_out :: "'a list \<Rightarrow> nat \<Rightarrow> 'a list" where "list_pad_out xs k = xs @ replicate (k + 1 - length xs) undefined" text \<open>The following function is like @{term "list_update"} but it adds additional elements to the list if the list isn't long enough first.\<close> definition list_augment :: "'a list \<Rightarrow> nat \<Rightarrow> 'a \<Rightarrow> 'a list" where "list_augment xs k v = (list_pad_out xs k)[k := v]" text \<open>The following function is like @{term nth} but it expressly returns @{term undefined} when the list isn't long enough.\<close> definition nth' :: "'a list \<Rightarrow> nat \<Rightarrow> 'a" where "nth' xs i = (if (length xs > i) then xs ! i else undefined)" text \<open>We can prove some additional laws about list update and append.\<close> lemma list_update_append_lemma1: "i < length xs \<Longrightarrow> xs[i := v] @ ys = (xs @ ys)[i := v]" by (simp add: list_update_append) lemma list_update_append_lemma2: "i < length ys \<Longrightarrow> xs @ ys[i := v] = (xs @ ys)[i + length xs := v]" by (simp add: list_update_append) text \<open>We can also prove some laws about our new operators.\<close> lemma nth'_0 [simp]: "nth' (x # xs) 0 = x" by (simp add: nth'_def) lemma nth'_Suc [simp]: "nth' (x # xs) (Suc n) = nth' xs n" by (simp add: nth'_def) lemma list_augment_0 [simp]: "list_augment (x # xs) 0 y = y # xs" by (simp add: list_augment_def list_pad_out_def) lemma list_augment_Suc [simp]: "list_augment (x # xs) (Suc n) y = x # list_augment xs n y" by (simp add: list_augment_def list_pad_out_def) lemma list_augment_twice: "list_augment (list_augment xs i u) j v = (list_pad_out xs (max i j))[i:=u, j:=v]" apply (auto simp add: list_augment_def list_pad_out_def list_update_append_lemma1 replicate_add[THEN sym] max_def) apply (metis Suc_le_mono add.commute diff_diff_add diff_le_mono le_add_diff_inverse2) done lemma list_augment_last [simp]: "list_augment (xs @ [y]) (length xs) z = xs @ [z]" by (induct xs, simp_all) lemma list_augment_idem [simp]: "i < length xs \<Longrightarrow> list_augment xs i (xs ! i) = xs" by (simp add: list_augment_def list_pad_out_def) text \<open>We can now prove that @{term list_augment} is commutative for different (arbitrary) indices.\<close> lemma list_augment_commute: "i \<noteq> j \<Longrightarrow> list_augment (list_augment \<sigma> j v) i u = list_augment (list_augment \<sigma> i u) j v" by (simp add: list_augment_twice list_update_swap max.commute) text \<open>We can also prove that we can always retrieve an element we have added to the list, since @{term list_augment} extends the list when necessary. This isn't true of @{term list_update}. \<close> lemma nth_list_augment: "list_augment xs k v ! k = v" by (simp add: list_augment_def list_pad_out_def) lemma nth'_list_augment: "nth' (list_augment xs k v) k = v" by (auto simp add: nth'_def nth_list_augment list_augment_def list_pad_out_def) text \<open> The length is expanded if not already long enough, or otherwise left as it is. \<close> lemma length_list_augment_1: "k \<ge> length xs \<Longrightarrow> length (list_augment xs k v) = Suc k" by (simp add: list_augment_def list_pad_out_def) lemma length_list_augment_2: "k < length xs \<Longrightarrow> length (list_augment xs k v) = length xs" by (simp add: list_augment_def list_pad_out_def) text \<open>We also have it that @{term list_augment} cancels itself.\<close> lemma list_augment_same_twice: "list_augment (list_augment xs k u) k v = list_augment xs k v" by (simp add: list_augment_def list_pad_out_def) lemma nth'_list_augment_diff: "i \<noteq> j \<Longrightarrow> nth' (list_augment \<sigma> i v) j = nth' \<sigma> j" by (auto simp add: list_augment_def list_pad_out_def nth_append nth'_def) text \<open>Finally we can create the list lenses, of which there are three varieties. One that allows us to view an index, one that allows us to view the head, and one that allows us to view the tail. They are all mainly well-behaved lenses.\<close> definition list_lens :: "nat \<Rightarrow> ('a::two \<Longrightarrow> 'a list)" where [lens_defs]: "list_lens i = \<lparr> lens_get = (\<lambda> xs. nth' xs i) , lens_put = (\<lambda> xs x. list_augment xs i x) \<rparr>" abbreviation hd_lens ("hd\<^sub>L") where "hd_lens \<equiv> list_lens 0" definition tl_lens :: "'a list \<Longrightarrow> 'a list" ("tl\<^sub>L") where [lens_defs]: "tl_lens = \<lparr> lens_get = (\<lambda> xs. tl xs) , lens_put = (\<lambda> xs xs'. hd xs # xs') \<rparr>" lemma list_mwb_lens: "mwb_lens (list_lens x)" by (unfold_locales, simp_all add: list_lens_def nth'_list_augment list_augment_same_twice) text \<open> The set of constructible sources is precisely those where the length is greater than the given index. \<close> lemma source_list_lens: "\<S>\<^bsub>list_lens i\<^esub> = {xs. length xs > i}" apply (auto simp add: lens_source_def list_lens_def) apply (metis length_list_augment_1 length_list_augment_2 lessI not_less) apply (metis list_augment_idem) done lemma tail_lens_mwb: "mwb_lens tl\<^sub>L" by (unfold_locales, simp_all add: tl_lens_def) lemma source_tail_lens: "\<S>\<^bsub>tl\<^sub>L\<^esub> = {xs. xs \<noteq> []}" using list.exhaust_sel by (auto simp add: tl_lens_def lens_source_def) text \<open>Independence of list lenses follows when the two indices are different.\<close> lemma list_lens_indep: "i \<noteq> j \<Longrightarrow> list_lens i \<bowtie> list_lens j" by (simp add: list_lens_def lens_indep_def list_augment_commute nth'_list_augment_diff) lemma hd_tl_lens_indep [simp]: "hd\<^sub>L \<bowtie> tl\<^sub>L" apply (rule lens_indepI) apply (simp_all add: list_lens_def tl_lens_def) apply (metis hd_conv_nth hd_def length_greater_0_conv list.case(1) nth'_def nth'_list_augment) apply (metis (full_types) hd_conv_nth hd_def length_greater_0_conv list.case(1) nth'_def) apply (metis One_nat_def diff_Suc_Suc diff_zero length_0_conv length_list_augment_1 length_tl linorder_not_less list.exhaust list.sel(2) list.sel(3) list_augment_0 not_less_zero) done lemma hd_tl_lens_pbij: "pbij_lens (hd\<^sub>L +\<^sub>L tl\<^sub>L)" by (unfold_locales, auto simp add: lens_defs) subsection \<open>Record Field Lenses\<close> text \<open>We also add support for record lenses. Every record created can yield a lens for each field. These cannot be created generically and thus must be defined case by case as new records are created. We thus create a new Isabelle outer syntax command \textbf{alphabet} which enables this. We first create syntax that allows us to obtain a lens from a given field using the internal record syntax translations.\<close> abbreviation (input) "fld_put f \<equiv> (\<lambda> \<sigma> u. f (\<lambda>_. u) \<sigma>)" syntax "_FLDLENS" :: "id \<Rightarrow> logic" ("FLDLENS _") translations "FLDLENS x" => "\<lparr> lens_get = x, lens_put = CONST fld_put (_update_name x) \<rparr>" text \<open> We also allow the extraction of the "base lens", which characterises all the fields added by a record without the extension. \<close> syntax "_BASELENS" :: "id \<Rightarrow> logic" ("BASELENS _") abbreviation (input) "base_lens t e m \<equiv> \<lparr> lens_get = t, lens_put = \<lambda> s v. e v (m s) \<rparr>" ML \<open> fun baselens_tr [Free (name, _)] = let val extend = Free (name ^ ".extend", dummyT); val truncate = Free (name ^ ".truncate", dummyT); val more = Free (name ^ ".more", dummyT); in Const (@{const_syntax "base_lens"}, dummyT) $ truncate $ extend $ more end | baselens_tr _ = raise Match; \<close> parse_translation \<open>[(@{syntax_const "_BASELENS"}, K baselens_tr)]\<close> text \<open>We also introduce the \textbf{alphabet} command that creates a record with lenses for each field. For each field a lens is created together with a proof that it is very well-behaved, and for each pair of lenses an independence theorem is generated. Alphabets can also be extended which yields sublens proofs between the extension field lens and record extension lenses. \<close> ML_file \<open>Lens_Lib.ML\<close> ML_file \<open>Lens_Record.ML\<close> text \<open>The following theorem attribute stores splitting theorems for alphabet types which which is useful for proof automation.\<close> named_theorems alpha_splits subsection \<open>Locale State Spaces \<close> text \<open> Alternative to the alphabet command, we also introduce the statespace command, which implements Schirmer and Wenzel's locale-based approach to state space modelling~\cite{Schirmer2009}. It has the advantage of allowing multiple inheritance of state spaces, and also variable names are fully internalised with the locales. The approach is also far simpler than record-based state spaces. It has the disadvantage that variables may not be fully polymorphic, unlike for the alphabet command. This makes it in general unsuitable for UTP theory alphabets. \<close> ML_file \<open>Lens_Statespace.ML\<close> subsection \<open>Type Definition Lens\<close> text \<open> Every type defined by a \<^bold>\<open>typedef\<close> command induces a partial bijective lens constructed using the abstraction and representation functions. \<close> context type_definition begin definition typedef_lens :: "'b \<Longrightarrow> 'a" ("typedef\<^sub>L") where [lens_defs]: "typedef\<^sub>L = \<lparr> lens_get = Abs, lens_put = (\<lambda> s. Rep) \<rparr>" lemma pbij_typedef_lens [simp]: "pbij_lens typedef\<^sub>L" by (unfold_locales, simp_all add: lens_defs Rep_inverse) lemma source_typedef_lens: "\<S>\<^bsub>typedef\<^sub>L\<^esub> = A" using Rep_cases by (auto simp add: lens_source_def lens_defs Rep) lemma bij_typedef_lens_UNIV: "A = UNIV \<Longrightarrow> bij_lens typedef\<^sub>L" by (auto intro: pbij_vwb_is_bij_lens simp add: mwb_UNIV_src_is_vwb_lens source_typedef_lens) end subsection \<open>Mapper Lenses\<close> definition lmap_lens :: "(('\<alpha> \<Rightarrow> '\<beta>) \<Rightarrow> ('\<gamma> \<Rightarrow> '\<delta>)) \<Rightarrow> (('\<beta> \<Rightarrow> '\<alpha>) \<Rightarrow> '\<delta> \<Rightarrow> '\<gamma>) \<Rightarrow> ('\<gamma> \<Rightarrow> '\<alpha>) \<Rightarrow> ('\<beta> \<Longrightarrow> '\<alpha>) \<Rightarrow> ('\<delta> \<Longrightarrow> '\<gamma>)" where [lens_defs]: "lmap_lens f g h l = \<lparr> lens_get = f (get\<^bsub>l\<^esub>), lens_put = g o (put\<^bsub>l\<^esub>) o h \<rparr>" text \<open> The parse translation below yields a heterogeneous mapping lens for any record type. This achieved through the utility function above that constructs a functorial lens. This takes as input a heterogeneous mapping function that lifts a function on a record's extension type to an update on the entire record, and also the record's ``more'' function. The first input is given twice as it has different polymorphic types, being effectively a type functor construction which are not explicitly supported by HOL. We note that the \<open>more_update\<close> function does something similar to the extension lifting, but is not precisely suitable here since it only considers homogeneous functions, namely of type \<open>'a \<Rightarrow> 'a\<close> rather than \<open>'a \<Rightarrow> 'b\<close>. \<close> syntax "_lmap" :: "id \<Rightarrow> logic" ("lmap[_]") ML \<open> fun lmap_tr [Free (name, _)] = let val extend = Free (name ^ ".extend", dummyT); val truncate = Free (name ^ ".truncate", dummyT); val more = Free (name ^ ".more", dummyT); val map_ext = Abs ("f", dummyT, Abs ("r", dummyT, extend $ (truncate $ Bound 0) $ (Bound 1 $ (more $ (Bound 0))))) in Const (@{const_syntax "lmap_lens"}, dummyT) $ map_ext $ map_ext $ more end | lmap_tr _ = raise Match; \<close> parse_translation \<open>[(@{syntax_const "_lmap"}, K lmap_tr)]\<close> subsection \<open>Lens Interpretation\<close> named_theorems lens_interp_laws locale lens_interp = interp begin declare meta_interp_law [lens_interp_laws] declare all_interp_law [lens_interp_laws] declare exists_interp_law [lens_interp_laws] end subsection \<open> Tactic \<close> text \<open> A simple tactic for simplifying lens expressions \<close> declare split_paired_all [alpha_splits] method lens_simp = (simp add: alpha_splits lens_defs prod.case_eq_if) end
# Heat diffusion - toc:false - branch: master - badges: true - comments: false - categories: [mathematics, numerical recipes] - hide: true ----- Questions: - How can I describe heat diffusion using a PDE? - What is the Laplacian operator? - What are boundary conditions? Objectives: ----- ### Partial differential equations have multiple inputs In the previous section of the course we studied <bold>ordinary differential equations</bold>. ODEs have a single input (also known as dependent variable) - for example, time. Partial differential equations (PDEs) have multiple inputs (dependent variables). For example, think about a sheet of metal that has been heated unevenly across the surface. Over time, heat will diffuse through the 2-dimensional sheet. The temperature depends on both time *and* position - there are two inputs. > Youtube: https://www.youtube.com/watch?v=twBcpxrWm5E Because PDEs have multiple inputs they are generally much more difficult to solve analytically than ODEs. However, there are a range of numerical methods that can be used to find approximate solutions. ### PDEs have application across a wide variety of topics The same type of PDE often appears in different contexts. For example, the <bold>diffusion equation</bold> takes the form: \begin{equation} \nabla^2T = \alpha \frac{\partial T}{\partial t} \end{equation} When used to describe heat diffusion, this PDE is known as the heat equation. This same PDE however can be used to model other seemingly unrelated processes such as brownian motion, or used in financial modelling via the Black-Sholes equation. Another type of PDE is known as <bold>Poisson's equation</bold>: \begin{equation} \nabla^2\phi = f(x,y,z) \end{equation} Poisson's equation can be used to describe electrostatic forces, where $\phi$ is the electric potential. It can also be applied to mechanics (where $\phi$ is the gravitational potential) or thermodynamics (where $\phi$ is the temperature). When $f(x,y,z)=0$ this equation is known as <bold>Laplace's equation</bold>. The third common type of PDE is the <bold>wave equation</bold>: \begin{equation} \nabla^2r = \alpha \frac{\partial^2 r}{\partial t^2} \end{equation} This describes mechanical processes such as the vibration of a string or the motion of a pendulum. It can also be used in electrodynamics to describe the exchange of energy between the electric and magnetic fields. In this course we will focus on only the heat equation, but many of the topics we will discuss - such as boundary conditions, and finite difference methods - can be transferred to PDEs more generally. ### The Laplacian operator corresponds to an average rate of change *But what is the operator $\nabla^2$?*. This is the <bold>Laplacian operator</bold>. When applied to $\phi$ and written in full for a three dimensional cartesian coordinate system with dependent variables $x$, $y$ and $z$ it takes the following form: \begin{equation} \nabla^2\phi = \frac{\partial^2\phi}{\partial x^2} + \frac{\partial^2\phi}{\partial y^2} + \frac{\partial^2\phi}{\partial z^2}. \end{equation} We can think of the laplacian as encoding an average rate of change. To better develop an intuition for how the laplacian can be interpreted physically, we need to understand two related operators - div and curl. We will not explore these operators further in this lesson, but a related video is below: > Youtube: https://youtu.be/EW08rD-GFh0 ### PDEs can have boundary values and initial values In the previous section of the course we learnt that ODEs have either initial values or boundary values. PDEs can also be separated in a similar manner. <bold>Boundary value problems</bold> describe the behaviour of a variable in a space and we are given some constraints on the variable around the boundary of that space. For example, consider a box with one wall at voltage $V$ and all others at voltage zero. The sprecification that one wall is at voltage $V$ and all others are at voltage zero are the boundary conditions. We could then calculate the electrostatic potential $\phi$ at all points within the box using Poisson's equation: \begin{equation} \nabla^2\phi = 0 \end{equation} <bold>Initial value problems</bold> are where the field - or other variable of interest - is varying in both space and time. We now require boundary conditions *and* initial values. For example, consider heat diffusion in a box. Here we could specify that there is no heat flow in or out of the box - this is the boundary condition. We could also specify that at time $t=0$ the centre of the box is at temperature $T_1$, whilst surrounding areas are at temperature $T_1$. This is the initial condition. It differs from a boundary condition in that we are told what the temperature is at the start of our time grid (at $t=0$) but not at the end of our time grid (when the simulation finishes). --- Keypoints: - Partial differential equations have multiple inputs - --- Do [the quick-test](https://nu-cem.github.io/CompPhys/2021/08/02/Heat-Diffusion-Qs.html). Back to [Modelling with Partial Differential Equations](https://nu-cem.github.io/CompPhys/2021/08/02/PDEs.html). --- ```python ```
[STATEMENT] lemma qbs_probI: assumes "\<alpha> \<in> qbs_Mx X" and "sets \<mu> = sets borel" and "prob_space \<mu>" shows "qbs_prob X \<alpha> \<mu>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. qbs_prob X \<alpha> \<mu> [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: \<alpha> \<in> qbs_Mx X sets \<mu> = sets real_borel prob_space \<mu> goal (1 subgoal): 1. qbs_prob X \<alpha> \<mu> [PROOF STEP] by(auto intro!: qbs_prob.intro simp: in_Mx_def real_distribution_def real_distribution_axioms_def)
#!/usr/bin/env python3 import numpy as np import csv import os ################################# Parameters ################################## # Input directory InputDir = "../data/PF/" # Output directory OutputDir = "../data/PF/SGLT_TK/" # Training trace file (input) TrainTraceFile = InputDir + "traintraces_TK.csv" # sg-LPM trace file (output) SglpmTraceFile = OutputDir + "input.trace" # sg-LPM mobility file (output) SglpmMobFile = OutputDir + "input.mobility" # sg-LPM location file (output) SglpmLocFile = OutputDir + "locations" # Minimum of y (latitude) MIN_Y = 35.65 # Maximum of y (latitude) MAX_Y = 35.75 # Minimum of x (longitude) MIN_X = 139.68 # Maximum of x (longitude) MAX_X = 139.8 # Number of regions on the x-axis #NumRegX = 10 #NumRegX = 15 NumRegX = 20 # Number of regions on the y-axis #NumRegY = 5 #NumRegY = 10 #NumRegY = 15 NumRegY = 20 #NumRegY = 25 #NumRegY = 30 #NumRegY = 35 #NumRegY = 40 #NumRegY = 45 #NumRegY = 50 ############################ Read training traces ############################# # [input1]: tracefile # [output1]: train_trace_list ([user_index, time_index, poi_index]) def ReadTrainTrace(tracefile): # Initialization train_trace_list = [] # Read training traces f = open(tracefile, "r") reader = csv.reader(f) next(reader) time_index = 0 user_index_pre = -1 for event in reader: user_index = int(event[0]) poi_index = int(event[1]) if user_index != user_index_pre: time_index = 0 train_trace_list.append([user_index, time_index, poi_index]) user_index_pre = user_index time_index += 1 f.close() return train_trace_list #################################### Main ##################################### # Make OutputDir if not os.path.exists(OutputDir): os.mkdir(OutputDir) # Number of POIs --> M M = NumRegX * NumRegY # Read training traces train_trace_list = ReadTrainTrace(TrainTraceFile) # Output sg-LPM trace data f = open(SglpmTraceFile, "w") writer = csv.writer(f, lineterminator="\n") for (user_index, time_index, poi_index) in train_trace_list: s = [user_index+1, time_index+1,poi_index+1] writer.writerow(s) f.close() # Output sg-LPM mobility information out_line = "1, " * (M - 1) + "1" f = open(SglpmMobFile, "w") for i in range(M): print(out_line, file=f) f.close() # Calculate the boundaries of the regions (NumRegX x NumRegY) [km] --> xb, yb # 1 degree of latitude (resp. longitude in TK) = 111 km (resp. 91 km) yb = np.zeros(NumRegY) xb = np.zeros(NumRegX) for i in range(NumRegY): yb[i] = ((MAX_Y - MIN_Y) * i / NumRegY) * 111 for i in range(NumRegX): xb[i] = ((MAX_X - MIN_X) * i / NumRegX) * 91 # Output sg-LPM location information f = open(SglpmLocFile, "w") for i in range(M): y_id = int(i / NumRegX) x_id = i % NumRegX out_line = '{:.4f}'.format(xb[x_id]) + ", " + '{:.4f}'.format(yb[y_id]) print(out_line, file=f) f.close()
module Main import Data.Vect infixr 5 .+. data Schema = SString | SInt | (.+.) Schema Schema SchemaType : Schema -> Type SchemaType SString = String SchemaType SInt = Int SchemaType (x .+. y) = (SchemaType x, SchemaType y) -- data DataStore : Type where -- MkData : (schema : Schema) -> (size : Nat) -> (items : Vect size (SchemaType schema)) -> DataStore record DataStore where constructor MkData schema : Schema size : Nat items : Vect size (SchemaType schema) -- data Command = Add String -- | Search String -- | Get Integer -- | Size -- | Quit data Command : Schema -> Type where Add : SchemaType schema -> Command schema Get : Integer -> Command schema SetSchema : (newschema : Schema) -> Command schema Quit : Command schema addToStore : (store : DataStore) -> SchemaType (schema store) -> DataStore addToStore (MkData schema size store) y = MkData schema _ (addToData store) where addToData : Vect old (SchemaType schema) -> Vect (S old) (SchemaType schema) addToData [] = [y] addToData (x :: xs) = x :: addToData xs sumInputs : Integer -> String -> Maybe (String, Integer) sumInputs tot inp = let val = cast inp in if val < 0 then Nothing else let newVal = tot + val in Just ("Subtotal: " ++ show newVal ++ "\n", newVal) parsePrefix : (schema : Schema) -> String -> Maybe (SchemaType schema, String) parsePrefix SString inp = getQuoted (unpack inp) where getQuoted : List Char -> Maybe (String, String) getQuoted ('"' :: xs) = case span (/= '"') xs of (quoted, '"' :: rest) => Just (pack quoted, ltrim (pack rest)) _ => Nothing getQuoted _ = Nothing parsePrefix SInt inp = case span isDigit inp of ("", rest) => Nothing (num, rest) => Just (cast num, ltrim rest) parsePrefix (x .+. y) inp = do l <- parsePrefix x inp r <- parsePrefix y $ snd l pure ((fst l, fst r), snd r) -- parsePrefix (x .+. y) inp = case parsePrefix x inp of -- Nothing => Nothing -- Just (lval, inp') => case parsePrefix y inp' of -- Nothing => Nothing -- Just (rval, inp'') => Just ((lval, rval), inp'') parseBySchema : (schema : Schema) -> (str : String) -> Maybe $ SchemaType schema parseBySchema schema inp = case parsePrefix schema inp of -- Just (res, "") => Just res Just _ => Nothing Nothing => Nothing parseCommand : (schema : Schema) -> (cmd : String) -> (args : String) -> Maybe (Command schema) parseCommand schema "add" str = case parseBySchema schema str of Nothing => Nothing Just r => Just (Add r) parseCommand schema "get" val = if all isDigit (unpack val) then Just (Get (cast val)) else Nothing parseCommand schema "quit" "" = Just Quit parseCommand schema _ args = Nothing parse : (schema : Schema) -> (input : String) -> Maybe (Command schema) parse schema input = case span (/= ' ') input of (cmd, args) => parseCommand schema cmd (ltrim args) display : SchemaType schema -> String display {schema = SString} item = show item display {schema = SInt} item = show item display {schema = (x .+. y)} (a, b) = display a ++ ", " ++ display b getEntry : (ind : Integer) -> (ds : DataStore) -> Maybe (String, DataStore) getEntry ind ds = let storeItems = items ds in (case (integerToFin ind (size ds)) of Nothing => Just ("Out of bounds \n", ds) (Just id) => Just (display (index id storeItems) ++ "\n", ds)) processInput : DataStore -> String -> Maybe (String, DataStore) processInput ds inp = case parse (schema ds) inp of Nothing => Just ("Invalid command inputed\n", ds) (Just x) => (case x of (Add item) => Just ("ID " ++ show (size ds) ++ "\n", addToStore ds item) (Get ind) => getEntry ind ds -- (Search str) => searchForEntry str ds -- Size => Just ("Size Of Datastore: " ++ show (size ds) ++ "\n", ds) Quit => Nothing) main : IO () main = replWith (MkData SString _ []) "Command: " processInput
% !TEX program = xelatex \documentclass{resume} %\usepackage{zh_CN-Adobefonts_external} % Simplified Chinese Support using external fonts (./fonts/zh_CN-Adobe/) %\usepackage{zh_CN-Adobefonts_internal} % Simplified Chinese Support using system fonts \begin{document} \pagenumbering{gobble} % suppress displaying page number \name{Ethan Bogart} \basicInfo{ \email{[email protected]} \textperiodcentered\ \faGithub\ github.com/EthanBogart} \smallskip \textbf{Full stack developer} with experience writing production frontend code with React and Angular, and a passion for other languages and frameworks like Go and Ruby on Rails. I love building software that serves a purpose. \section{\faCogs\ Skills} \begin{itemize}[parsep=0.5ex] \item Programming Languages: Javascript, Go, Ruby, Python, Java \item Frameworks: React, Redux, Rails, Angular 1, Ionic, Gorilla Mux, Node, D3 \item Databases: MySQL \item Tools: Webpack, Heroku, Git \end{itemize} \section{\faUsers\ Experience} \datedsubsection{\textbf{HubSpot} Cambridge, MA}{June 2017 -- August 2017} \role{Software Engineering Intern}\space Frontend engineering in React and Redux \begin{itemize} \item Rewrote user onboarding process to integrate with Redux \item Refactored and added unit tests for all actions \item Added a new message badge and a HubSpot branding option to the Messages product \end{itemize} \datedsubsection{\textbf{HomDNA} Newport Beach, CA}{May 2016 -- August 2016} \role{Software Engineering Intern} \space Hybrid mobile development with Node, Ionic and Angular 1 \begin{itemize} \item Greatly improved product searching experience with similarity checking \item Oversaw the entry of tens of thousands of home appliances to the product library \end{itemize} \datedsubsection{\textbf{Tulane University} New Orleans, LA}{September 2015 -- May 2016} \role{Teaching Assistant}\space Grading and office hours for Introduction to Computer Science % Reference Test %\datedsubsection{\textbf{Paper Title\cite{zaharia2012resilient}}}{May. 2015} %An xxx optimized for xxx\cite{verma2015large} %\begin{itemize} % \item main contribution %\end{itemize} \section{\faWrench\ Projects} \subsection{\textbf{Mr. Baseball Guy} Pebble Smartwatch App} Displays live baseball scores and information using PebbleJS platform, and a Node backend to send notifications. \begin{itemize} \item Store:\quad https://apps.getpebble.com/en\_US/application/57b17966f01b53ce0c000483?section=watchapps \end{itemize} \subsection{\textbf{Extinguish.io} Social Support Web Forum} Forum for women in abusive relationships, built with Ruby on Rails and a PostgreSQL backend, on Heroku. \subsection{\textbf{Swarm Satellite Scheduler} Undergraduate Capstone Project} Project with a professor to help NASA implement and optimize a solution for a unique temporal constraint satisfaction problem (TCSP), to coordinate multiple missions on a swarm of small satellites. Written in Java. \subsection{\textbf{PolyWrite} Electron Desktop App (Defunct)} User friendly document version control with UI. React/Redux/Electron frontend and a Go/MySQL backend. \section{\faGraduationCap\ Education} \datedsubsection{\textbf{Tulane University}, New Orleans, Louisiana}{2014 -- Present} \textit{Undergraduate} in Computer Science and Economics, Mathematics minor, expected graduation May 2018 \\ \textbf{3.77} GPA out of 4.0 in Computer Science %% Reference %\newpage %\bibliographystyle{IEEETran} %\bibliography{mycite} \end{document}
The historic house that South Africa's national hero Nelson Mandela and his family used to live in from 1946. It is located in Soweto, the black township on the edge of Johannesburg that also has many significant historical connections with the story of apartheid and the struggle against it. And there are a few more points of interest related to that as well in the area other than Mandela's House. More background info: The founding of the settlements of Soweto goes back to before the introduction of apartheid proper, but was still a result of segregation. It was deliberately created as a residential area for blacks only, to separate them from whites and get them out of white quarters. The collective name Soweto, short for South-West Township, however, wasn't used until the early 1960s. Small, squat, brick four-room houses (also known as “matchboxes”) were provided in the 1940s, and it was into one of those, originally built in 1945 and located in an area of Soweto called West Orlando, that then 28-year-old Nelson Mandela moved in 1946 together with his first wife. After their divorce he continued living there with his second wife Winnie Mandela from 1958. He was practising law at the time but had also already become a pivotal figure in the ANC's struggle against apartheid. After his arrest and imprisonment (see Robben Island), his family continued living in this same house, even after Winnie Mandela's own exile to Brandfort from 1977. After the abolition of apartheid when Nelson Mandela was released from prison, he briefly came back to this house in Soweto, if only for just 11 days. He then moved on to a bigger place elsewhere, namely in Houghton (see under Johannesburg). Some of the family stayed on in Soweto, but in 1996, when Winnie and Nelson Mandela divorced, they left and in 1997 Mandela donated the house to the newly formed Soweto Heritage Trust and it was declared a public heritage site. In 2008 the site was temporarily closed and reopened to the public in 2009 after 10 months of comprehensive restoration work. But back to Soweto as such: during the apartheid era Soweto grew to become the largest black township in South Africa. It was not yet incorporated into Johannesburg (that came only in 2002) but was a separate entity, yet provided the black workforce for white businesses in Johannesburg and the surrounding mines. With well over a million inhabitants it became a low-rise city in itself, yet one with only small houses, like the Mandelas', as well as vast areas of makeshift shacks that were, and still are, actually a shanty town, if not a slum, without electricity or running water. Soweto naturally also became a hotbed of protest against apartheid and a stage for civil unrest. As such Soweto also became a household name in the West. Especially so after the Soweto uprising of 1976, when students went on strike and marched in protest against the introduction of Afrikaans as the language of instruction in schools (a measure intended to further disenfranchise the black population). The police reacted with violence. They opened fire on the protesters, killing at least 176, and injuring over a thousand. Throughout the 1980s, Soweto remained a centre of resistance and, in return, a target of police reprisals. Besides Nelson Mandela, another key human-rights figure in the struggle against apartheid, Nobel Peace Prize laureate Desmond Tutu (see under apartheid and the Apartheid Museum), also had his residence in Soweto, in fact on the same street. He continued living in Soweto even after he'd become archbishop and could have moved to much more privileged accommodation provided by the church. Instead he decided to stay put in Soweto as a sign of solidarity. His house, though not open to the public, has become a firm fixture on tours of Soweto as well. Another such element is the Hector Pieterson Memorial, which was established in early 1990, and the museum joined it in 2002. It's named after the first victim of the Soweto uprising of 16 June 1976 (see above and, again, under apartheid and the Apartheid Museum), a 12-year-old schoolboy, who was shot dead by the police just a few blocks from here. The cooling towers used to be part of the old Orlando power station, which dated back to the 1930s, though it wasn't completed until 1955. It was a coal-fired power station serving Johannesburg until it was decommissioned in 1998. Most of the plant has been demolished, but the iconic towers were retained. They now serve as giant billboards and you can also go bungee-jumping from a bridge that has been installed between the two towers. What there is to see: When I went to Soweto it was as part of a longer day tour from Johannesburg, which first (and foremost) included the Apartheid Museum, before we carried on to Soweto. We entered Soweto at one of the more recently developed affluent parts, where well-to-do black families have built multi-bedroom two-storey houses, often with double garages as well, that wouldn't look out of place in any middle-class residential area anywhere in the West. So it wasn't the expected slum-like look that was my first impression. However, we did carry on to such areas – and ones in between. So we saw both less posh two-storey houses and long rows of workers' hostel housing, and also large shanty-town areas with nothing but the simplest, makeshift shacks built from wood, corrugated metal sheets and cardboard. It's here that the very poorest of Soweto's inhabitants live in squalid conditions still today. It is also those parts that have given rise to so-called slum tourism … being guided around by locals through these poorest of areas to get a glimpse of the kind of life they lead in these parts. My guide also offered getting us on such a walking tour with a local guide as an add-on to his tour (and at extra cost). However, I felt uncomfortable with the idea, said so, and declined. I was a bit torn, though, to be honest. On the one hand, going on such a tour would have given me insights on the basis of which I could have evaluated this form of tourism from first-hand experience. So it could have been useful. On the other hand, though, I've spoken out against the inclusion of 'slum tourism' under the banner of dark tourism so often (see also here under beyond dark tourism proper), that I thought it would be hypocritical of me to then jump on such a tour at the first opportunity. I'm still not quite sure if I made the right decision, but I know for certain that I would have felt very uncomfortable with the unavoidable element of voyeurism that necessarily comes with such tours. So from a personal, emotional point of view, I'm happy to have declined, while from a more distanced, pure research point of view I feel I may have lost out on valuable insights. It's a dilemma. Anyway, we continued to the main stop on our Soweto tour, where we got out of the car and walked, namely up Vilakazi Street, towards Mandela's House. It became instantly apparent that this is tourist central in Soweto. Nowhere in Soweto had I seen so many white people, all tourists, and there were (black) souvenir vendors everywhere so you had to fend off a lot of hassling. But once at Mandela's House, everything is very orderly indeed. Visitors have to go on a guided tour of the house, which lasts approximately 20 minutes. When it's busy you may have to wait a bit for the next tour to become available, as the maximum number on the tour is 20. The interior of the house is filled with both original (presumably) furnishings as well as with all manner of Mandela-related memorabilia, from certificates, diplomas, awards and other documents to sculptures, posters and photos from all stages of Mandela's life. Outside in the backyard stands a symbolic tomb stone with the words “RIP Tata 1918-2013” (“Tata” is one of the many nicknames given to Mandela, this one meaning 'father' in Xhosa). On the back wall of the house you can also still see bullet holes and scorch marks from Molotov cocktails … evidence of troubled times. But today it's a peaceful place (the brisk tourism trade these days notwithstanding). Incredibly, and uniquely, there's another Nobel Peace Prize winner's house just down the road, namely that of Desmond Tutu (see above and under apartheid). It's said to be the only location in the world where two Nobel laureates lived on the same street. Unlike Mandela's house, however, Tutu's house is not open to the public. But there is a historical marker plaque just outside. On my tour we also passed the Hector Pieterson Memorial that commemorates the Soweto uprising of 16 June 1976 (see above). But we didn't stop to also visit the attached museum. So I cannot say much about that. It's said to feature audio-visuals, testimonies, photos and historical documents illustrating those events and its aftermath. I wish I had known about this before, then I would have asked to visit the place (instead of the slum tour – see above). It would probably have been quite interesting. Shame. All in all, even though I don't think this visit to Soweto was a massive highlight of my time in Johannesburg, it was still a worthwhile addition to the trip to the Apartheid Museum. Mandela's House, though very small, is certainly a moving and worthwhile spot, and I guess the Hector Pieterson Museum would have been too, had we had time for it. If ever I go back to Jo'burg, I'll try and see it then. Location: Soweto's location is kind-of in its name: to the south-west of Johannesburg (South-West Township); more precisely the area is roughly 12 km (18 km) from the city centre (by car). Mandela's House is on Vilakazi Street, number 8115 Orlando West. Tutu's house is just down the road on the corner of Bacela Street. The Hector Pieterson Memorial is a few hundred yards to the north at the intersection of Pela Street and Khumalo Road, while the former cooling towers are south of Orlando East, just off the main road, Nicholas Street. Access and costs: far from Johannesburg city centre, but tours to Soweto are a well-established feature of the city's tourism industry. Prices vary. Details: It would be tricky, and not necessarily to be recommended, trying to get to Soweto on an independent basis, though it wouldn't be impossible (as the relevant parts of Soweto are connected to the public transport system). But there are various operators offering guided tours of Soweto. In fact these have become a very common and regular thing with much competition. Tours vary in length and nature, from half day to full day, and from private, by car, or group tours, including by bicycle. Prices vary accordingly, and widely, from ca. 400 to over 2000 ZAR. So it's best to shop around. For me the Soweto leg was part of a longer day tour of Johannesburg, which had been organized by the operator who I booked my whole 2018 St Helena, South Africa and Zimbabwe trip with, so I can't say what just this single component would have cost on its own. Admission to Mandela's House, including a 20-minute guided tour, costs 60 ZAR for international visitors (less for students, senior citizens, African Union members and children), opening times: daily from 9 a.m. to 4:45 p.m. (but closed on a few public holidays). Admission to the Hector Pieterson Museum is 30 ZAR (senior citizens and students: 10 ZAR); opening times: daily from 10 a.m. to 5 p.m. (only to 4 p.m. on Sundays). Time required: Just about half an hour for Mandela's house, and only a few moments for a look at Tutu's house and the cooling towers, but how long the Hector Pieterson Museum would take I cannot say, because I didn't have a chance to go inside, but I would guess under an hour. Add to all that driving and walking time and/or cycling. Combinations with other dark destinations: Obviously the Apartheid Museum has to be the most fitting combination here. In fact it is en route to Soweto from Johannesburg city centre, so combines geographically/logistically well too. For more see under Johannesburg. Combinations with non-dark destinations: see under Johannesburg and the Apartheid Museum.
Formal statement is: lemma continuous_polymonial_function: fixes f :: "'a::real_normed_vector \<Rightarrow> 'b::euclidean_space" assumes "polynomial_function f" shows "continuous (at x) f" Informal statement is: If $f$ is a polynomial function, then $f$ is continuous at $x$.
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: mgga_exc *) (* prefix: mgga_c_m05_params *params; assert(p->params != NULL); params = (mgga_c_m05_params * )(p->params); *) $define lda_c_pw_params $define lda_c_pw_modified_params $include "lda_c_pw.mpl" $include "b97.mpl" (* The parallel and perpendicular components of the energy *) m05_comp := (rs, z, spin, xs, t) -> + lda_stoll_par(f_pw, rs, z, 1) * b97_g(params_a_gamma_ss, params_a_css, xs) * Fermi_D_corrected(xs, t): m05_fpar := (rs, z, xs0, xs1, t0, t1) -> + m05_comp(rs, z, 1, xs0, t0) + m05_comp(rs, -z, -1, xs1, t1): m05_fperp := (rs, z, xs0, xs1, t0, t1) -> + lda_stoll_perp(f_pw, rs, z) * b97_g(params_a_gamma_ab, params_a_cab, sqrt(xs0^2 + xs1^2)): m05_f := (rs, z, xs0, xs1, t0, t1) -> + m05_fpar (rs, z, xs0, xs1, t0, t1) + m05_fperp(rs, z, xs0, xs1, t0, t1): f := (rs, z, xt, xs0, xs1, u0, u1, t0, t1) -> m05_f(rs, z, xs0, xs1, t0, t1):
/- Homework 2.4: Functional Programming — Metaprogramming -/ open expr open tactic open declaration /- Question 1: A `safe` tactic -/ /- We develop a tactic that applies all safe introduction and elimination rules for the connectives and quantifiers exhaustively. A rule is said to be _safe_ if it always gives rise to provable subgoals. In addition, we will require that safe rules do not introduce metavariables (which can easily be instantiated accidentally with the wrong terms.) We proceed in three steps. -/ /- 1.1. Develop a `safe_intros` tactic that applies the introduction rules for `true', `¬`, `∧`, `↔`, and `→`/`∀`. (Hint: You can use `tactic.intro` or `tactic.intro1` for some of these.) -/ meta def safe_intros : tactic unit := do tactic.intros, repeat (applyc `and.intro), tactic.intro `a2, repeat (applyc `iff.intro) example {a b c d e f : Prop} {p : ℕ → Prop} : a → ¬ b ∧ (c ↔ d) := begin safe_intros, /- The proof state should be roughly as follows: a b c d e f : Prop, p : ℕ → Prop, a_1 : a, a_2 : b ⊢ false a b c d e f : Prop, p : ℕ → Prop, a_1 : a, a_2 : c ⊢ d a b c d e f : Prop, p : ℕ → Prop, a_1 : a, a_2 : d ⊢ c -/ repeat { sorry } end /- 1.2. Develop a `safe_destructs` tactic that eliminates `false`, `∧`, `∨`, `↔`, and `∃`. -/ meta def safe_destructs : tactic unit := (do hs ← local_context, h ← hs.mfirst (λh, do `(false ) ← infer_type h, pure h), cases h, safe_destructs, skip) <|> (do hs ← local_context, h ← hs.mfirst (λh, do `(_ ∧ _) ← infer_type h, pure h), cases h, safe_destructs, skip) <|> (do hs ← local_context, h ← hs.mfirst (λh, do `(_ ∨ _) ← infer_type h, pure h), cases h, safe_destructs, skip) <|> repeat(do hs ← local_context, h ← hs.mfirst (λh, do `(_ ↔ _) ← infer_type h, pure h), cases h, safe_destructs, skip) <|> skip example {a b c d e f : Prop} {p : ℕ → Prop} (hneg: ¬ a) (hand : a ∧ b ∧ c) (hor : c ∨ d) (himp : b → e) (hiff : e ↔ f) (hex : ∃x, p x) : false := begin safe_destructs, /- The proof state should be roughly as follows: 2 goals a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, hand_left : a, hor : c, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, hand_left : a, hor : d, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false -/ repeat { sorry } end /- 1.3. Implement a `safe` tactic that first performs introduction, then elimination, and finally proves all the subgoals that can be discharged directly by `assumption`. Hint: The `try` tactic combinator might come in handy. -/ meta def safe : tactic unit := do applyc (`safe_intros), applyc (`safe_destructs), assumption example {a b c d e f : Prop} {p : ℕ → Prop} (hneg: ¬ a) (hand : a ∧ b ∧ c) (hor : c ∨ d) (himp : b → e) (hiff : e ↔ f) (hex : ∃x, p x) : a → ¬ b ∧ (c ↔ d) := begin safe, /- The proof state should be roughly as follows: 3 goals a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, a_1 : a, a_2 : b, hand_left : a, hor : c, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, a_1 : a, a_2 : b, hand_left : a, hor : d, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ false a b c d e f : Prop, p : ℕ → Prop, hneg : ¬a, himp : b → e, a_1 : a, a_2 : c, hand_left : a, hor : c, hiff_mp : e → f, hiff_mpr : f → e, hex_w : ℕ, hex_h : p hex_w, hand_right_left : b, hand_right_right : c ⊢ d -/ repeat { sorry } end /- Question 2: A `solve_direct` advisor -/ /- It often happens that a user states a new lemma, proves it, and later realizes that the lemma already exists in the library. To help prevent this, we want to implement a `solve_direct` tactic, which goes through all lemmas in the database and checks whether one of them can be used to fully solve the statement. We implement it in steps. -/ /- 2.1. Develop a function that returns `tt` if a `declaration` is a theorem (`declaration.thm`) or an axiom (`declaration.ax`) and `ff` otherwise. -/ meta def is_theorem : declaration → bool | (declaration.thm s us ty body) := tt | (declaration.ax n us ty) := tt | otherwise := ff /- 2.2. Develop a function that returns the list of all theorem names (theorem in the sense of `is_theorem`). Here `get_env` and `environment.fold` are very helpful. See also Question 3 of the exercise. -/ meta def get_all_theorems : tactic (list name) := do env ← get_env, opts ← get_options, environment.fold env [] $ λdecl lst, if term_contains_all ns decl.type then decl.to_name :: lst else lst ) /- 2.3. Develop a tactic that (fully) solves the goal using a theorem `n`. Hints: * `mk_const n` can be used to produce an `expr` (representing the proof) from a name `n` (the theorem name). * `apply` applies an `expr` to the current goal. For speed reasons one might want to add the c onfiguration `apply c { md := transparency.reducible, unify := ff }`, where `c : expr` is the current theorem, and the parameters in `{ ... }` tell `apply` to apply less computational unfolding. * `all_goals` in combination with `assumption` can be used to ensure that the hypothesis from the local context are used to fill in all remaining subgoals. * `done` can be used to check that no subgoal is left. -/ meta def solve (n : name) : tactic unit := sorry /- 2.4. Implement `solve_direct`. Now `solve_direct` should go through `get_all_theorems` and succeed with the first theorem solving the current goal. You can use `list.mfirst` to apply a tactic to each element of a list until one application succeeds. Use `trace` to output the successful theorem to the user. -/ meta def solve_direct : tactic unit := sorry /- 2.5. Develop a version of `solve_direct` that also looks for equalities stated in symmetric form (e.g., if the goal is `l = r` but the theorem is `r = l`). -/ #check eq.symm meta def solve_direct_symm : tactic unit := sorry example {n : ℕ} : n + 0 = n := by solve_direct_symm example {n : ℕ} : n = n + 0 := by solve_direct_symm /- Question 3 **optional**: An `auto` tactic -/ /- 3.1. Develop an Isabelle-style `auto` tactic. This tactic would apply all safe introduction and elimination rules. In addition, it would try unsafe rules (such as `or.intro_left` and `false.elim`) but backtrack at some point (or try several possibilities in parallel). Iterative deepening may be a valid approach, or best-first search, or breadth-first search. The tactic should also attempt to apply assumptions whose conclusion matches the goal, but backtrack if necessary. See also "Automatic Proof and Disproof in Isabelle/HOL" (https://www.cs.vu.nl/~jbe248/frocos2011-dis-proof.pdf) by Blanchette, Bulwahn, and Nipkow, and the references they give. -/ /- 3.2. Test your tactic on some benchmarks. You can try your tactic on logical puzzles of the kinds we proved in exercise 1.3 and howework 1.3. Please include these below. -/
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.hom.equiv.type_tags import algebra.module.equiv import data.finsupp.defs import group_theory.free_abelian_group import group_theory.is_free_group import linear_algebra.dimension /-! # Isomorphism between `free_abelian_group X` and `X →₀ ℤ` In this file we construct the canonical isomorphism between `free_abelian_group X` and `X →₀ ℤ`. We use this to transport the notion of `support` from `finsupp` to `free_abelian_group`. ## Main declarations - `free_abelian_group.equiv_finsupp`: group isomorphism between `free_abelian_group X` and `X →₀ ℤ` - `free_abelian_group.coeff`: the multiplicity of `x : X` in `a : free_abelian_group X` - `free_abelian_group.support`: the finset of `x : X` that occur in `a : free_abelian_group X` -/ noncomputable theory open_locale big_operators variables {X : Type*} /-- The group homomorphism `free_abelian_group X →+ (X →₀ ℤ)`. -/ def free_abelian_group.to_finsupp : free_abelian_group X →+ (X →₀ ℤ) := free_abelian_group.lift $ λ x, finsupp.single x (1 : ℤ) /-- The group homomorphism `(X →₀ ℤ) →+ free_abelian_group X`. -/ def finsupp.to_free_abelian_group : (X →₀ ℤ) →+ free_abelian_group X := finsupp.lift_add_hom $ λ x, (smul_add_hom ℤ (free_abelian_group X)).flip (free_abelian_group.of x) open finsupp free_abelian_group @[simp] lemma finsupp.to_free_abelian_group_comp_single_add_hom (x : X) : finsupp.to_free_abelian_group.comp (finsupp.single_add_hom x) = (smul_add_hom ℤ (free_abelian_group X)).flip (of x) := begin ext, simp only [add_monoid_hom.coe_comp, finsupp.single_add_hom_apply, function.comp_app, one_smul, to_free_abelian_group, finsupp.lift_add_hom_apply_single] end @[simp] lemma free_abelian_group.to_finsupp_comp_to_free_abelian_group : to_finsupp.comp to_free_abelian_group = add_monoid_hom.id (X →₀ ℤ) := begin ext x y, simp only [add_monoid_hom.id_comp], rw [add_monoid_hom.comp_assoc, finsupp.to_free_abelian_group_comp_single_add_hom], simp only [to_finsupp, add_monoid_hom.coe_comp, finsupp.single_add_hom_apply, function.comp_app, one_smul, lift.of, add_monoid_hom.flip_apply, smul_add_hom_apply, add_monoid_hom.id_apply], end @[simp] lemma finsupp.to_free_abelian_group_comp_to_finsupp : to_free_abelian_group.comp to_finsupp = add_monoid_hom.id (free_abelian_group X) := begin ext, rw [to_free_abelian_group, to_finsupp, add_monoid_hom.comp_apply, lift.of, lift_add_hom_apply_single, add_monoid_hom.flip_apply, smul_add_hom_apply, one_smul, add_monoid_hom.id_apply], end @[simp] lemma finsupp.to_free_abelian_group_to_finsupp {X} (x : free_abelian_group X) : x.to_finsupp.to_free_abelian_group = x := by rw [← add_monoid_hom.comp_apply, finsupp.to_free_abelian_group_comp_to_finsupp, add_monoid_hom.id_apply] namespace free_abelian_group open finsupp variable {X} @[simp] @[simp] lemma to_finsupp_to_free_abelian_group (f : X →₀ ℤ) : f.to_free_abelian_group.to_finsupp = f := by rw [← add_monoid_hom.comp_apply, to_finsupp_comp_to_free_abelian_group, add_monoid_hom.id_apply] variable (X) /-- The additive equivalence between `free_abelian_group X` and `(X →₀ ℤ)`. -/ @[simps] def equiv_finsupp : free_abelian_group X ≃+ (X →₀ ℤ) := { to_fun := to_finsupp, inv_fun := to_free_abelian_group, left_inv := to_free_abelian_group_to_finsupp, right_inv := to_finsupp_to_free_abelian_group, map_add' := to_finsupp.map_add } /-- `A` is a basis of the ℤ-module `free_abelian_group A`. -/ noncomputable def basis (α : Type*) : basis α ℤ (free_abelian_group α) := ⟨(free_abelian_group.equiv_finsupp α).to_int_linear_equiv ⟩ /-- Isomorphic free ablian groups (as modules) have equivalent bases. -/ def equiv.of_free_abelian_group_linear_equiv {α β : Type*} (e : free_abelian_group α ≃ₗ[ℤ] free_abelian_group β) : α ≃ β := let t : _root_.basis α ℤ (free_abelian_group β) := (free_abelian_group.basis α).map e in t.index_equiv $ free_abelian_group.basis _ /-- Isomorphic free abelian groups (as additive groups) have equivalent bases. -/ def equiv.of_free_abelian_group_equiv {α β : Type*} (e : free_abelian_group α ≃+ free_abelian_group β) : α ≃ β := equiv.of_free_abelian_group_linear_equiv e.to_int_linear_equiv /-- Isomorphic free groups have equivalent bases. -/ def equiv.of_free_group_equiv {α β : Type*} (e : free_group α ≃* free_group β) : α ≃ β := equiv.of_free_abelian_group_equiv e.abelianization_congr.to_additive open is_free_group /-- Isomorphic free groups have equivalent bases (`is_free_group` variant`). -/ def equiv.of_is_free_group_equiv {G H : Type*} [group G] [group H] [is_free_group G] [is_free_group H] (e : G ≃* H) : generators G ≃ generators H := equiv.of_free_group_equiv $ mul_equiv.trans ((to_free_group G).symm) $ mul_equiv.trans e $ to_free_group H variable {X} /-- `coeff x` is the additive group homomorphism `free_abelian_group X →+ ℤ` that sends `a` to the multiplicity of `x : X` in `a`. -/ def coeff (x : X) : free_abelian_group X →+ ℤ := (finsupp.apply_add_hom x).comp to_finsupp /-- `support a` for `a : free_abelian_group X` is the finite set of `x : X` that occur in the formal sum `a`. -/ def support (a : free_abelian_group X) : finset X := a.to_finsupp.support lemma mem_support_iff (x : X) (a : free_abelian_group X) : x ∈ a.support ↔ coeff x a ≠ 0 := by { rw [support, finsupp.mem_support_iff], exact iff.rfl } lemma not_mem_support_iff (x : X) (a : free_abelian_group X) : x ∉ a.support ↔ coeff x a = 0 := by { rw [support, finsupp.not_mem_support_iff], exact iff.rfl } @[simp] lemma support_zero : support (0 : free_abelian_group X) = ∅ := by simp only [support, finsupp.support_zero, add_monoid_hom.map_zero] @[simp] lemma support_of (x : X) : support (of x) = {x} := by simp only [support, to_finsupp_of, finsupp.support_single_ne_zero _ one_ne_zero] @[simp] lemma support_neg (a : free_abelian_group X) : support (-a) = support a := by simp only [support, add_monoid_hom.map_neg, finsupp.support_neg] @[simp] lemma support_zsmul (k : ℤ) (h : k ≠ 0) (a : free_abelian_group X) : support (k • a) = support a := begin ext x, simp only [mem_support_iff, add_monoid_hom.map_zsmul], simp only [h, zsmul_int_int, false_or, ne.def, mul_eq_zero] end @[simp] lemma support_nsmul (k : ℕ) (h : k ≠ 0) (a : free_abelian_group X) : support (k • a) = support a := by { apply support_zsmul k _ a, exact_mod_cast h } open_locale classical lemma support_add (a b : free_abelian_group X) : (support (a + b)) ⊆ a.support ∪ b.support := begin simp only [support, add_monoid_hom.map_add], apply finsupp.support_add end end free_abelian_group
#include <boost/foreach.hpp> #include "clip_grid.hpp" vector<Vector2D> clip_grid(const Shape2D& shape, const vector<Vector2D>& original) { vector<Vector2D> res; BOOST_FOREACH(Vector2D point, original) { if(shape(point)) res.push_back(point); } return res; }
module SimIndex export Index, push!, compile!, k_nearest_neighbors, test_error_ratio using ProgressMeter using Base.Collections # For PriorityQueue. using Iterators # For drop. import Distances import Base.push! # We overload push! on SimIndex, need Base.push! as well. type Index{KeyType, ValueType} k::Int # Number of neighbors a::Int # Size of actual neighborset (> k for convergence) distance::Function items::Dict{KeyType, ValueType} index::Dict{KeyType, PriorityQueue{KeyType, Float64}} compiled_index::Dict{KeyType, Array{Pair{KeyType, Float64}, 1}} dirty::Bool # Have elements been pushed to the index since a successful compile? end function Index(items; k=10, d=Distances.euclidean) if !(typeof(items) <: Dict) items = [x => x for x in items] end KeyType = eltype(keys(items)) ValueType = eltype(values(items)) index = Dict{KeyType, PriorityQueue{KeyType, Float64}}() compiled_index = Dict{KeyType, Array{Pair{KeyType, Float64}, 1}}() si = Index{KeyType, ValueType}(k, 2 * k, d, items, index, compiled_index, true) compile!(si) end function push!(s::Index, value) s.items[value] = value s.dirty = true end function push!(s::Index, key, value) s.items[key] = value s.dirty = true end function compile!(s::Index, delta::Float64=0.05) KeyType = eltype(keys(s.items)) recompile = (length(s.compiled_index) != 0) vs = [k for k in keys(s.items)] nvs = length(vs) # Initialize the neighbor list. If we've never compiled an index before, # we'll sample s.a neighbors at random for each vertex's neighbor list. If # this is a recompile of an existing index, we'll keep s.k of the best # neighbors for each vertex and sample s.a - s.k neighbors. if s.a > nvs - 1 error("k too large: can't sample $(s.a) neighbors from a set of size $(nvs - 1)") end p = Progress(nvs, 1, "Sampling vertices for initial neighbor lists...") for (v, val) in s.items if recompile && haskey(s.compiled_index, v) q = [x => d for (x,d) in s.compiled_index[v][1:s.k]] s.index[v] = PriorityQueue(q, Base.Sort.Reverse) for x in sample(vs, s.a - s.k, union(Set(keys(q)), Set([v]))) enqueue!(s.index[v], x, s.distance(val, s.items[x])) end else sampled = sample(vs, s.a, Set([v])) s.index[v] = PriorityQueue( [x => s.distance(val, s.items[x])::Float64 for x in sampled], Base.Sort.Reverse) end next!(p) end empty!(s.compiled_index) res = 1.01 # Decrease res to have more granular progress displayed. steps = round(Int, ceil(log(res, 2/delta))) # Number of steps in progress. thres = 2.0 # Next milestone for displaying progress. ratio = 2.0 # Current progress (c / nvs) p = Progress(steps, 1, "Compiling index...") while true c = 0 for j=1:nvs u = vs[rand(1:nvs)] w = rand_key(s.index[rand_key(s.index[u])]) if u == w continue end d = s.distance(s.items[u], s.items[w]) for (x,y) in [(u,w), (w,u)] _, maxd = peek(s.index[x]) if maxd > d c += update_priority_queue(s, x, y, d) end end end if c == 0 || ratio < delta break end if c / nvs < ratio ratio = c / nvs end while ratio < thres / res next!(p) thres = thres / res end end finish!(p) generate_compiled_index!(s) end function rand_key(d) first(take(drop(keys(d), rand(1:length(d)) - 1), 1)) end # Update SimIndex s to add y to x's nearest neighbors if d is less than one of # x's existing nearest neighbors' distances. Return 1 if y was added to x's # nearest neighbors, 0 otherwise. function update_priority_queue(s, x, y, d) try enqueue!(s.index[x], y, d) catch # y is already in s.index[x] return 0 end dequeue!(s.index[x]) return 1 end # Sample k elements uniformly from the stream xs while avoiding items in the avoid set. function sample(xs, k, avoid) s = Set{eltype(xs)}() nx = length(xs) while length(s) < k x = xs[rand(1:nx)] if !in(x, avoid) push!(s, x) end end return [x for x in s] end function generate_compiled_index!(s::Index) KeyType = eltype(keys(s.index)) for (key, vals) in s.index xs = Pair{KeyType, Float64}[] while true try push!(xs, peek(vals)) dequeue!(vals) catch break end end reverse!(xs) s.compiled_index[key] = xs end empty!(s.index) s.dirty = false s end function k_nearest_neighbors(s::Index, key; k=s.k) if s.dirty error("Index needs to be compiled.") end vals = get(s.compiled_index, key, Union{}) if vals == Union{} return Union{} end return vals[1:min(length(vals), k)] end function test_error_ratio(s::Index, n=50) ks = [k for k in keys(s.items)] KeyType = eltype(ks) ratios = Float64[] for i=1:n k = ks[rand(1:end)] v = s.items[k] q = PriorityQueue(Dict{KeyType, Float64}(), Base.Sort.Reverse) for (k2, v2) in s.items if k2 == k continue end d = s.distance(v, v2) enqueue!(q, k2, d) if length(q) > s.k dequeue!(q) end end # Accumulate key, distance pairs xs = Pair{KeyType, Float64}[] while true try push!(xs, peek(q)) dequeue!(q) catch break end end reverse!(xs) push!(ratios, error_ratio(xs, k_nearest_neighbors(s, k))) end mean(ratios) end function error_ratio(actual, approx) if length(actual) != length(approx) error("Arrays passed to error_ratio have different lengths") end xs = Float64[] for i=1:length(actual) push!(xs, (approx[i].second + eps()) / (actual[i].second + eps())) end mean(xs) end end # module
{-# OPTIONS --copatterns #-} -- Andreas, 2013-11-05 Coverage checker needs clauses to reduce type! -- {-# OPTIONS -v tc.cover:20 #-} module Issue937a where open import Common.Prelude open import Common.Equality open import Common.Product T : (b : Bool) → Set T true = Nat T false = Bool → Nat test : Σ Bool T proj₁ test = false proj₂ test true = zero proj₂ test false = suc zero -- Error: unreachable clause module _ {_ : Set} where bla : Σ Bool T proj₁ bla = false proj₂ bla true = zero proj₂ bla false = suc zero -- Error: unreachable clause -- should coverage check
{-# OPTIONS --cubical --safe #-} open import Algebra open import Relation.Binary open import Algebra.Monus module Data.MonoidalHeap.Monad {s} (monus : TMAPOM s) where open TMAPOM monus open import Prelude open import Data.List using (List; _∷_; []; foldr; _++_) import Data.Nat as ℕ import Data.Nat.Properties as ℕ 𝒮 : Type s 𝒮 = 𝑆 → 𝑆 ⟦_⇑⟧ : 𝑆 → 𝒮 ⟦_⇑⟧ = _∙_ ⟦_⇓⟧ : 𝒮 → 𝑆 ⟦ x ⇓⟧ = x ε infixl 10 _⊙_ _⊙_ : (𝑆 → A) → 𝑆 → 𝑆 → A f ⊙ x = λ y → f (x ∙ y) mutual data Node (V : 𝑆 → Type a) : Type (a ℓ⊔ s) where leaf : V ε → Node V _⋊_ : (w : 𝑆) → Heap (V ⊙ w) → Node V Heap : (𝑆 → Type a) → Type (a ℓ⊔ s) Heap V = List (Node V) private variable v : Level V : 𝑆 → Type v Root : (𝑆 → Type v) → Type _ Root V = ∃ w × Heap (V ⊙ w) partition : Heap V → List (V ε) × List (Root V) partition = foldr f ([] , []) where f : Node V → List (V ε) × List (∃ w × Heap (V ⊙ w)) → List (V ε) × List (∃ w × Heap (V ⊙ w)) f (leaf x) (ls , hs) = (x ∷ ls) , hs f (w ⋊ x) (ls , hs) = ls , ((w , x) ∷ hs) module _ {V : 𝑆 → Type v} where ⊙-assoc : ∀ x y k → x ≡ y ∙ k → V ⊙ x ≡ V ⊙ y ⊙ k ⊙-assoc x y k x≡y∙k i z = V ((cong (_∙ z) x≡y∙k ; assoc y k z) i) ⊙ε : V ⊙ ε ≡ V ⊙ε i x = V (ε∙ x i) ⊙-rassoc : ∀ x y → V ⊙ (x ∙ y) ≡ V ⊙ x ⊙ y ⊙-rassoc x y i z = V (assoc x y z i) merge : Root V → Root V → Root V merge (x , xs) (y , ys) with x ≤|≥ y ... | inl (k , y≡x∙k) = x , (k ⋊ subst Heap (⊙-assoc y x k y≡x∙k) ys) ∷ xs ... | inr (k , x≡y∙k) = y , (k ⋊ subst Heap (⊙-assoc x y k x≡y∙k) xs) ∷ ys merges⁺ : Root V → List (Root V) → Root V merges⁺ x [] = x merges⁺ x₁ (x₂ ∷ []) = merge x₁ x₂ merges⁺ x₁ (x₂ ∷ x₃ ∷ xs) = merge (merge x₁ x₂) (merges⁺ x₃ xs) merges : List (Root V) → Maybe (Root V) merges [] = nothing merges (x ∷ xs) = just (merges⁺ x xs) popMin : Heap V → List (V ε) × Maybe (Root V) popMin = map₂ merges ∘ partition return : V ε → Heap V return x = leaf x ∷ [] weight : ∃ x × V x → Heap V weight (w , x) = (w ⋊ (leaf (subst V (sym (∙ε w)) x) ∷ [])) ∷ [] _>>=_ : Heap V → (∀ {x} → V x → Heap (V ⊙ x)) → Heap V _>>=_ [] k = [] _>>=_ (leaf x ∷ xs) k = subst Heap ⊙ε (k x) ++ (xs >>= k) _>>=_ {V = V} ((w ⋊ x) ∷ xs) k = (w ⋊ (x >>= (subst Heap (⊙-rassoc {V = V} w _) ∘ k))) ∷ (xs >>= k)
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def show_heatmap(pvalues, stock_list, title): fig, ax = plt.subplots(figsize=(12,8)) plt.rcParams["font.family"] = "IPAexGothic" #全体のフォントを設定 plt.suptitle(title) sns.heatmap(pvalues, xticklabels=stock_list, yticklabels=stock_list, annot=True, cmap='Blues', mask=(1<=pvalues)) plt.show() if (__name__ == "__main__"): pass
Battlefield: Bad Company 2 $9.99 Fight from the ground or blow away terrorists from the air in this FPS game formerly only found on desktop computers and consoles. battlefield bad company 2 free download free download - Battlefield Bad Company 2 Stats, Battlefield 2 v1.12 patch, Battlefield 2 Stats Viewer, and many more programs. Battlefield: Bad Company 2 Update Squad Deathmatch and a pair of new maps are the focus of our latest hands-on with DICE's upcoming shooter.
lemma closure_linear_image_subset: fixes f :: "'m::euclidean_space \<Rightarrow> 'n::real_normed_vector" assumes "linear f" shows "f ` (closure S) \<subseteq> closure (f ` S)"
function R = Rroll(phi) c = cos(phi); s = sin(phi); R = [1 0 0; 0 c -s; 0 s c];
[STATEMENT] lemma M_invertible: "invertible M" [PROOF STATE] proof (prove) goal (1 subgoal): 1. invertible M [PROOF STEP] unfolding invertible_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>A'. M ** A' = mat 1 \<and> A' ** M = mat 1 [PROOF STEP] using M_self_inverse [PROOF STATE] proof (prove) using this: M ** M = mat 1 goal (1 subgoal): 1. \<exists>A'. M ** A' = mat 1 \<and> A' ** M = mat 1 [PROOF STEP] by auto
module Main main : IO () main = repl "\n> " reverse
module STLC import Data.Fin import Data.Vect data Ty = TyInt | TyBool | TyFun Ty Ty interpTy : Ty -> Type interpTy TyInt = Int interpTy TyBool = Bool interpTy (TyFun A T) = interpTy A -> interpTy T using (G:Vect n Ty) data HasType : (i : Fin n) -> Vect n Ty -> Ty -> Type where Stop : HasType FZ (t :: G) t Pop : HasType k G t -> HasType (FS k) (u :: G) t data Expr : Vect n Ty -> Ty -> Type where Var : HasType i G t -> Expr G t Val : (x : Int) -> Expr G TyInt Lam : Expr (a :: G) t -> Expr G (TyFun a t) App : Expr G (TyFun a t) -> Expr G a -> Expr G t Op : (interpTy a -> interpTy b -> interpTy c) -> Expr G a -> Expr G b -> Expr G c If : Expr G TyBool -> Lazy (Expr G a) -> Lazy (Expr G a) -> Expr G a data Env : Vect n Ty -> Type where Nil : Env Nil (::) : interpTy a -> Env G -> Env (a :: G) lookup : HasType i G t -> Env G -> interpTy t lookup Stop (x :: xs) = x lookup (Pop k) (x :: xs) = lookup k xs interp : Env G -> Expr G t -> interpTy t interp env (Var i) = lookup i env interp env (Val x) = x interp env (Lam sc) = \x => interp (x :: env) sc interp env (App f s) = interp env f (interp env s) interp env (Op op x y) = op (interp env x) (interp env y) interp env (If x t e) = if interp env x then interp env t else interp env e -- Unit Tests sub1 : Expr G (TyFun TyInt TyInt) sub1 = Lam (Op (-) (Var Stop) (Val 1)) sub2 : Expr G (TyFun TyInt TyInt) sub2 = Lam (App sub1 (App sub1 (Var Stop))) add : Expr G (TyFun TyInt (TyFun TyInt TyInt)) add = Lam (Lam (Op (+) (Var Stop) (Var (Pop Stop)))) fact : Expr G (TyFun TyInt TyInt) fact = Lam (If (Op (==) (Var Stop) (Val 0)) (Val 1) (Op (*) (App fact (Op (-) (Var Stop) (Val 1))) (Var Stop))) fib : Expr G (TyFun TyInt TyInt) fib = Lam (If (Op (==) (Var Stop) (Val 0)) (Val 1) (If (Op (==) (Var Stop) (Val 1)) (Val 1) (Op (*) (App fib (App sub1 (Var Stop))) (App fib (App sub2 (Var Stop))))))
## TRAITS FOR MEASURES is_measure(::Any) = false const MEASURE_TRAITS = [:name, :target_scitype, :supports_weights, :prediction_type, :orientation, :reports_each_observation, :is_feature_dependent] # already defined in model_traits.jl: # name - fallback for non-MLJType is string(M) where M is arg # target_scitype - fallback value = Unknown # supports_weights - fallback value = false # prediction_type - fallback value = :unknown (also: :deterministic, # :probabilistic, :interval) # specfic to measures: orientation(::Type) = :loss # other options are :score, :other reports_each_observation(::Type) = false is_feature_dependent(::Type) = false # extend to instances: orientation(m) = orientation(typeof(m)) reports_each_observation(m) = reports_each_observation(typeof(m)) is_feature_dependent(m) = is_feature_dependent(typeof(m)) # specific to probabilistic measures: distribution_type(::Type) = missing ## DISPATCH FOR EVALUATION # yhat - predictions (point or probabilisitic) # X - features # y - target observations # w - per-observation weights value(measure, yhat, X, y, w) = value(measure, yhat, X, y, w, Val(is_feature_dependent(measure)), Val(supports_weights(measure))) ## DEFAULT EVALUATION INTERFACE # is feature independent, weights not supported: value(measure, yhat, X, y, w, ::Val{false}, ::Val{false}) = measure(yhat, y) # is feature dependent:, weights not supported: value(measure, yhat, X, y, w, ::Val{true}, ::Val{false}) = measure(yhat, X, y) # is feature independent, weights supported: value(measure, yhat, X, y, w, ::Val{false}, ::Val{true}) = measure(yhat, y, w) value(measure, yhat, X, y, ::Nothing, ::Val{false}, ::Val{true}) = measure(yhat, y) # is feature dependent, weights supported: value(measure, yhat, X, y, w, ::Val{true}, ::Val{true}) = measure(yhat, X, y, w) value(measure, yhat, X, y, ::Nothing, ::Val{true}, ::Val{true}) = measure(yhat, X, y) ## HELPERS """ check_dimension(ŷ, y) Check that two vectors have compatible dimensions """ function check_dimensions(ŷ::AbstractVector, y::AbstractVector) length(y) == length(ŷ) || throw(DimensionMismatch("Differing numbers of observations and "* "predictions. ")) return nothing end function check_pools(ŷ, y) levels(y) == levels(ŷ[1]) || error("Conflicting categorical pools found "* "in observations and predictions. ") return nothing end ## FOR BUILT-IN MEASURES abstract type Measure <: MLJType end is_measure(::Measure) = true Base.show(stream::IO, ::MIME"text/plain", m::Measure) = print(stream, "$(name(m)) (callable Measure)") Base.show(stream::IO, m::Measure) = print(stream, name(m)) MLJBase.info(measure, ::Val{:measure}) = (name=name(measure), target_scitype=target_scitype(measure), prediction_type=prediction_type(measure), orientation=orientation(measure), reports_each_observation=reports_each_observation(measure), is_feature_dependent=is_feature_dependent(measure), supports_weights=supports_weights(measure)) ## REGRESSOR METRICS (FOR DETERMINISTIC PREDICTIONS) mutable struct MAV<: Measure end """ mav(ŷ, y) mav(ŷ, y, w) Mean absolute error (also known as MAE). ``\\text{MAV} = n^{-1}∑ᵢ|yᵢ-ŷᵢ|`` or ``\\text{MAV} = ∑ᵢwᵢ|yᵢ-ŷᵢ|/∑ᵢwᵢ`` For more information, run `info(mav)`. """ mav = MAV() name(::Type{<:MAV}) = "mav" target_scitype(::Type{<:MAV}) = Union{AbstractVector{Continuous},AbstractVector{Count}} prediction_type(::Type{<:MAV}) = :deterministic orientation(::Type{<:MAV}) = :loss reports_each_observation(::Type{<:MAV}) = false is_feature_dependent(::Type{<:MAV}) = false supports_weights(::Type{<:MAV}) = true function (::MAV)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) check_dimensions(ŷ, y) ret = 0.0 for i in eachindex(y) dev = y[i] - ŷ[i] ret += abs(dev) end return ret / length(y) end function (::MAV)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}, w::AbstractVector{<:Real}) check_dimensions(ŷ, y) check_dimensions(y, w) ret = 0.0 for i in eachindex(y) dev = w[i]*(y[i] - ŷ[i]) ret += abs(dev) end return ret / sum(w) end # synonym """ mae(ŷ, y) See also [`mav`](@ref). """ const mae = mav struct RMS <: Measure end """ rms(ŷ, y) rms(ŷ, y, w) Root mean squared error: ``\\text{RMS} = \\sqrt{n^{-1}∑ᵢ|yᵢ-ŷᵢ|^2}`` or ``\\text{RMS} = \\sqrt{\\frac{∑ᵢwᵢ|yᵢ-ŷᵢ|^2}{∑ᵢwᵢ}}`` For more information, run `info(rms)`. """ rms = RMS() name(::Type{<:RMS}) = "rms" target_scitype(::Type{<:RMS}) = Union{AbstractVector{Continuous},AbstractVector{Count}} prediction_type(::Type{<:RMS}) = :deterministic orientation(::Type{<:RMS}) = :loss reports_each_observation(::Type{<:RMS}) = false is_feature_dependent(::Type{<:RMS}) = false supports_weights(::Type{<:RMS}) = true function (::RMS)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) check_dimensions(ŷ, y) ret = 0.0 for i in eachindex(y) dev = y[i] - ŷ[i] ret += dev * dev end return sqrt(ret / length(y)) end function (::RMS)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}, w::AbstractVector{<:Real}) check_dimensions(ŷ, y) ret = 0.0 for i in eachindex(y) dev = y[i] - ŷ[i] ret += w[i]*dev*dev end return sqrt(ret / sum(w)) end struct L2 <: Measure end """ l2(ŷ, y) l2(ŷ, y, w) L2 per-observation loss. For more information, run `info(l2)`. """ l2 = L2() name(::Type{<:L2}) = "l2" target_scitype(::Type{<:L2}) = Union{AbstractVector{Continuous},AbstractVector{Count}} prediction_type(::Type{<:L2}) = :deterministic orientation(::Type{<:L2}) = :loss reports_each_observation(::Type{<:L2}) = true is_feature_dependent(::Type{<:L2}) = false supports_weights(::Type{<:L2}) = true function (::L2)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) (check_dimensions(ŷ, y); (y - ŷ).^2) end function (::L2)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}, w::AbstractVector{<:Real}) check_dimensions(ŷ, y) check_dimensions(w, y) return (y - ŷ).^2 .* w ./ (sum(w)/length(y)) end struct L1 <: Measure end """ l1(ŷ, y) l1(ŷ, y, w) L1 per-observation loss. For more information, run `info(l1)`. """ l1 = L1() name(::Type{<:L1}) = "l1" target_scitype(::Type{<:L1}) = Union{AbstractVector{Continuous},AbstractVector{Count}} prediction_type(::Type{<:L1}) = :deterministic orientation(::Type{<:L1}) = :loss reports_each_observation(::Type{<:L1}) = true is_feature_dependent(::Type{<:L1}) = false supports_weights(::Type{<:L1}) = true function (::L1)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) (check_dimensions(ŷ, y); abs.(y - ŷ)) end function (::L1)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}, w::AbstractVector{<:Real}) check_dimensions(ŷ, y) check_dimensions(w, y) return abs.(y - ŷ) .* w ./ (sum(w)/length(y)) end struct RMSL <: Measure end """ rmsl(ŷ, y) Root mean squared logarithmic error: ``\\text{RMSL} = n^{-1}∑ᵢ\\log\\left({yᵢ \\over ŷᵢ}\\right)`` For more information, run `info(rmsl)`. See also [`rmslp1`](@ref). """ rmsl = RMSL() name(::Type{<:RMSL}) = "rmsl" target_scitype(::Type{<:RMSL}) = Union{AbstractVector{Continuous},AbstractVector{Count}} prediction_type(::Type{<:RMSL}) = :deterministic orientation(::Type{<:RMSL}) = :loss reports_each_observation(::Type{<:RMSL}) = false is_feature_dependent(::Type{<:RMSL}) = false supports_weights(::Type{<:RMSL}) = false function (::RMSL)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) check_dimensions(ŷ, y) ret = 0.0 for i in eachindex(y) dev = log(y[i]) - log(ŷ[i]) ret += dev * dev end return sqrt(ret / length(y)) end struct RMSLP1 <: Measure end """ rmslp1(ŷ, y) Root mean squared logarithmic error with an offset of 1: ``\\text{RMSLP1} = n^{-1}∑ᵢ\\log\\left({yᵢ + 1 \\over ŷᵢ + 1}\\right)`` For more information, run `info(rmslp1)`. See also [`rmsl`](@ref). """ rmslp1 = RMSLP1() name(::Type{<:RMSLP1}) = "rmslp1" target_scitype(::Type{<:RMSLP1}) = Union{AbstractVector{Continuous},AbstractVector{Count}} prediction_type(::Type{<:RMSLP1}) = :deterministic orientation(::Type{<:RMSLP1}) = :loss reports_each_observation(::Type{<:RMSLP1}) = false is_feature_dependent(::Type{<:RMSLP1}) = false supports_weights(::Type{<:RMSLP1}) = false function (::RMSLP1)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) check_dimensions(ŷ, y) ret = 0.0 for i in eachindex(y) dev = log(y[i] + 1) - log(ŷ[i] + 1) ret += dev * dev end return sqrt(ret / length(y)) end struct RMSP <: Measure end """ rmsp(ŷ, y) Root mean squared percentage loss: ``\\text{RMSP} = m^{-1}∑ᵢ \\left({yᵢ-ŷᵢ \\over yᵢ}\\right)^2`` where the sum is over indices such that `yᵢ≂̸0` and `m` is the number of such indices. For more information, run `info(rmsp)`. """ rmsp = RMSP() name(::Type{<:RMSP}) = "rmsp" target_scitype(::Type{<:RMSP}) = Union{AbstractVector{Continuous},AbstractVector{Count}} prediction_type(::Type{<:RMSP}) = :deterministic orientation(::Type{<:RMSP}) = :loss reports_each_observation(::Type{<:RMSP}) = false is_feature_dependent(::Type{<:RMSP}) = false supports_weights(::Type{<:RMSP}) = false function (::RMSP)(ŷ::AbstractVector{<:Real}, y::AbstractVector{<:Real}) check_dimensions(ŷ, y) ret = 0.0 count = 0 for i in eachindex(y) if y[i] != 0.0 dev = (y[i] - ŷ[i])/y[i] ret += dev * dev count += 1 end end return sqrt(ret/count) end ## CLASSIFICATION METRICS (FOR DETERMINISTIC PREDICTIONS) struct MisclassificationRate <: Measure end """ misclassification_rate(ŷ, y) misclassification_rate(ŷ, y, w) Returns the rate of misclassification of the (point) predictions `ŷ`, given true observations `y`, optionally weighted by the weights `w`. All three arguments must be abstract vectors of the same length. For more information, run `info(misclassification_rate)`. """ misclassification_rate = MisclassificationRate() name(::Type{<:MisclassificationRate}) = "misclassification_rate" target_scitype(::Type{<:MisclassificationRate}) = AbstractVector{<:Finite} prediction_type(::Type{<:MisclassificationRate}) = :deterministic orientation(::Type{<:MisclassificationRate}) = :loss reports_each_observation(::Type{<:MisclassificationRate}) = false is_feature_dependent(::Type{<:MisclassificationRate}) = false supports_weights(::Type{<:MisclassificationRate}) = true (::MisclassificationRate)(ŷ::AbstractVector{<:CategoricalElement}, y::AbstractVector{<:CategoricalElement}) = mean(y .!= ŷ) (::MisclassificationRate)(ŷ::AbstractVector{<:CategoricalElement}, y::AbstractVector{<:CategoricalElement}, w::AbstractVector{<:Real}) = sum((y .!= ŷ) .*w) / sum(w) ## CLASSIFICATION METRICS (FOR PROBABILISTIC PREDICTIONS) struct CrossEntropy <: Measure end """ cross_entropy(ŷ, y::AbstractVector{<:Finite}) Given an abstract vector of `UnivariateFinite` distributions `ŷ` (ie, probabilistic predictions) and an abstract vector of true observations `y`, return the negative log-probability that each observation would occur, according to the corresponding probabilistic prediction. For more information, run `info(cross_entropy)`. """ cross_entropy = CrossEntropy() name(::Type{<:CrossEntropy}) = "cross_entropy" target_scitype(::Type{<:CrossEntropy}) = AbstractVector{<:Finite} prediction_type(::Type{<:CrossEntropy}) = :probabilistic orientation(::Type{<:CrossEntropy}) = :loss reports_each_observation(::Type{<:CrossEntropy}) = true is_feature_dependent(::Type{<:CrossEntropy}) = false supports_weights(::Type{<:CrossEntropy}) = false # for single observation: _cross_entropy(d, y) = -log(pdf(d, y)) function (::CrossEntropy)(ŷ::AbstractVector{<:UnivariateFinite}, y::AbstractVector{<:CategoricalElement}) check_dimensions(ŷ, y) check_pools(ŷ, y) return broadcast(_cross_entropy, Any[ŷ...], y) end # TODO: support many distributions/samplers D below: struct BrierScore{D} <: Measure end """ brier = BrierScore(; distribution=UnivariateFinite) brier(ŷ, y) Given an abstract vector of distributions `ŷ` and an abstract vector of true observations `y`, return the corresponding Brier (aka quadratic) scores. Currently only `distribution=UnivariateFinite` is supported, which is applicable to superivised models with `Finite` target scitype. In this case, if `p(y)` is the predicted probability for a *single* observation `y`, and `C` all possible classes, then the corresponding Brier score for that observation is given by ``2p(y) - \\left(\\sum_{η ∈ C} p(η)^2\\right) - 1`` For more information, run `info(brier_score)`. """ function BrierScore(; distribution=UnivariateFinite) distribution == UnivariateFinite || error("Only `UnivariateFinite` Brier scores currently supported. ") return BrierScore{distribution}() end name(::Type{<:BrierScore{D}}) where D = "BrierScore{$(string(D))}" target_scitype(::Type{<:BrierScore{D}}) where D = AbstractVector{<:Finite} prediction_type(::Type{<:BrierScore}) = :probabilistic orientation(::Type{<:BrierScore}) = :score reports_each_observation(::Type{<:BrierScore}) = true is_feature_dependent(::Type{<:BrierScore}) = false supports_weights(::Type{<:BrierScore}) = true # For single observations (no checks): # UnivariateFinite: function brier_score(d::UnivariateFinite, y) levels = classes(d) pvec = broadcast(pdf, d, levels) offset = 1 + sum(pvec.^2) return 2*pdf(d, y) - offset end # For multiple observations: # UnivariateFinite: function (::BrierScore{<:UnivariateFinite})( ŷ::AbstractVector{<:UnivariateFinite}, y::AbstractVector{<:CategoricalElement}) check_dimensions(ŷ, y) check_pools(ŷ, y) return broadcast(brier_score, Any[ŷ...], y) end function (score::BrierScore{<:UnivariateFinite})( ŷ, y, w::AbstractVector{<:Real}) check_dimensions(y, w) return w .* score(ŷ, y) ./ (sum(w)/length(y)) end ## DEFAULT MEASURES default_measure(model::M) where M<:Supervised = default_measure(model, target_scitype(M)) default_measure(model, ::Any) = nothing default_measure(model::Deterministic, ::Type{<:Union{AbstractVector{Continuous}, AbstractVector{Count}}}) = rms # default_measure(model::Probabilistic, # ::Type{<:Union{AbstractVector{Continuous}, # AbstractVector{Count}}}) = rms default_measure(model::Deterministic, ::Type{<:AbstractVector{<:Finite}}) = misclassification_rate default_measure(model::Probabilistic, ::Type{<:AbstractVector{<:Finite}}) = cross_entropy
[STATEMENT] lemma weakCongWeakEq: fixes P :: pi and Q :: pi assumes "P \<simeq>\<^sup>s Q" shows "P \<simeq> Q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P \<simeq> Q [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: P \<simeq>\<^sup>s Q goal (1 subgoal): 1. P \<simeq> Q [PROOF STEP] apply(auto simp add: substClosed_def congruenceSubst_def) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>\<sigma>. P[<\<sigma>>] \<simeq> Q[<\<sigma>>] \<Longrightarrow> P \<simeq> Q [PROOF STEP] apply(erule_tac x="[]" in allE) [PROOF STATE] proof (prove) goal (1 subgoal): 1. P[<[]>] \<simeq> Q[<[]>] \<Longrightarrow> P \<simeq> Q [PROOF STEP] by auto
(* Title: HOL/Auth/n_flash_lemma_on_inv__117.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_flash Protocol Case Study*} theory n_flash_lemma_on_inv__117 imports n_flash_base begin section{*All lemmas on causal relation between inv__117 and some rule r*} lemma n_PI_Remote_GetVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Remote_GetXVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_NakVsinv__117: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__0Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Nak__part__2Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__0Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Get__part__1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_HeadVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_PutVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_Get_Put_DirtyVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_NakVsinv__117: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_Get_PutVsinv__117: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__0Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_Nak__part__2Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__0Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_GetX__part__1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_2Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_3Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_4Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_5Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_6Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_HomeVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8Vsinv__117: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__117: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10_HomeVsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_10Vsinv__117: assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Local_GetX_PutX_11Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_NakVsinv__117: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_GetX_PutXVsinv__117: assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutVsinv__117: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_Remote_PutXVsinv__117: assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(dst=p__Inv4)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(dst~=p__Inv4)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_InvAck_1Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_InvAck_1 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') src)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_InvAck_2Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_InvAck_2 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') src)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_NI_InvAck_3Vsinv__117: assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src)" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_InvAck_3 N src" apply fastforce done from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(src=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') p__Inv4)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(src~=p__Inv4)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Field (Field (Ident ''Sta'') ''Dir'') ''InvSet'') src)) (Const true)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_PI_Local_Get_GetVsinv__117: assumes a1: "(r=n_PI_Local_Get_Get )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_GetX__part__0Vsinv__117: assumes a1: "(r=n_PI_Local_GetX_GetX__part__0 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_GetX__part__1Vsinv__117: assumes a1: "(r=n_PI_Local_GetX_GetX__part__1 )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__117: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__0 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__117: assumes a1: "(r=n_PI_Local_GetX_PutX_HeadVld__part__1 N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P1 s" proof(cut_tac a1 a2 , auto) qed then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Nak_ClearVsinv__117: assumes a1: "(r=n_NI_Nak_Clear )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))) (eqn (IVar (Field (Field (Ident ''Sta'') ''NakcMsg'') ''Cmd'')) (Const NAKC_Nakc))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutVsinv__117: assumes a1: "(r=n_NI_Local_Put )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_Put)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Local_PutXAcksDoneVsinv__117: assumes a1: "(r=n_NI_Local_PutXAcksDone )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''HomeUniMsg'') ''Cmd'')) (Const UNI_PutX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_FAckVsinv__117: assumes a1: "(r=n_NI_FAck )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))) (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_FAck))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_ShWbVsinv__117: assumes a1: "(r=n_NI_ShWb N )" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__117 p__Inv4" apply fastforce done have "?P3 s" apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_GetX))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))))" in exI, auto) done then show "invHoldForRule s f r (invariants N)" by auto qed lemma n_NI_Remote_GetX_PutX_HomeVsinv__117: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX__part__0Vsinv__117: assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_WbVsinv__117: assumes a1: "r=n_NI_Wb " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__117: assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_ReplaceVsinv__117: assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_Store_HomeVsinv__117: assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_ReplaceVsinv__117: assumes a1: "r=n_PI_Local_Replace " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_existsVsinv__117: assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Remote_PutXVsinv__117: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Put_HomeVsinv__117: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvVsinv__117: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_PutXVsinv__117: assumes a1: "r=n_PI_Local_PutX " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_Get_PutVsinv__117: assumes a1: "r=n_PI_Local_Get_Put " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_ReplaceVsinv__117: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_GetX_Nak_HomeVsinv__117: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_PI_Local_GetX_PutX__part__1Vsinv__117: assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Remote_Get_Nak_HomeVsinv__117: assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_InvAck_exists_HomeVsinv__117: assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Replace_HomeVsinv__117: assumes a1: "r=n_NI_Replace_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_NI_Nak_HomeVsinv__117: assumes a1: "r=n_NI_Nak_Home " and a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__117 p__Inv4)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
!requires lapack ! CITATION: ! P. McCullagh, P. T. Lake, M. McCullagh. Deriving Coarse-grained Charges from All-atom Systems: An Analytic Solution. J. Chem. Theory Comp., 2016. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!! Modules !!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! module inputData integer deltaStep integer nThreads endmodule inputData module atomData integer nAtoms real (kind=8), allocatable :: atomPos(:,:) real (kind=8), allocatable :: atomCharges(:) character*80 atomXyzFile character*80 atomPsfFile character*80 outFile real (kind=8), allocatable :: atomEspMat(:,:) endmodule atomData module cgData integer nCgs real (kind=8), allocatable :: cgPos(:,:) real (kind=8), allocatable :: cgCharges(:) character*80 cgXyzFile real (kind=8), allocatable :: cgEspMat(:,:) endmodule cgData module gridData integer nGrids(3) integer totalGrids real (kind=8) gridMin(3) real (kind=8) gridMax(3) real (kind=8) deltaGrid real (kind=8) cutoff2 integer gridCut integer maxCutInt real (kind=8), save :: minThresh2 = 0.01 endmodule gridData module integralData real (kind=8), allocatable :: A(:,:) real (kind=8), allocatable :: B(:,:) real (kind=8), allocatable :: C(:,:) real (kind=8), allocatable :: intCgCharges(:) real (kind=8) gridRss real (kind=8) intRss endmodule integralData !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!! Main Program !!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! program esp_grid use atomData use cgData use inputData use gridData, only : totalGrids implicit none character*80 cfgFile real (kind=8) omp_get_wtime real (kind=8) ti,tf ti = omp_get_wtime() ! read config file, number of openMP threads and stride from command line call parse_command_line(cfgFile,nThreads,deltaStep) ! read the rest of the config parameters from the config file call parse_config_file(cfgFile) ! read the trajectories and perform the fits call read_xyz_fit_esp() tf = omp_get_wtime() write(*,'("Total time elapsed:",f8.3)') tf-ti endprogram esp_grid !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!! Subroutines !!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! allocate arrays subroutine allocate_arrays() use atomData use gridData use cgData use integralData implicit none ! grid based array containing the ESP multiplied by the atomic charges allocate(atomEspMat(nCgs,nAtoms)) ! grid based array containing 1/dist between grids and CG sites allocate(cgEspMat(nCgs,nCgs)) ! zero out each array as they will be added to atomEspMat = 0.0 cgEspMat = 0.0 ! integral based matrices allocate(A(nCgs,nCgs),B(nCgs,nAtoms),C(nAtoms,nAtoms),intCgCharges(nCgs)) A = 0.0 B = 0.0 C = 0.0 endsubroutine allocate_arrays subroutine read_xyz_fit_esp() use inputData use atomData use cgData use gridData use integralData implicit none integer atom1 integer k integer nSteps integer step real (kind=8) centerVec(3) real (kind=8), allocatable :: lagrangeCgCharges(:) real (kind=8) gridCenter(3) real (kind=8) temp real (kind=8) tempLagrange integer filenum integer totalSteps integer cutoff_int real (kind=8) cutoff real (kind=8) atomMin(3) real (kind=8) atomMax(3) real (kind=8) atomAvg gridCenter = (gridMax+gridMin) / 2.0 print*, "Grid center:", gridCenter(1),gridCenter(2),gridCenter(3) ! read the atom psf file to obtain number of atoms and charges. atomPos and charge array are allocated in this routine call read_psf_file() call read_dcd_header(atomXyzFile,nAtoms,nSteps,20) call read_dcd_header(cgXyzFile,nCgs,nSteps,30) allocate(cgPos(nCgs,3)) allocate(cgCharges(nCgs)) call read_dcd_step(atomPos,nAtoms,20) call read_dcd_step(cgPos,nCgs,30) ! call read_atom_xyz() ! call read_cg_xyz() allocate(lagrangeCgCharges(nCgs)) ! allocate some grid and integral arrays call allocate_arrays() ! place molecule at origin do k=1,3 atomAvg = sum(atomPos(:,k))/ dble(nAtoms) atomPos(:,k) = atomPos(:,k) - atomAvg cgPos(:,k) = cgPos(:,k) - atomAvg atomMin(k) = minval(atomPos(:,k)) atomMax(k) = maxval(atomPos(:,k)) enddo ! update A, B and C matrices for integral method call update_A_B_C_matrices(atomPos,nAtoms,cgPos,nCgs,A,B,C) ! fit using integral approach call integral_fit_charges(A, B, C, atomCharges, intCgCharges, nAtoms, nCgs, intRss) open(77,file = "ssc_v_cutoff.dat") write(77,'(a20,a20,a20,a25,a20)') "cutoff", "Sum Grid Charges", "Grid SSD", "Sum Lagrange Charges", "Lagrange Grid SSD" do cutoff_int = 1, maxCutInt cutoff = cutoff_int*1.0 cutoff2 = cutoff*cutoff gridMin = atomMin - cutoff - deltaGrid gridMax = atomMax + cutoff + deltaGrid nGrids = int( (gridMax-gridMin) / deltaGrid ) + 1 totalGrids = nGrids(1)*nGrids(2)*nGrids(3) write(*,'("Iteration ", i5, " cutoff value:", f10.5, " nGrids", i10,i10,i10)') cutoff_int, cutoff, nGrids(1),nGrids(2),nGrids(3) atomEspMat = 0.0 cgEspMat = 0.0 ! ?? call compute_grid_esp_mats(atomPos,nAtoms,cgPos,nCgs,atomEspMat,cgEspMat) call fit_cg_charges_lagrange(atomEspMat,nAtoms,cgEspMat,nCgs,atomCharges,lagrangeCgCharges) call fit_cg_charges(atomEspMat,nAtoms,cgEspMat,nCgs,atomCharges,cgCharges) temp = 0.0 tempLagrange = 0.0 do k = 1, nCgs temp = temp + (cgCharges(k)-intCgCharges(k))**2 tempLagrange = tempLagrange + (lagrangeCgCharges(k)-intCgCharges(k))**2 enddo write(77,'(f20.10,f20.10,f20.10,f25.10,f20.10)') cutoff,sum(cgCharges), temp, sum(lagrangeCgCharges),tempLagrange enddo close(77) ! print CG charges open(35,file=outFile) write(35,'(a10,a20,a20,a20,a20,a20)') "CG Site", "Grid Charges", "Integral Charges", "Squared difference", "Lagrange Charges", "SD" write(*,'(a10,a20,a20,a20,a20,a20)') "CG Site", "Grid Charges", "Integral Charges", "Squared difference", "Lagrange Charges", "SD" temp = 0 do k=1, nCgs temp = temp + (cgCharges(k)-intCgCharges(k))**2 write(35,'(i10,f20.10,f20.10,f20.10,f20.10,f20.10)') k , cgCharges(k), intCgCharges(k), (cgCharges(k)-intCgCharges(k))**2, lagrangeCgCharges(k), (lagrangeCgCharges(k)-intCgCharges(k))**2 write(*,'(i10,f20.10,f20.10,f20.10,f20.10,f20.10)') k , cgCharges(k), intCgCharges(k), (cgCharges(k)-intCgCharges(k))**2, lagrangeCgCharges(k), (lagrangeCgCharges(k)-intCgCharges(k))**2 enddo write(35,'("Sums:", a20,a20,a20,a20)') "Atomic", "Grid Charges", "Integral Charges", "Sum of sq diff" write(35,'(4x,f20.10,f20.10,f20.10,f20.10)') sum(atomCharges), sum(cgCharges), sum(intCgCharges), temp close(35) write(*,'("Sums:", a20,a20,a20,a20)') "Atomic", "Grid Charges", "Integral Charges", "Sum of sq diff" write(*,'(4x,f20.10,f20.10,f20.10,f20.10)') sum(atomCharges), sum(cgCharges), sum(intCgCharges), temp close(35) ! write(*,'("CG grid charge:", f10.5, "CG int charges:", f10.5, " total atom charge:", f10.5)') sum(cgCharges), sum(intCgCharges), sum(atomCharges) endsubroutine read_xyz_fit_esp ! solve set of linear equations to solve for CG charges subroutine fit_cg_charges(atomEspMat,nAtoms,cgEspMat,nCgs,atomCharges,cgCharges) implicit none integer nCgs integer nAtoms real (kind=8) atomEspMat(nCgs,nAtoms) real (kind=8) cgEspMat(nCgs,nCgs) real (kind=8) cgCharges(nCgs) real (kind=8) atomCharges(nAtoms,1) integer info integer ipiv(nCgs) real(kind=8) B(nCgs,1) integer cg1, cg2 ! ! first symmetrize cgEspMat matrix ! do cg1 = 1, nCgs-1 ! do cg2 = cg1+1,nCgs ! cgEspMat(cg2,cg1) = cgEspMat(cg1,cg2) ! enddo ! enddo ! now compute right hand side of equation as A*q B = matmul(atomEspMat,atomCharges) call dgesv(nCgs, 1, cgEspMat, nCgs, ipiv, B, nCgs, info) cgCharges = B(1:nCgs,1) endsubroutine fit_cg_charges ! solve set of linear equations to solve for CG charges with Lagrange multipliers to enforce charge conservation subroutine fit_cg_charges_lagrange(atomEspMat,nAtoms,cgEspMat,nCgs,atomCharges,cgCharges) implicit none integer nCgs integer nAtoms real (kind=8) atomEspMat(nCgs,nAtoms) real (kind=8) cgEspMat(nCgs,nCgs) real (kind=8) cgCharges(nCgs) real (kind=8) atomCharges(nAtoms,1) integer info integer ipiv(nCgs+1) real(kind=8) B(nCgs+1,1) real(kind=8) A(nCgs+1,nCgs+1) integer cg1, cg2 ! first symmetric cgEspMat matrix do cg1 = 1, nCgs-1 do cg2 = cg1+1,nCgs cgEspMat(cg2,cg1) = cgEspMat(cg1,cg2) enddo enddo ! now compute right hand side of equation as A*q B(1:nCgs,:) = matmul(atomEspMat,atomCharges) B(nCgs+1,1) = sum(atomCharges) A(1:nCgs,1:nCgs) = cgEspMat A(nCgs+1,1:nCgs) = 1.0 A(1:nCgs,nCgs+1) = 1.0 A(nCgs+1,nCgs+1) = 0.0 call dgesv(nCgs+1, 1, A, nCgs+1, ipiv, B, nCgs+1, info) cgCharges = B(1:nCgs,1) endsubroutine fit_cg_charges_lagrange ! subroutine compute_grid_esp_mats(atomPos,nAtoms,cgPos,nCgs,atomEspMat,cgEspMat) use inputData, only : nThreads use gridData implicit none integer nAtoms real (kind=8) atomPos(nAtoms,3) integer nCgs real (kind=8) cgPos(nCgs,3) real (kind=8) atomEspMat(nCgs,nAtoms) real (kind=8) cgEspMat(nCgs,nCgs) real (kind=8) atomEspMat_temp(nCgs,nAtoms) real (kind=8) cgEspMat_temp(nCgs,nCgs) integer atom integer cg1, cg2 real (kind=8) diff1(3), diff2(3) real (kind=8) dist1_2, dist2_2 real (kind=8) dist1, dist2 integer grid, gridCount(3) real (kind=8) gridPos(3) logical gridPass !$omp parallel num_threads(nThreads) private(gridPass,atomEspMat_temp,cgEspMat_temp,grid,gridCount,gridPos,diff1,diff2,dist1_2,dist1,dist2_2,dist2,cg1,cg2,atom) shared(nGrids,deltaGrid,gridMin,cutoff2,cgEspMat,atomEspMat,nAtoms,nCgs) !$omp do do grid = 1, totalGrids gridCount(1) = int(grid/dble(nGrids(3)*nGrids(2))) gridCount(2) = int( (grid - gridCount(1)*nGrids(3)*nGrids(2)) / dble(nGrids(3))) gridCount(3) = mod(grid-1,nGrids(3)) gridPos = (gridCount+0.5)*deltaGrid + gridMin atomEspMat_temp = atomEspMat cgEspMat_temp = cgEspMat gridPass = .true. do cg1 = 1, nCgs diff1 = cgPos(cg1,:) - gridPos dist1_2 = dot_product(diff1,diff1) if (dist1_2 < cutoff2 .and. dist1_2 > minThresh2) then dist1 = sqrt(dist1_2) do cg2 = cg1, nCgs diff2 = cgPos(cg2,:) - gridPos dist2_2 = dot_product(diff2,diff2) if (dist2_2 < cutoff2 .and. dist2_2 > minThresh2) then dist2 = sqrt(dist2_2) !$omp atomic cgEspMat_temp(cg1,cg2) = cgEspMat_temp(cg1,cg2) + 1/(dist1*dist2) elseif (dist2_2 < minThresh2) then gridPass = .false. exit endif enddo if (gridPass.eqv..true.) then do atom=1, nAtoms diff2 = atomPos(atom,:) - gridPos dist2_2 = dot_product(diff2,diff2) if (dist2_2 < cutoff2 .and. dist2_2 > minThresh2) then dist2 = sqrt(dist2_2) !$omp atomic atomEspMat_temp(cg1,atom) = atomEspMat_temp(cg1,atom) + 1/(dist1*dist2) elseif (dist2_2 < minThresh2) then gridPass = .false. exit endif enddo endif elseif (dist1_2 < minThresh2) then gridPass = .false. exit endif if (gridPass .eqv. .false.) then exit endif enddo if (gridPass .eqv. .true.) then atomEspMat = atomEspMat_temp cgEspMat = cgEspMat_temp endif enddo !$omp end do !$omp end parallel endsubroutine compute_grid_esp_mats subroutine parse_command_line(cfgFile,nThreads,deltaStep) implicit none integer i character*30 arg character*80 cfgFile integer nThreads integer deltaStep logical deltaStepFlag logical cfgFileFlag logical nThreadsFlag deltaStepFlag = .false. nThreadsFlag = .false. cfgFileFlag = .false. i=1 do call get_command_argument(i, arg) select case (arg) case ('-cfg') i = i+1 call get_command_argument(i,cfgFile) cfgFileFlag=.true. print*, "CFG File: ", cfgFile case ('-stride') i = i+1 call get_command_argument(i,arg) read(arg,'(i10)') deltaStep print*, "Stride: ", deltaStep deltaStepFlag = .true. case ('-np') i = i+1 call get_command_argument(i,arg) read(arg,'(i10)') nThreads print*, "Number of threads: ", nThreads nThreadsFlag = .true. case default print '(a,a,/)', 'Unrecognized command-line option: ', arg print*, 'Usage: esp_grid.x -cfg [cfg file] -stride [delta step size] -np [number of threads]' stop end select i = i+1 if (i.ge.command_argument_count()) exit enddo if (cfgFileFlag.eqv..false.) then write(*,'("Must provide a cfg file using command line argument -cfg [cfg file name]")') stop endif if (deltaStepFlag.eqv..false.) then write(*,'("Using default step size of 1. Change this with command line argument -stride [delta step size]")') deltaStep = 1 endif if (nThreadsFlag.eqv..false.) then write(*,'("Using default of 1 thread. Change this with command line argument -np [number of threads]")') nThreads = 1 endif endsubroutine parse_command_line !read config information from file subroutine parse_config_file(cfgFile) use gridData use atomData use cgData implicit none character*80 cfgFile character*200 line character*80,firstWord integer i, k character*30 arg character*30 sep real (kind=8) cutoff integer ios logical atomXyzFlag logical atomPsfFlag logical cgXyzFlag logical outFileFlag logical gridMaxFlag logical gridMinFlag logical deltaGridFlag logical cutoffFlag logical maxCutFlag atomXyzFlag = .false. atomPsfFlag = .false. cgXyzFlag = .false. outFileFlag = .false. gridMaxFlag = .false. gridMinFlag = .false. deltaGridFlag = .false. cutoffFlag = .false. maxCutFlag = .false. open(12,file=cfgFile) do while(ios>=0) read(12,'(a600)',IOSTAT=ios) line call split(line,'=',firstWord, sep) if (line .ne. "") then if (firstWord .eq. "atomxyzfile") then atomXyzFile = line write(*,*) "Atom xyz file:", atomXyzFile atomXyzFlag = .true. else if (firstWord .eq. "atompsffile") then atomPsfFile = line write(*,*) "Atom PSF file:", atomPsfFile atomPsfFlag = .true. else if (firstWord .eq. "cgxyzfile") then cgXyzFile = line write(*,*) "CG xyz file:", cgXyzFile cgXyzFlag = .true. else if (firstWord .eq. "outfile") then outFile = line write(*,*) "out file:", outFile outFileFlag = .true. else if (firstWord .eq. "deltagrid") then read(line,'(f10.5)') deltaGrid write(*,*) "deltaGrid:", deltaGrid deltaGridFlag = .true. else if (firstWord .eq. "cutoff") then read(line,'(f10.5)') cutoff cutoff2 = cutoff * cutoff write(*,*) "cutoff:", cutoff cutoffFlag = .true. else if (firstWord .eq. "maxcut") then read(line,'(i10)') maxCutInt write(*,*) "maxCut:", maxCutInt maxCutFlag = .true. else if (firstWord .eq. "maxgrid") then do k = 1,3 call split(line,' ',firstWord, sep) read(firstWord,'(f10.5)') gridMax(k) enddo write(*,*) "max grid:", gridMax(1), gridMax(2), gridMax(3) gridMaxFlag = .true. else if (firstWord .eq. "mingrid") then do k = 1,3 call split(line,' ',firstWord, sep) read(firstWord,'(f10.5)') gridMin(k) enddo write(*,*) "min grid:", gridMin(1),gridMin(2),gridMin(3) gridMinFlag = .true. endif endif enddo close(12) if (cutoffFlag.eqv..false.) then write(*,'("cutoff not defined. using default of 20.0. change with cutoff = [cutoff] in config file")') cutoff = 20.0 cutoff2 = cutoff * cutoff endif if (maxCutFlag.eqv..false.) then write(*,'("maxCut not defined. using default of 50.0. change with maxcut = [maxcut] in config file")') maxCutInt = 50 endif if (atomXyzFlag.eqv..false.) then write(*,'("Must provide a atom xyz file using command line argument -adcd [atom dcd file name]")') stop endif if (atomPsfFlag.eqv..false.) then write(*,'("Must provide a atom PSF file using config file")') stop endif if (cgXyzFlag.eqv..false.) then write(*,'("Must provide a CG xyz file using config file")') stop endif if (outFileFlag.eqv..false.) then write(*,'("Must provide an output file name using command line argument -o [output file name]")') stop endif if (gridMaxFlag.eqv..false.) then write(*,'("Using default max radius of 400. Change this with command line argument -max [max radius]")') gridMax = 100.0 endif if (gridMinFlag.eqv..false.) then write(*,'("Using default min radius of 0. Change this with command line argument -min [min radius]")') gridMin = 0.0 endif if (deltaGridFlag.eqv..false.) then write(*,'("Using default of deltaGrid=1.0.")') deltaGrid=1.0 endif ! compute total number of grid points totalGrids = 1.0 do k=1,3 nGrids(k) = int( (gridMax(k)-gridMin(k))/deltaGrid) + 1 totalGrids = totalGrids*nGrids(k) enddo gridCut = int(cutoff/deltaGrid) + 1 endsubroutine parse_config_file !subroutine to compute CG charges from input matrices A and B. The residual sum of squares is calculated with aid of all-atom matrix C subroutine integral_fit_charges(A, B, C, atomCharges, cgCharges, nAtoms, nCg, rss) implicit none integer nAtoms integer nCg real (kind=8) A(nCg,nCg) real (kind=8) ATemp(nCg,nCg) real (kind=8) D(nCg-1,nCg) real (kind=8) B(nCg,nAtoms) real (kind=8) C(nAtoms,nAtoms) real (kind=8) BTemp(nCg,nAtoms) real (kind=8) cgCharges(nCg,1) real (kind=8) atomCharges(nAtoms) real (kind=8) atomChargesM(nAtoms,1) real (kind=8) newB(nCg) real (kind=8) temp(1,1) real (kind=8) rss integer j, i, k !lapack routine variables integer ipiv(nCg) integer info !First we need to modify A and B to have the correct matrix properties !create D matrices D=0.0 do i=1,nCg-1 D(i,i)=1.0 D(i,i+1)=-1.0 enddo !multiply A by D0 and B by D1 giving new matrices A and B the correct behavior ATemp(1:(nCg-1),:) = matmul(D,A) BTemp(1:(nCg-1),:) = matmul(D,B) !generate new matrices with last line having 1.0s forcing charge conservation ATemp(nCg,:) = 1.0 BTemp(nCg,:) = 1.0 ! multiple right hand side of equation by atomic charges newB = matmul(BTemp,atomCharges) ! determine the solution to system of linear equations ATemp*X = newB call dgesv(nCg,1, ATemp,nCg,ipiv,newB,nCg,info) cgCharges(:,1) = real(newB(1:nCg)) atomChargesM(:,1) = atomCharges ! compute residual sum of squares temp = matmul(transpose(atomChargesM),matmul(C,atomChargesM))+matmul(transpose(cgCharges),matmul(A,cgCharges))-2*matmul(transpose(cgCharges),matmul(B,atomChargesM)) rss = temp(1,1) endsubroutine integral_fit_charges !requires lapack subroutine update_A_B_C_matrices(atomPos,nAtoms,cgPos,nCgs,A,B,C) implicit none integer nAtoms integer nCgs real (kind=8) atomPos(nAtoms,3) real (kind=8) atomCharges(nAtoms) real (kind=8) cgPos(nCgs,3) real (kind=8) A(nCgs,nCgs) real (kind=8) B(nCgs,nAtoms) real (kind=8) C(nAtoms,nAtoms) real (kind=8) dist, temp !loop indeces integer cgSite1, cgSite2 integer j integer atom1, atom2 ! populate A matrix with negative distances between CG sites do cgSite1 = 1, nCgs-1 do cgSite2 = cgSite1+1,nCgs dist = 0 do j=1,3 temp = cgPos(cgSite1,j)-cgPos(cgSite2,j) dist = dist + temp*temp enddo dist = sqrt(dist) A(cgSite1,cgSite2) = A(cgSite1,cgSite2)-dist !symmetrize the matrix A(cgSite2,cgSite1) = A(cgSite1,cgSite2) enddo enddo ! populate B matrix with negative distance between CG sites and atoms do cgSite1 = 1, nCgs do atom1 = 1,nAtoms dist = 0 do j=1,3 temp = cgPos(cgSite1,j)-atomPos(atom1,j) dist = dist + temp*temp enddo B(cgSite1,atom1) = B(cgSite1,atom1)-sqrt(dist) enddo enddo ! populate C matrix with negative distance between atoms do atom1 = 1, nAtoms-1 do atom2 = atom1+1, nAtoms dist = 0 do j=1,3 temp = atomPos(atom1,j)-atomPos(atom2,j) dist = dist + temp*temp enddo C(atom1,atom2) = C(atom1,atom2)-sqrt(dist) ! symmetrize the matrix C(atom2,atom1) = C(atom1,atom2) enddo enddo endsubroutine update_A_B_C_matrices !Read atomic charges from some file subroutine read_atom_xyz use atomData implicit none ! real (kind=8), parameter :: chargeConvert = 553.43949573 ! to convert to kT/e with dielectric of 1 real (kind=8), parameter :: chargeConvert = 1.0 ! integer atom, j character*600 line character*80,firstWord character*30 sep integer ios !open the xyz file open(20,file=atomXyzFile) ! first line contains number of atoms read(20,'(a600)') line call split(line,' ',firstWord, sep) read(firstWord,'(i10)') nAtoms print*, "Number of atoms:", nAtoms ! allocate position and charge arrays allocate(atomCharges(nAtoms)) allocate(atomPos(nAtoms,3)) ! skip second line read(20,*) ! read position and charge of all atoms do atom=1, nAtoms read(20,'(a600)') line call split(line,' ',firstWord, sep) do j = 1,3 call split(line,' ',firstWord, sep) read(firstWord,'(f20.5)') atomPos(atom,j) enddo call split(line,' ',firstWord, sep) read(firstWord,'(f20.5)') atomCharges(atom) enddo close(20) endsubroutine read_atom_xyz !Read CG positions subroutine read_cg_xyz use cgData implicit none integer atom, j character*600 line character*80,firstWord character*30 sep integer ios !open the xyz file open(30,file=cgXyzFile) ! first line contains number of atoms read(30,'(a600)') line call split(line,' ',firstWord, sep) read(firstWord,'(i10)') nCgs print*, "Number of CG sites:", nCgs ! allocate position and charge arrays allocate(cgCharges(nCgs)) allocate(cgPos(nCgs,3)) ! skip second line read(30,*) ! read position and charge of all atoms do atom=1, nCgs read(30,'(a600)') line call split(line,' ',firstWord, sep) do j = 1,3 call split(line,' ',firstWord, sep) read(firstWord,'(f20.5)') cgPos(atom,j) enddo enddo close(30) endsubroutine read_cg_xyz !Read atomic charges from some file subroutine read_psf_file use atomData implicit none ! real (kind=8), parameter :: chargeConvert = 553.43949573 ! to convert to kT/e with dielectric of 1 real (kind=8), parameter :: chargeConvert = 1.0 ! integer atom, j character*6 check !character to check if NATOM is in the line character*8 numChar !character to read number of atoms. must be converted to an integer character*4 atomCheck character*24 posChar integer ios !open the psf file print*, "psf file name here:", atomPsfFile open(10,file=atomPsfFile) !run through the header of the file and look for the number of atoms do read(10,'(a8,2x,a6)') numChar, check !if we read the number of atoms exit this do loop if (check.eq.'NATOM ') then !this converts the character natoms_char to the integer natoms read(numChar,*) nAtoms write(*,*) "Number of atoms=", nAtoms !Now that we know the number of atoms we must allocate the arrays allocate(atomCharges(nAtoms)) allocate(atomPos(nAtoms,3)) !Now we loop through the number of atoms and read the pertinent information do atom=1,nAtoms read(10,'(34x,f10.6)') atomCharges(atom) atomCharges(atom) = atomCharges(atom) * chargeConvert !add to total charge enddo write(*,*) "Total charge in atom psf=", sum(atomCharges) elseif (check.eq.'NBOND:') then exit endif enddo close(10) endsubroutine read_psf_file
315/60 R22.5 Tyres Fitted to Front Axle. 295/60 R22.5 Tyres Fitted to Rear Axle. Twin Long Range Aluminium Fuel Tank. Mileage As Shown : 864,152 Kms.
[STATEMENT] lemma cf_comma_proj_left_is_functor: assumes "\<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>" and "\<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC>" shows "\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA> [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA> [PROOF STEP] interpret \<GG>: is_functor \<alpha> \<AA> \<CC> \<GG> [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> [PROOF STEP] by (rule assms(1)) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA> [PROOF STEP] interpret \<HH>: is_functor \<alpha> \<BB> \<CC> \<HH> [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> [PROOF STEP] by (rule assms(2)) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA> [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> [PROOF STEP] interpret \<GG>\<HH>: category \<alpha> \<open>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<close> [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> goal (1 subgoal): 1. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) [PROOF STEP] by (cs_concl cs_shallow cs_intro: cat_comma_cs_intros) [PROOF STATE] proof (state) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA> [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA> [PROOF STEP] proof(rule is_functorI') [PROOF STATE] proof (state) goal (15 subgoals): 1. \<Z> \<alpha> 2. vfsequence (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) 3. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) 4. category \<alpha> \<AA> 5. vcard (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) = 4\<^sub>\<nat> 6. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomDom\<rparr> = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> 7. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomCod\<rparr> = \<AA> 8. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) 9. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) 10. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> A total of 15 subgoals... [PROOF STEP] show "vfsequence (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. vfsequence (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) [PROOF STEP] unfolding cf_comma_proj_left_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. vfsequence [\<lambda>a\<in>\<^sub>\<circ>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr>. a\<lparr>[]\<^sub>\<circ>\<rparr>, \<lambda>f\<in>\<^sub>\<circ>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Arr\<rparr>. f\<lparr>2\<^sub>\<nat>\<rparr>\<lparr>[]\<^sub>\<circ>\<rparr>, \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>, \<GG>\<lparr>HomDom\<rparr>]\<^sub>\<circ> [PROOF STEP] by auto [PROOF STATE] proof (state) this: vfsequence (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) goal (14 subgoals): 1. \<Z> \<alpha> 2. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) 3. category \<alpha> \<AA> 4. vcard (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) = 4\<^sub>\<nat> 5. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomDom\<rparr> = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> 6. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomCod\<rparr> = \<AA> 7. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) 8. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) 9. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> 10. \<R>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) \<subseteq>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> A total of 14 subgoals... [PROOF STEP] show "vcard (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) = 4\<^sub>\<nat>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. vcard (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) = 4\<^sub>\<nat> [PROOF STEP] unfolding cf_comma_proj_left_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. vcard [\<lambda>a\<in>\<^sub>\<circ>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr>. a\<lparr>[]\<^sub>\<circ>\<rparr>, \<lambda>f\<in>\<^sub>\<circ>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Arr\<rparr>. f\<lparr>2\<^sub>\<nat>\<rparr>\<lparr>[]\<^sub>\<circ>\<rparr>, \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>, \<GG>\<lparr>HomDom\<rparr>]\<^sub>\<circ> = 4\<^sub>\<nat> [PROOF STEP] by (simp add: nat_omega_simps) [PROOF STATE] proof (state) this: vcard (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>) = 4\<^sub>\<nat> goal (13 subgoals): 1. \<Z> \<alpha> 2. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) 3. category \<alpha> \<AA> 4. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomDom\<rparr> = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> 5. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomCod\<rparr> = \<AA> 6. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) 7. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) 8. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> 9. \<R>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) \<subseteq>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> 10. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Arr\<rparr> A total of 13 subgoals... [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> [PROOF STEP] show "\<R>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) \<subseteq>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr>" [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> goal (1 subgoal): 1. \<R>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) \<subseteq>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> [PROOF STEP] by (rule cf_comma_proj_left_ObjMap_vrange) [PROOF STATE] proof (state) this: \<R>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) \<subseteq>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> goal (12 subgoals): 1. \<Z> \<alpha> 2. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) 3. category \<alpha> \<AA> 4. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomDom\<rparr> = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> 5. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomCod\<rparr> = \<AA> 6. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) 7. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) 8. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> 9. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Arr\<rparr> 10. \<And>a b f. f : a \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> b \<Longrightarrow> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>f\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> A total of 12 subgoals... [PROOF STEP] show "\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>B\<rparr>" if "F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B" for A B F [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>B\<rparr> [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>B\<rparr> [PROOF STEP] from assms that [PROOF STATE] proof (chain) picking this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B [PROOF STEP] obtain a b f a' b' f' g h where F_def: "F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ>" and A_def: "A = [a, b, f]\<^sub>\<circ>" and B_def: "B = [a', b', f']\<^sub>\<circ>" and g: "g : a \<mapsto>\<^bsub>\<AA>\<^esub> a'" [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B goal (1 subgoal): 1. (\<And>a b f a' b' f' g h. \<lbrakk>F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ>; A = [a, b, f]\<^sub>\<circ>; B = [a', b', f']\<^sub>\<circ>; g : a \<mapsto>\<^bsub>\<AA>\<^esub> a'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ> A = [a, b, f]\<^sub>\<circ> B = [a', b', f']\<^sub>\<circ> g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>B\<rparr> [PROOF STEP] from that g [PROOF STATE] proof (chain) picking this: F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' [PROOF STEP] show "\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>B\<rparr>" [PROOF STATE] proof (prove) using this: F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>B\<rparr> [PROOF STEP] unfolding F_def A_def B_def [PROOF STATE] proof (prove) using this: [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ> : [a, b, f]\<^sub>\<circ> \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> [a', b', f']\<^sub>\<circ> g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr> \<lparr>[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>\<rparr>\<^sub>\<bullet> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr> \<lparr>a, b, f\<rparr>\<^sub>\<bullet> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr> \<lparr>a', b', f'\<rparr>\<^sub>\<bullet> [PROOF STEP] by (cs_concl cs_simp: cat_comma_cs_simps cs_intro: cat_cs_intros) [PROOF STATE] proof (state) this: \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>B\<rparr> goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: ?F : ?A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> ?B \<Longrightarrow> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>?F\<rparr> : \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>?A\<rparr> \<mapsto>\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>?B\<rparr> goal (11 subgoals): 1. \<Z> \<alpha> 2. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) 3. category \<alpha> \<AA> 4. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomDom\<rparr> = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> 5. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomCod\<rparr> = \<AA> 6. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) 7. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) 8. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> 9. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Arr\<rparr> 10. \<And>b c g a f. \<lbrakk>g : b \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> c; f : a \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> b\<rbrakk> \<Longrightarrow> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>g \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> f\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>f\<rparr> A total of 11 subgoals... [PROOF STEP] show "\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr>" if "G : B \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> C" and "F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B" for B C G A F [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> [PROOF STEP] from assms that(2) [PROOF STATE] proof (chain) picking this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B [PROOF STEP] obtain a b f a' b' f' g h where F_def: "F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ>" and A_def: "A = [a, b, f]\<^sub>\<circ>" and B_def: "B = [a', b', f']\<^sub>\<circ>" and g: "g : a \<mapsto>\<^bsub>\<AA>\<^esub> a'" and h: "h : b \<mapsto>\<^bsub>\<BB>\<^esub> b'" and f: "f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr>" and f': "f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr>" and [cat_cs_simps]: "f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f" [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B goal (1 subgoal): 1. (\<And>a b f a' b' f' g h. \<lbrakk>F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ>; A = [a, b, f]\<^sub>\<circ>; B = [a', b', f']\<^sub>\<circ>; g : a \<mapsto>\<^bsub>\<AA>\<^esub> a'; h : b \<mapsto>\<^bsub>\<BB>\<^esub> b'; f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr>; f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr>; f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ> A = [a, b, f]\<^sub>\<circ> B = [a', b', f']\<^sub>\<circ> g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' h : b \<mapsto>\<^bsub>\<BB>\<^esub> b' f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr> f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> [PROOF STEP] with that(1) assms [PROOF STATE] proof (chain) picking this: G : B \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> C \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ> A = [a, b, f]\<^sub>\<circ> B = [a', b', f']\<^sub>\<circ> g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' h : b \<mapsto>\<^bsub>\<BB>\<^esub> b' f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr> f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f [PROOF STEP] obtain a'' b'' f'' g' h' where G_def: "G = [[a', b', f']\<^sub>\<circ>, [a'', b'', f'']\<^sub>\<circ>, [g', h']\<^sub>\<circ>]\<^sub>\<circ>" and C_def: "C = [a'', b'', f'']\<^sub>\<circ>" and g': "g' : a' \<mapsto>\<^bsub>\<AA>\<^esub> a''" and h': "h' : b' \<mapsto>\<^bsub>\<BB>\<^esub> b''" and f'': "f'' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a''\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b''\<rparr>" and [cat_cs_simps]: "f'' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f'" [PROOF STATE] proof (prove) using this: G : B \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> C \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> F = [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ> A = [a, b, f]\<^sub>\<circ> B = [a', b', f']\<^sub>\<circ> g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' h : b \<mapsto>\<^bsub>\<BB>\<^esub> b' f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr> f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f goal (1 subgoal): 1. (\<And>a'' b'' f'' g' h'. \<lbrakk>G = [[a', b', f']\<^sub>\<circ>, [a'', b'', f'']\<^sub>\<circ>, [g', h']\<^sub>\<circ>]\<^sub>\<circ>; C = [a'', b'', f'']\<^sub>\<circ>; g' : a' \<mapsto>\<^bsub>\<AA>\<^esub> a''; h' : b' \<mapsto>\<^bsub>\<BB>\<^esub> b''; f'' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a''\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b''\<rparr>; f'' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f'\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: G = [[a', b', f']\<^sub>\<circ>, [a'', b'', f'']\<^sub>\<circ>, [g', h']\<^sub>\<circ>]\<^sub>\<circ> C = [a'', b'', f'']\<^sub>\<circ> g' : a' \<mapsto>\<^bsub>\<AA>\<^esub> a'' h' : b' \<mapsto>\<^bsub>\<BB>\<^esub> b'' f'' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a''\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b''\<rparr> f'' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f' goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> [PROOF STEP] (*slow*) [PROOF STATE] proof (state) this: G = [[a', b', f']\<^sub>\<circ>, [a'', b'', f'']\<^sub>\<circ>, [g', h']\<^sub>\<circ>]\<^sub>\<circ> C = [a'', b'', f'']\<^sub>\<circ> g' : a' \<mapsto>\<^bsub>\<AA>\<^esub> a'' h' : b' \<mapsto>\<^bsub>\<BB>\<^esub> b'' f'' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a''\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b''\<rparr> f'' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f' goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> [PROOF STEP] note [cat_cs_simps] = category.cat_assoc_helper [ where \<CC>=\<CC> and h=f'' and g=\<open>\<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr>\<close> and q=\<open>\<HH>\<lparr>ArrMap\<rparr>\<lparr>h'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f'\<close> ] category.cat_assoc_helper [ where \<CC>=\<CC> and h=f and g=\<open>\<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr>\<close> and q=\<open>f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr>\<close> ] [PROOF STATE] proof (state) this: \<lbrakk>category ?\<alpha> \<CC>; ?f : ?a \<mapsto>\<^bsub>\<CC>\<^esub> ?b; \<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr> : ?b \<mapsto>\<^bsub>\<CC>\<^esub> ?c; f'' : ?c \<mapsto>\<^bsub>\<CC>\<^esub> ?d; f'' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr> = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f'\<rbrakk> \<Longrightarrow> f'' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> (\<GG>\<lparr>ArrMap\<rparr>\<lparr>g'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> ?f) = \<HH>\<lparr>ArrMap\<rparr>\<lparr>h'\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> ?f \<lbrakk>category ?\<alpha> \<CC>; ?f : ?a \<mapsto>\<^bsub>\<CC>\<^esub> ?b; \<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> : ?b \<mapsto>\<^bsub>\<CC>\<^esub> ?c; f : ?c \<mapsto>\<^bsub>\<CC>\<^esub> ?d; f \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> = f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr>\<rbrakk> \<Longrightarrow> f \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> (\<HH>\<lparr>ArrMap\<rparr>\<lparr>h\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> ?f) = f' \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> \<GG>\<lparr>ArrMap\<rparr>\<lparr>g\<rparr> \<circ>\<^sub>A\<^bsub>\<CC>\<^esub> ?f goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> [PROOF STEP] from assms that g g' h h' f f' f'' [PROOF STATE] proof (chain) picking this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> G : B \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> C F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' g' : a' \<mapsto>\<^bsub>\<AA>\<^esub> a'' h : b \<mapsto>\<^bsub>\<BB>\<^esub> b' h' : b' \<mapsto>\<^bsub>\<BB>\<^esub> b'' f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr> f'' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a''\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b''\<rparr> [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> G : B \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> C F : A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> B g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' g' : a' \<mapsto>\<^bsub>\<AA>\<^esub> a'' h : b \<mapsto>\<^bsub>\<BB>\<^esub> b' h' : b' \<mapsto>\<^bsub>\<BB>\<^esub> b'' f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr> f'' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a''\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b''\<rparr> goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> [PROOF STEP] unfolding F_def G_def A_def B_def C_def [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> [[a', b', f']\<^sub>\<circ>, [a'', b'', f'']\<^sub>\<circ>, [g', h']\<^sub>\<circ>]\<^sub>\<circ> : [a', b', f']\<^sub>\<circ> \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> [a'', b'', f'']\<^sub>\<circ> [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ> : [a, b, f]\<^sub>\<circ> \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> [a', b', f']\<^sub>\<circ> g : a \<mapsto>\<^bsub>\<AA>\<^esub> a' g' : a' \<mapsto>\<^bsub>\<AA>\<^esub> a'' h : b \<mapsto>\<^bsub>\<BB>\<^esub> b' h' : b' \<mapsto>\<^bsub>\<BB>\<^esub> b'' f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> f' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a'\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b'\<rparr> f'' : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a''\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b''\<rparr> goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>[[a', b', f']\<^sub>\<circ>, [a'', b'', f'']\<^sub>\<circ>, [g', h']\<^sub>\<circ>]\<^sub>\<circ> \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> [[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>]\<^sub>\<circ>\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr> \<lparr>[a', b', f']\<^sub>\<circ>, [a'', b'', f'']\<^sub>\<circ>, [g', h']\<^sub>\<circ>\<rparr>\<^sub>\<bullet> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr> \<lparr>[a, b, f]\<^sub>\<circ>, [a', b', f']\<^sub>\<circ>, [g, h]\<^sub>\<circ>\<rparr>\<^sub>\<bullet> [PROOF STEP] by ( cs_concl cs_shallow cs_simp: cat_cs_simps cat_comma_cs_simps cs_intro: cat_comma_cs_intros cat_cs_intros ) [PROOF STATE] proof (state) this: \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>F\<rparr> goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: \<lbrakk>?G : ?B \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> ?C; ?F : ?A \<mapsto>\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> ?B\<rbrakk> \<Longrightarrow> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>?G \<circ>\<^sub>A\<^bsub>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<^esub> ?F\<rparr> = \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>?G\<rparr> \<circ>\<^sub>A\<^bsub>\<AA>\<^esub> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>?F\<rparr> goal (10 subgoals): 1. \<Z> \<alpha> 2. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) 3. category \<alpha> \<AA> 4. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomDom\<rparr> = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> 5. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomCod\<rparr> = \<AA> 6. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) 7. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) 8. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> 9. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Arr\<rparr> 10. \<And>c. c \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> \<Longrightarrow> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>c\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>c\<rparr>\<rparr> [PROOF STEP] show "\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>A\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr>\<rparr>" if "A \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr>" for A [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>A\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr>\<rparr> [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>A\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr>\<rparr> [PROOF STEP] from assms that [PROOF STATE] proof (chain) picking this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> A \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> [PROOF STEP] obtain a b f where A_def: "A = [a, b, f]\<^sub>\<circ>" and "a \<in>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr>" and "b \<in>\<^sub>\<circ> \<BB>\<lparr>Obj\<rparr>" and "f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr>" [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> A \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> goal (1 subgoal): 1. (\<And>a b f. \<lbrakk>A = [a, b, f]\<^sub>\<circ>; a \<in>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr>; b \<in>\<^sub>\<circ> \<BB>\<lparr>Obj\<rparr>; f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr>\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: A = [a, b, f]\<^sub>\<circ> a \<in>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> b \<in>\<^sub>\<circ> \<BB>\<lparr>Obj\<rparr> f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>A\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr>\<rparr> [PROOF STEP] from assms that this(2-4) [PROOF STATE] proof (chain) picking this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> A \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> a \<in>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> b \<in>\<^sub>\<circ> \<BB>\<lparr>Obj\<rparr> f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> A \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> a \<in>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> b \<in>\<^sub>\<circ> \<BB>\<lparr>Obj\<rparr> f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>A\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr>\<rparr> [PROOF STEP] unfolding A_def [PROOF STATE] proof (prove) using this: \<GG> : \<AA> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> \<HH> : \<BB> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<CC> [a, b, f]\<^sub>\<circ> \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> a \<in>\<^sub>\<circ> \<AA>\<lparr>Obj\<rparr> b \<in>\<^sub>\<circ> \<BB>\<lparr>Obj\<rparr> f : \<GG>\<lparr>ObjMap\<rparr>\<lparr>a\<rparr> \<mapsto>\<^bsub>\<CC>\<^esub> \<HH>\<lparr>ObjMap\<rparr>\<lparr>b\<rparr> goal (1 subgoal): 1. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr> \<lparr>a, b, f\<rparr>\<^sub>\<bullet>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr> \<lparr>a, b, f\<rparr>\<^sub>\<bullet>\<rparr> [PROOF STEP] by ( cs_concl cs_shallow cs_simp: cat_cs_simps cat_comma_cs_simps cs_intro: cat_comma_cs_intros cat_cs_intros ) [PROOF STATE] proof (state) this: \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>A\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>A\<rparr>\<rparr> goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: ?A \<in>\<^sub>\<circ> \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> \<Longrightarrow> \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>CId\<rparr>\<lparr>?A\<rparr>\<rparr> = \<AA>\<lparr>CId\<rparr>\<lparr>\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>\<lparr>?A\<rparr>\<rparr> goal (9 subgoals): 1. \<Z> \<alpha> 2. category \<alpha> (\<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>) 3. category \<alpha> \<AA> 4. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomDom\<rparr> = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> 5. \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>HomCod\<rparr> = \<AA> 6. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) 7. vsv (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) 8. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ObjMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Obj\<rparr> 9. \<D>\<^sub>\<circ> (\<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH>\<lparr>ArrMap\<rparr>) = \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH>\<lparr>Arr\<rparr> [PROOF STEP] qed ( use assms in \<open> cs_concl cs_shallow cs_simp: cat_comma_cs_simps cs_intro: cat_cs_intros cat_comma_cs_intros \<close> )+ [PROOF STATE] proof (state) this: \<GG> \<^sub>C\<^sub>F\<Sqinter> \<HH> : \<GG> \<^sub>C\<^sub>F\<down>\<^sub>C\<^sub>F \<HH> \<mapsto>\<mapsto>\<^sub>C\<^bsub>\<alpha>\<^esub> \<AA> goal: No subgoals! [PROOF STEP] qed
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) lg93_ad := 1e-8: lg93_b := 0.024974: lg93_a2 := (lg93_ad + 0.1234)/lg93_b: lg93_a4 := 29.790: lg93_a6 := 22.417: lg93_a8 := 12.119: lg93_a10 := 1570.1: lg93_a12 := 55.944: lg93_f0 := s-> 1 + lg93_a2*s^2 + lg93_a4*s^4 + lg93_a6*s^6 + lg93_a8*s^8 + lg93_a10*s^10 + lg93_a12*s^12: lg93_f1 := s-> lg93_f0(s)^lg93_b/(1 + lg93_ad*s^2): lg93_f := x->lg93_f1(X2S*x): f := (rs, zeta, xt, xs0, xs1) -> gga_exchange(lg93_f, rs, zeta, xs0, xs1):
lemma algebraic_int_root: assumes "algebraic_int y" and "poly p x = y" and "\<forall>i. coeff p i \<in> \<int>" and "lead_coeff p = 1" and "degree p > 0" shows "algebraic_int x"
subroutine z_vermom_nhfull(nmmax ,kmax ,icx ,icy ,u0 , & & v0 ,w0 ,vicww ,rxz ,ryz , & & guu ,gvv ,guv ,gvu ,kfs , & & kcs ,aak ,bbk ,cck ,ddk , & & bdx ,bux ,bdy ,buy ,uvdwk ,vvdwk , & & kfuz0 ,kfvz0 ,kfsz0 ,kfsmin ,kfsmx0 , & & kcshyd ,w1 ,p0 ,zk ,nst , & & gdp ) !----- GPL --------------------------------------------------------------------- ! ! Copyright (C) Stichting Deltares, 2011-2016. ! ! This program is free software: you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation version 3. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License ! along with this program. If not, see <http://www.gnu.org/licenses/>. ! ! contact: [email protected] ! Stichting Deltares ! P.O. Box 177 ! 2600 MH Delft, The Netherlands ! ! All indications and logos of, and references to, "Delft3D" and "Deltares" ! are registered trademarks of Stichting Deltares, and remain the property of ! Stichting Deltares. All rights reserved. ! !------------------------------------------------------------------------------- ! $Id: z_vermom_nhfull.f90 5717 2016-01-12 11:35:24Z mourits $ ! $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/tags/6686/src/engines_gpl/flow2d3d/packages/kernel/src/non_hydro/z_vermom_nhfull.f90 $ !!--description----------------------------------------------------------------- ! ! Vertical momentum equation. Integration for ! full timestep. w0 is vertical velocity at ! end of previous non-hydrostatic timestep. ! !!--pseudo code and references-------------------------------------------------- ! NONE !!--declarations---------------------------------------------------------------- use precision use globaldata ! implicit none ! type(globdat),target :: gdp ! ! The following list of pointer parameters is used to point inside the gdp structure ! real(fp) , pointer :: eps integer , pointer :: lundia real(fp) , pointer :: hdt real(fp) , pointer :: rhow real(fp) , pointer :: vicmol integer , pointer :: m1_nhy integer , pointer :: m2_nhy integer , pointer :: n1_nhy integer , pointer :: n2_nhy character(6) , pointer :: momsol ! ! Global variables ! integer , intent(in) :: icx integer , intent(in) :: icy integer , intent(in) :: kmax ! Description and declaration in esm_alloc_int.f90 integer , intent(in) :: nmmax ! Description and declaration in dimens.igs integer , dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: kcs ! Description and declaration in esm_alloc_int.f90 integer , dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: kfs ! Description and declaration in esm_alloc_int.f90 integer , dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: kfsmx0 ! Description and declaration in esm_alloc_int.f90 integer , dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: kfsmin ! Description and declaration in esm_alloc_int.f90 integer , dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: kcshyd ! Description and declaration in esm_alloc_int.f90 integer , dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: kfsz0 ! Description and declaration in esm_alloc_int.f90 integer , dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: kfuz0 ! Description and declaration in esm_alloc_int.f90 integer , dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: kfvz0 ! Description and declaration in esm_alloc_int.f90 integer , intent(in) :: nst !! Time step number real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: guu ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: guv ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: gvu ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub) , intent(in) :: gvv ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: aak real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: bbk real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: cck real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: ddk real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bdx !! Internal work array real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bux !! Internal work array real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: bdy !! Internal work array real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: buy !! Internal work array real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: uvdwk !! Internal work array for Jac.iteration real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: vvdwk !! Internal work array for Jac.iteration real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) , intent(in) :: vicww ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) , intent(in) :: w0 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, 0:kmax) :: w1 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: p0 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: rxz ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) :: ryz ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: u0 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(gdp%d%nmlb:gdp%d%nmub, kmax) , intent(in) :: v0 ! Description and declaration in esm_alloc_real.f90 real(fp), dimension(0:kmax) , intent(in) :: zk ! Description and declaration in esm_alloc_real.f90 ! ! Local variables ! integer :: ddb integer :: icxy integer :: ifkx integer :: ifky integer :: ikenx integer :: ikeny integer :: iter integer :: itr integer :: k integer :: kfad integer :: ku integer :: kuu integer :: kd integer :: m integer :: maxk integer :: mink integer :: ndelta integer :: ndm integer :: ndmd integer :: ndmu integer :: nm integer :: nmd integer :: nmst integer :: nmstart integer :: nmu integer :: num integer :: numd integer :: numu real(fp) :: advecx real(fp) :: advecy real(fp) :: advecz real(fp) :: adza real(fp) :: adzc real(fp) :: bi real(fp) :: cuu real(fp) :: cvv real(fp) :: ddza real(fp) :: ddzb real(fp) :: ddzc real(fp) :: dt real(fp) :: dz real(fp) :: dzdo real(fp) :: dzu real(fp) :: dzup real(fp) :: dzv real(fp) :: geta real(fp) :: gksi real(fp) :: uuu real(fp) :: viscow real(fp) :: visk real(fp) :: viskup real(fp) :: vix real(fp) :: viy real(fp) :: vvv real(fp) :: wdo real(fp) :: wup real(fp) :: www real(fp) :: ddkadx real(fp) :: ddkady real(fp) :: ddkadz integer :: kadx integer :: kady integer :: kadz real(fp) :: area ! area of flux interface real(fp) :: uavg0 ! transport velocity at interface, east real(fp) :: vavg0 ! transport velocity at interface, north real(fp) :: wavg0 ! transport velocity at interface, top real(fp) :: wzeta ! conservation correction real(fp) :: thvert ! theta coefficient for vertical terms real(fp) :: pcoef ! temporary value for coefficient pressure derivative real(fp) :: voltemp ! work variable character(5) :: errtxt ! !! executable statements ------------------------------------------------------- ! eps => gdp%gdconst%eps lundia => gdp%gdinout%lundia m1_nhy => gdp%gdnonhyd%m1_nhy m2_nhy => gdp%gdnonhyd%m2_nhy n1_nhy => gdp%gdnonhyd%n1_nhy n2_nhy => gdp%gdnonhyd%n2_nhy rhow => gdp%gdphysco%rhow vicmol => gdp%gdphysco%vicmol hdt => gdp%gdnumeco%hdt momsol => gdp%gdnumeco%momsol ! ddb = gdp%d%ddbound icxy = max(icx,icy) dt = 2.0_fp * hdt thvert = 0.0_fp ! kadx = 1 kady = 1 kadz = 1 ! ddkadx = 0.0_fp ddkady = 0.0_fp ddkadz = 0.0_fp ! ndelta = n2_nhy - n1_nhy nmstart = (n1_nhy + ddb) + (m1_nhy - 1 + ddb)*icxy ! ! Array initialisation ! aak = 0.0_fp bbk = 1.0_fp cck = 0.0_fp ddk = 0.0_fp bdx = 0.0_fp bux = 0.0_fp bdy = 0.0_fp buy = 0.0_fp w1 = 0.0_fp ! ! Turbulent stresses rxz, ryz ! do m = m1_nhy, m2_nhy nmst = nmstart + (m - m1_nhy)*icxy do nm = nmst, nmst + ndelta if (kfs(nm)*kcs(nm) == 1) then nmu = nm + icx num = nm + icy rxz(nm,kmax) = 0.0_fp ryz(nm,kmax) = 0.0_fp do k = 1, kmax-1 ku = k + 1 kd = k - 1 ifkx = kfuz0(nm,k) * kfuz0(nm,ku) * kfsz0(nm,k) * kfsz0(nmu,k) ifky = kfvz0(nm,k) * kfvz0(nm,ku) * kfsz0(nm,k) * kfsz0(num,k) vix = 0.5_fp * (vicww(nm,k)+vicww(nmu,k)) viy = 0.5_fp * (vicww(nm,k)+vicww(num,k)) dzu = 0.5_fp * (zk(ku)-zk(kd)) dzv = 0.5_fp * (zk(ku)-zk(kd)) if (ifkx == 1) then rxz(nm,k) = vix * ( (w0(nmu,k )-w0(nm,k))/gvu(nm) & & + (u0(nm ,ku)-u0(nm,k))/dzu ) else rxz(nm,k) = 0.0_fp endif if (ifky == 1) then ryz(nm,k) = viy * ( (w0(num,k )-w0(nm,k))/guv(nm) & & + (v0(nm ,ku)-v0(nm,k))/dzv ) else ryz(nm,k) = 0.0_fp endif enddo endif enddo enddo ! ! Horizontal advection: u dw/dx + v dw/dy ! if (momsol == 'mdue' .or. momsol == 'flood') then ! ! Multi-directional upwind explicit horizontal advection ! call z_vermom_horadv_mdue(kmax , icx , icy , icxy , kcs , & & kfs , guu , guv , gvu , u0 , & & v0 , kfsmin, kfsmx0 , kfuz0 , kfsz0 , & & kfvz0 , w0 , ddk , gdp) ! elseif (momsol == 'iupw' .or. momsol == 'mdui') then ! ! First order implicit horizontal advection ! call z_vermom_horadv_iupw(kmax , icx , icy , icxy , kcs , & & kfs , guu , guv , gvu , u0 , & & v0 , kfsmin, kfsmx0 , kfuz0 , kfsz0 , & & kfvz0 , w0 , bbk , ddk , bdx , & & bux , bdy , buy , gdp) ! endif ! ! Vertical advection and diffusion ! do m = m1_nhy, m2_nhy nmst = nmstart + (m - m1_nhy)*icxy do nm = nmst, nmst + ndelta if (kfs(nm)*kcs(nm) == 1) then nmd = nm - icx ndm = nm - icy ndmd = nm - icx - icy nmu = nm + icx num = nm + icy numu = nm + icx + icy ndmu = nm + icx - icy numd = nm - icx + icy gksi = gvu(nm) geta = guu(nm) ! ! Loop over internal layers ! do k = kfsmin(nm), kfsmx0(nm)-1 ku = k + 1 kd = k - 1 ! ! Vertical advection ! dz = 0.5_fp * (zk(ku)-zk(kd)) kfad = 0 if (k == kfsmin(nm)) then kfad = 1 endif dzup = zk(ku)-zk(k ) dzdo = zk(k )-zk(kd) if (kfs(nm)*kcs(nm) == 1) then www = w0(nm,k) if (www < 0.0_fp) then adza = -www / (dzup+dzdo) * real(1-abs(kfad),fp) adzc = www / (dzup+dzdo) * real(1-abs(kfad),fp) & & + kfad*(1+kfad)*www/(2.0_fp*dzup) else adza = -www / (dzup+dzdo) * real(1-abs(kfad),fp) & & + abs(kfad)*(-1+kfad)*www/(2.0_fp*dzdo) adzc = www / (dzup+dzdo) * real(1-abs(kfad),fp) endif endif aak(nm,k) = adza bbk(nm,k) = bbk(nm,k) + 1.0_fp/dt - adza - adzc cck(nm,k) = adzc ! ! Vertical viscosity (rzz) ! viskup = 0.5_fp * (2.0_fp*vicmol + vicww(nm, k) + vicww(nm, ku)) visk = 0.5_fp * (2.0_fp*vicmol + vicww(nm, k) + vicww(nm, kd)) dzup = zk(ku) - zk(k ) dzdo = zk(k ) - zk(kd) dz = 0.5_fp * (dzup+dzdo) ddza = visk / (dzdo*dz) ddzc = viskup / (dzup*dz) ddzb = -ddza - ddzc aak(nm,k) = aak(nm,k) - ddza bbk(nm,k) = bbk(nm,k) - ddzb cck(nm,k) = cck(nm,k) - ddzc ! viscow = (rxz(nm,k)-rxz(nmd,k)) / (0.5_fp*(gvv(nm)+gvv(ndm))) & & + (ryz(nm,k)-ryz(ndm,k)) / (0.5_fp*(guu(nm)+gvv(nmd))) ddk(nm, k) = ddk(nm,k) + w0(nm,k)/dt + viscow & & - (p0(nm,ku)-p0(nm,k)) / (dz*rhow) if (k == kfsmin(nm)) then aak(nm,kd) = 0.0_fp bbk(nm,kd) = 1.0_fp cck(nm,kd) = 0.0_fp ddk(nm,kd) = 0.0_fp endif ! ! Eq. for velocity above free surface ! if (k == kfsmx0(nm)-1) then aak(nm,ku) = -1.0_fp bbk(nm,ku) = 1.0_fp cck(nm,ku) = 0.0_fp ddk(nm,ku) = 0.0_fp endif enddo endif enddo enddo ! ! SOLUTION PROCEDURE SYSTEM OF EQUATIONS ! do nm = 1, nmmax if (kfs(nm) /= 0) then mink = kfsmin(nm) cck(nm,mink-1) = cck(nm,mink-1) / bbk(nm,mink-1) bbk(nm,mink-1) = 1.0_fp do k = kfsmin(nm), kfsmx0(nm) bi = 1.0_fp/(bbk(nm, k) - aak(nm, k)*cck(nm, k - 1)) bbk(nm, k) = bi cck(nm, k) = cck(nm, k) * bi enddo endif enddo ! ! Iteration loop ! iter = 0 do nm = 1, nmmax if (kcs(nm)*kfs(nm) == 1) then mink = kfsmin(nm) do k = kfsmin(nm)-1, kfsmx0(nm) w1(nm, k) = w0(nm, k) uvdwk(nm, k) = w0(nm, k) enddo endif enddo ! 333 continue iter = iter + 1 ! ! ITERATIVE SOLUTION METHOD (JACOBI ITERATION) ! IN HORIZONTAL DIRECTION ! itr=0 ! do m = m1_nhy, m2_nhy nmst = nmstart + (m-m1_nhy)*icxy do nm = nmst, nmst+ndelta if (kfsmx0(nm)-kfsmin(nm)>0 .and. kcs(nm)*kfs(nm)==1) then do k = kfsmin(nm), kfsmx0(nm) uvdwk(nm, k) = bdx(nm,k) * w1(nm-icx, k) & & + bdy(nm,k) * w1(nm-icy, k) & & + buy(nm,k) * w1(nm+icy, k) & & + bux(nm,k) * w1(nm+icx, k) uvdwk(nm, k) = ddk(nm,k) - uvdwk(nm, k) enddo endif enddo enddo ! ! SOLUTION PROCEDURE SYSTEM OF EQUATIONS ! do m = m1_nhy, m2_nhy nmst = nmstart + (m-m1_nhy)*icxy do nm = nmst, nmst+ndelta if (kfsmx0(nm)-kfsmin(nm)>0 .and. kcs(nm)==1) then mink = kfsmin(nm) - 1 vvdwk(nm,mink) = uvdwk(nm,mink) * bbk(nm, mink) endif enddo enddo ! ! Forward sweep ! do m = m1_nhy, m2_nhy nmst = nmstart + (m-m1_nhy)*icxy do nm = nmst, nmst+ndelta if (kfs(nm)*kcs(nm) == 1) then do k = kfsmin(nm), kfsmx0(nm) vvdwk(nm,k) = (uvdwk(nm,k)-aak(nm,k)*vvdwk(nm,k-1)) * bbk(nm,k) enddo endif enddo enddo ! ! Backward sweep ! do m = m1_nhy, m2_nhy nmst = nmstart + (m-m1_nhy)*icxy do nm = nmst, nmst+ndelta if (kfs(nm)*kcs(nm) == 1) then do k = kfsmx0(nm)-1, kfsmin(nm)-1,-1 vvdwk(nm,k) = (vvdwk(nm,k)-cck(nm,k)*vvdwk(nm,k+1)) enddo endif enddo enddo ! ! CHECK FOR CONVERGENCE ! do nm = 1, nmmax if (kcs(nm)*kfs(nm) == 1) then do k = kfsmin(nm)-1, kfsmx0(nm) if (abs(vvdwk(nm, k) - w1(nm, k)) > eps) then itr = 1 endif w1(nm, k) = vvdwk(nm, k) enddo endif enddo ! if (itr>0 .and. iter<50) goto 333 ! if (iter >= 50) then write (errtxt, '(a,i0)') '*** WARNING No convergence in Z_VERMOM_NHFULL for tstep: #', nst call prterr(lundia ,'U190' ,errtxt ) endif ! end subroutine z_vermom_nhfull
[STATEMENT] lemma restrict_fun: "\<lbrakk> f \<in> A \<rightarrow> B; A1 \<subseteq> A \<rbrakk> \<Longrightarrow> restrict f A1 \<in> A1 \<rightarrow> B" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>f \<in> A \<rightarrow> B; A1 \<subseteq> A\<rbrakk> \<Longrightarrow> restrict f A1 \<in> A1 \<rightarrow> B [PROOF STEP] apply (simp add:Pi_def restrict_def) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>\<forall>x. x \<in> A \<longrightarrow> f x \<in> B; A1 \<subseteq> A\<rbrakk> \<Longrightarrow> \<forall>x. x \<in> A1 \<longrightarrow> f x \<in> B [PROOF STEP] apply (rule allI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. \<lbrakk>\<forall>x. x \<in> A \<longrightarrow> f x \<in> B; A1 \<subseteq> A\<rbrakk> \<Longrightarrow> x \<in> A1 \<longrightarrow> f x \<in> B [PROOF STEP] apply (rule impI) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. \<lbrakk>\<forall>x. x \<in> A \<longrightarrow> f x \<in> B; A1 \<subseteq> A; x \<in> A1\<rbrakk> \<Longrightarrow> f x \<in> B [PROOF STEP] apply (simp add:subsetD) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
Formal statement is: lemma lipschitz_on_cmult_real_upper [lipschitz_intros]: fixes f::"'a::metric_space \<Rightarrow> real" assumes "C-lipschitz_on U f" "abs(a) \<le> D" shows "(D * C)-lipschitz_on U (\<lambda>x. a * f x)" Informal statement is: If $f$ is $C$-Lipschitz on $U$, then $a f$ is $(D C)$-Lipschitz on $U$, where $|a| \leq D$.
<a href="https://colab.research.google.com/github/WebheadTech/QCourse511-1/blob/main/qua.ipynb" target="_parent"></a> ```python pip install tensorflow==2.4.1 tensorflow-quantum ``` ```python # Update package resources to account for version changes. import importlib, pkg_resources importlib.reload(pkg_resources) ``` <module 'pkg_resources' from '/usr/local/lib/python3.7/dist-packages/pkg_resources/__init__.py'> ```python ``` ```python ``` ```python ``` ```python from google.colab import drive drive.mount('/content/drive') ``` Mounted at /content/drive ```python import sys sys.path.append('/content/drive/My Drive') ``` ```python import eecs598 import torch import torchvision import matplotlib.pyplot as plt import statistics import numpy as np ``` ```python import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np import seaborn as sns import collections # visualization tools %matplotlib inline import matplotlib.pyplot as plt from cirq.contrib.svg import SVGCircuit ``` ```python # Control qrid size for visualization plt.rcParams['figure.figsize'] = (10.0, 8.0) plt.rcParams['font.size'] = 16 ``` ```python x_train, y_train, x_test, y_test = eecs598.data.cifar10() print('Training set:', ) print(' data shape:', x_train.shape) print(' labels shape: ', y_train.shape) print('Test set:') print(' data shape: ', x_test.shape) print(' labels shape', y_test.shape) ``` Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./cifar-10-python.tar.gz 0%| | 0/170498071 [00:00<?, ?it/s] Extracting ./cifar-10-python.tar.gz to . Training set: data shape: torch.Size([50000, 3, 32, 32]) labels shape: torch.Size([50000]) Test set: data shape: torch.Size([10000, 3, 32, 32]) labels shape torch.Size([10000]) ```python import random from torchvision.utils import make_grid classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] samples_per_class = 12 samples = [] for y, cls in enumerate(classes): plt.text(-4, 34 * y + 18, cls, ha='right') idxs, = (y_train == y).nonzero(as_tuple=True) for i in range(samples_per_class): idx = idxs[random.randrange(idxs.shape[0])].item() samples.append(x_train[idx]) img = torchvision.utils.make_grid(samples, nrow=samples_per_class) plt.imshow(eecs598.tensor_to_image(img)) plt.axis('off') plt.show() ``` ```python ``` ```python from tensorflow.keras.datasets import cifar10 (train_images, train_labels), (test_images, test_labels) = cifar10.load_data() ``` Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 170500096/170498071 [==============================] - 6s 0us/step ```python y_train=train_labels.flatten() y_test=test_labels.flatten() # We have reduced the dimension ``` ```python x_train=tf.image.rgb_to_grayscale(train_images) x_test=tf.image.rgb_to_grayscale(test_images) #to convert grayscale ``` ```python def filter_36(x, y): keep = (y == 3) | (y == 6) x, y = x[keep], y[keep] y = y == 3 return x,y ``` ```python x_train, y_train = filter_36(x_train, y_train) x_test, y_test = filter_36(x_test, y_test) print("Number of filtered training examples:", len(x_train)) print("Number of filtered test examples:", len(x_test)) ``` Number of filtered training examples: 10000 Number of filtered test examples: 2000 ```python plt.imshow(x_train[0, :, :, 0]) plt.colorbar() ``` ```python x_train_s = tf.image.resize(x_train, (4,4)).numpy() x_test_s = tf.image.resize(x_test, (4,4)).numpy() ``` ```python THRESHOLD = 0.5 x_train_bin = np.array(x_train_s > THRESHOLD, dtype=np.float32) x_test_bin = np.array(x_test_s > THRESHOLD, dtype=np.float32) ``` ```python qubits = cirq.GridQubit.rect(4, 4) ``` ```python xx=cirq.Y(qubits[1]) ``` ```python cirq.X(qubits[1]) cirq.Y(qubits[1]) cirq.Z ``` Y((0, 1)) ```python np.random.uniform(size=(4, 3)) ``` array([[0.7967969 , 0.30777665, 0.44788952], [0.18320573, 0.26701107, 0.49590493], [0.05564715, 0.00566145, 0.81495824], [0.77629675, 0.28633108, 0.49930407]]) ```python cirq.Circuit(cirq.X(qubits[1]), cirq.Y(qubits[1])) ``` <pre style="overflow: auto; white-space: pre;">(0, 1): ───X───Y───</pre> ```python ``` ```python def convert_to_circuit(image): """Encode truncated classical image into quantum datapoint.""" values = np.ndarray.flatten(image) qubits = cirq.GridQubit.rect(6, 6) circuit = cirq.Circuit() for i, value in enumerate(values): if value: cirq.X(qubits[i]) circuit.append((cirq.X(qubits[i]), cirq.Y(qubits[i]), cirq.Z(qubits[i]) )) return circuit x_train_circ = [convert_to_circuit(x) for x in x_train_bin] x_test_circ = [convert_to_circuit(x) for x in x_test_bin] ``` ```python SVGCircuit(x_train_circ[0]) ``` findfont: Font family ['Arial'] not found. Falling back to DejaVu Sans. ```python x_train_tfcirc = tfq.convert_to_tensor(x_train_circ) x_test_tfcirc = tfq.convert_to_tensor(x_test_circ) ``` ```python class CircuitLayerBuilder(): def __init__(self, data_qubits, readout): self.data_qubits = data_qubits self.readout = readout def add_layer(self, circuit, gate, prefix): for i, qubit in enumerate(self.data_qubits): symbol = sympy.Symbol(prefix + '-' + str(i)) circuit.append(gate(qubit, self.readout)**symbol) ``` ```python demo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1), readout=cirq.GridQubit(-1,-1)) circuit = cirq.Circuit() demo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx') SVGCircuit(circuit) ``` ```python def create_quantum_model(): """Create a QNN model circuit and readout operation to go along with it.""" data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid. readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1] circuit = cirq.Circuit() # Prepare the readout qubit. circuit.append(cirq.X(readout)) circuit.append(cirq.H(readout)) builder = CircuitLayerBuilder( data_qubits = data_qubits, readout=readout) # Then add layers (experiment by adding more). builder.add_layer(circuit, cirq.XX, "xx1") builder.add_layer(circuit, cirq.ZZ, "zz1") # Finally, prepare the readout qubit. circuit.append(cirq.H(readout)) return circuit, cirq.Z(readout) ``` ```python model_circuit, model_readout = create_quantum_model() ``` ```python model = tf.keras.Sequential([ # The input is the data-circuit, encoded as a tf.string tf.keras.layers.Input(shape=(), dtype=tf.string), # The PQC layer returns the expected value of the readout gate, range [-1,1]. tfq.layers.PQC(model_circuit, model_readout), ]) ``` ```python y_train_hinge = 2.0*y_train-1.0 y_test_hinge = 2.0*y_test-1.0 ``` ```python def hinge_accuracy(y_true, y_pred): y_true = tf.squeeze(y_true) > 0.0 y_pred = tf.squeeze(y_pred) > 0.0 result = tf.cast(y_true == y_pred, tf.float32) return tf.reduce_mean(result) ``` ```python model.compile( loss=tf.keras.losses.Hinge(), optimizer=tf.keras.optimizers.Adam(), metrics=[hinge_accuracy]) ``` ```python print(model.summary()) ``` Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= pqc (PQC) (None, 1) 32 ================================================================= Total params: 32 Trainable params: 32 Non-trainable params: 0 _________________________________________________________________ None ```python EPOCHS = 3 BATCH_SIZE = 128 NUM_EXAMPLES = len(x_train_tfcirc) ``` ```python x_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES] y_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES] ``` ```python import time start_time = time.time() ``` ```python qnn_history = model.fit( x_train_tfcirc_sub, y_train_hinge_sub, batch_size=32, epochs=EPOCHS, verbose=1, validation_data=(x_test_tfcirc, y_test_hinge)) qnn_results = model.evaluate(x_test_tfcirc, y_test) ``` Epoch 1/3 12/313 [>.............................] - ETA: 3:09:25 - loss: 1.0009 - hinge_accuracy: 0.5213
(* Title: HOL/Auth/n_germanSymIndex_lemma_on_inv__50.thy Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences *) header{*The n_germanSymIndex Protocol Case Study*} theory n_germanSymIndex_lemma_on_inv__50 imports n_germanSymIndex_base begin section{*All lemmas on causal relation between inv__50 and some rule r*} lemma n_RecvReqSVsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqS N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''CurCmd'')) (Const Empty)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const Inv))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvReqEVsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvReqE N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__0Vsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__0 i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInv__part__1Vsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__1 i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P3 s" apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (eqn (IVar (Para (Ident ''InvSet'') p__Inv2)) (Const true)) (eqn (IVar (Ident ''ExGntd'')) (Const true))) (eqn (IVar (Para (Ident ''InvSet'') p__Inv0)) (Const true))))" in exI, auto) done then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendInvAckVsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntSVsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendGntEVsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntSVsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntS i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_RecvGntEVsinv__50: assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s") proof - from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntE i" apply fastforce done from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2" apply fastforce done have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done moreover { assume b1: "(i=p__Inv2)" have "?P1 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i=p__Inv0)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } moreover { assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)" have "?P2 s" proof(cut_tac a1 a2 b1, auto) qed then have "invHoldForRule s f r (invariants N)" by auto } ultimately show "invHoldForRule s f r (invariants N)" by satx qed lemma n_SendReqE__part__1Vsinv__50: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_StoreVsinv__50: assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_RecvInvAckVsinv__50: assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvInvAck i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqE__part__0Vsinv__50: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done lemma n_SendReqSVsinv__50: assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__50 p__Inv0 p__Inv2)" shows "invHoldForRule s f r (invariants N)" apply (rule noEffectOnRule, cut_tac a1 a2, auto) done end
% Options for packages loaded elsewhere \PassOptionsToPackage{unicode}{hyperref} \PassOptionsToPackage{hyphens}{url} % \documentclass[ ]{book} \usepackage{lmodern} \usepackage{amssymb,amsmath} \usepackage{ifxetex,ifluatex} \ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{textcomp} % provide euro and other symbols \else % if luatex or xetex \usepackage{unicode-math} \defaultfontfeatures{Scale=MatchLowercase} \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1} \fi % Use upquote if available, for straight quotes in verbatim environments \IfFileExists{upquote.sty}{\usepackage{upquote}}{} \IfFileExists{microtype.sty}{% use microtype if available \usepackage[]{microtype} \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts }{} \makeatletter \@ifundefined{KOMAClassName}{% if non-KOMA class \IfFileExists{parskip.sty}{% \usepackage{parskip} }{% else \setlength{\parindent}{0pt} \setlength{\parskip}{6pt plus 2pt minus 1pt}} }{% if KOMA class \KOMAoptions{parskip=half}} \makeatother \usepackage{xcolor} \IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available \IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}} \hypersetup{ pdftitle={A Minimal Book Example}, pdfauthor={Yihui Xie}, hidelinks, pdfcreator={LaTeX via pandoc}} \urlstyle{same} % disable monospaced font for URLs \usepackage{color} \usepackage{fancyvrb} \newcommand{\VerbBar}{|} \newcommand{\VERB}{\Verb[commandchars=\\\{\}]} \DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}} % Add ',fontsize=\small' for more characters per line \usepackage{framed} \definecolor{shadecolor}{RGB}{248,248,248} \newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}} \newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}} \newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}} \newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}} \newcommand{\BuiltInTok}[1]{#1} \newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}} \newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}} \newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}} \newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}} \newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}} \newcommand{\ExtensionTok}[1]{#1} \newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}} \newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\ImportTok}[1]{#1} \newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}} \newcommand{\NormalTok}[1]{#1} \newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}} \newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}} \newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}} \newcommand{\RegionMarkerTok}[1]{#1} \newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}} \newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}} \newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}} \usepackage{longtable,booktabs} % Correct order of tables after \paragraph or \subparagraph \usepackage{etoolbox} \makeatletter \patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{} \makeatother % Allow footnotes in longtable head/foot \IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}} \makesavenoteenv{longtable} \usepackage{graphicx,grffile} \makeatletter \def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi} \def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi} \makeatother % Scale images if necessary, so that they will not overflow the page % margins by default, and it is still possible to overwrite the defaults % using explicit options in \includegraphics[width, height, ...]{} \setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio} % Set default figure placement to htbp \makeatletter \def\fps@figure{htbp} \makeatother \setlength{\emergencystretch}{3em} % prevent overfull lines \providecommand{\tightlist}{% \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}} \setcounter{secnumdepth}{5} \usepackage{booktabs} \usepackage{amsthm} \makeatletter \def\thm@space@setup{% \thm@preskip=8pt plus 2pt minus 4pt \thm@postskip=\thm@preskip } \makeatother \usepackage[]{natbib} \bibliographystyle{apalike} \title{A Minimal Book Example} \author{Yihui Xie} \date{2021-02-17} \begin{document} \maketitle { \setcounter{tocdepth}{1} \tableofcontents } \hypertarget{prerequisites}{% \chapter{Prerequisites}\label{prerequisites}} This is a \emph{sample} book written in \textbf{Markdown}. You can use anything that Pandoc's Markdown supports, e.g., a math equation \(a^2 + b^2 = c^2\). The \textbf{bookdown} package can be installed from CRAN or Github: \begin{Shaded} \begin{Highlighting}[] \KeywordTok{install.packages}\NormalTok{(}\StringTok{"bookdown"}\NormalTok{)} \CommentTok{# or the development version} \CommentTok{# devtools::install_github("rstudio/bookdown")} \end{Highlighting} \end{Shaded} Remember each Rmd file contains one and only one chapter, and a chapter is defined by the first-level heading \texttt{\#}. To compile this example to PDF, you need XeLaTeX. You are recommended to install TinyTeX (which includes XeLaTeX): \url{https://yihui.name/tinytex/}. \hypertarget{sysadmins}{% \chapter{System Administrators}\label{sysadmins}} \hypertarget{server-software}{% \section{Server Software}\label{server-software}} \begin{itemize} \tightlist \item \url{https://github.com/mhk-env/mhk-env_server-software} \end{itemize} Symbolically link (\texttt{ln\ -s}) a Shiny server app from within the Github repo (\texttt{mhk-env\_shiny-apps}) to the active folder \texttt{/srv/shiny-server} from where Shiny apps get served: \begin{verbatim} ln -s /share/github/mhk-env_shiny-apps/report-gen2 /srv/shiny-server/report \end{verbatim} \hypertarget{old-bookdown}{% \section{OLD (bookdown)}\label{old-bookdown}} This website describes how to use open-source software and data to construct the \href{https://MarineEnergy.app}{MarineEnergy.app} Toolkit for Enviromental Compliance, organized for now by audience. \hypertarget{rtech}{% \chapter{R Technicians}\label{rtech}} \hypertarget{updating-dynamic-content}{% \section{Updating dynamic content}\label{updating-dynamic-content}} \begin{itemize} \item \end{itemize} \hypertarget{comm}{% \chapter{Community Members}\label{comm}} \hypertarget{edit-in-openei}{% \section{Edit in OpenEI}\label{edit-in-openei}} \begin{itemize} \tightlist \item \href{https://marineenergy.app/regs.html}{Regulations} \begin{itemize} \tightlist \item \href{https://openei.org/wiki/MarineEnergyApp}{MarineEnergyApp \textbar{} OpenEI} \end{itemize} \end{itemize} \hypertarget{suggest-in-google-sheets}{% \section{Suggest in Google Sheets}\label{suggest-in-google-sheets}} \begin{itemize} \item Suggest and then get reviewed by R-technicians for updating. \item \href{https://marineenergy.app/projects.html}{Projects} \begin{itemize} \tightlist \item \href{https://docs.google.com/spreadsheets/d/1HC5hXyi2RQSHevnV7rvyk748U5-X3iUw70ewHEfrHm0/edit\#gid=793817660}{projects} \end{itemize} \item \href{https://marineenergy.app/ferc.html}{Documents} \begin{itemize} \tightlist \item \href{https://docs.google.com/spreadsheets/d/1c9pFSkQyQvLFpyMT4KlBoSFA_wtJ_iNj8YmNX_RZmXc/edit\#gid=951079264}{documents} \end{itemize} \item \href{https://shiny.marineenergy.app/report/?nav=Spatial}{Spatial} \begin{itemize} \tightlist \item \href{https://docs.google.com/spreadsheets/d/1MMVqPr39R5gAyZdY2iJIkkIdYqgEBJYQeGqDk1z-RKQ/edit\#gid=936111013}{spatial} \end{itemize} \end{itemize} \hypertarget{applications}{% \chapter{Applications}\label{applications}} Some \emph{significant} applications are demonstrated in this chapter. \hypertarget{example-one}{% \section{Example one}\label{example-one}} \hypertarget{example-two}{% \section{Example two}\label{example-two}} \hypertarget{final-words}{% \chapter{Final Words}\label{final-words}} We have finished a nice book. \bibliography{book.bib,packages.bib} \end{document}
module PPM %default total record Color : Type where C : (red, green, blue : Bits8) -> Color data PPM : Nat -> Nat -> Type where MkPPM: (x, y: Nat) -> (image : Vect x (Vect y Color)) -> PPM x y data VectZipper : Nat -> Nat -> Type -> Type where VZ : (left : Vect n a) -> (right : Vect m a) -> VectZipper n m a toVect : VectZipper n m a -> Vect (n + m) a toVect (VZ l r) = reverse l ++ r goLeft : VectZipper (S n) m a -> VectZipper n (S m) a goLeft (VZ (x :: l) r) = VZ l (x :: r) goRight : VectZipper n (S m) a -> VectZipper (S n) m a goRight (VZ l (x :: r)) = VZ (x :: l) r zipper : Vect n a -> VectZipper 0 n a zipper v = VZ [] v instance Cast Bits8 Int where cast = prim__zextB8_Int toString : PPM n m -> String toString (MkPPM x y image) = header ++ concatMap {t=Vect x} row image where header : String header = concat (the (List String) [ "P3\n" , show x, " " , show y, "\n" ]) component : Bits8 -> String component b = show (cast {to=Int} b) pixel : Color -> String pixel (C r g b) = component r ++ " " ++ component g ++ " " ++ component b ++ "\n" row : Vect n Color -> String row = concatMap pixel
function [str] = strengths_und(CIJ) %STRENGTHS_UND Strength % % str = strengths_und(CIJ); % % Node strength is the sum of weights of links connected to the node. % % Input: CIJ, undirected weighted connection matrix % % Output: str, node strength % % % Olaf Sporns, Indiana University, 2002/2006/2008 % compute strengths str = sum(CIJ); % strength
Set Implicit Arguments. Require Export Lia. Require Export ArithRing. Require Export Coq.Numbers.Natural.Peano.NPeano. (* [Nat] is a sub-module of [NPeano], which seems to contain many things. E.g. it defines [Nat.div], [Nat.pow], [Nat.log2]. E.g. it defines [Nat.max], which is the same as [max]. E.g. it has many properties of [max], see [Coq.Structures.GenericMinMax]. Unfortunately [Nat.le] is NOT the same as [le], which is [Peano.le]. For this reason, we do NOT import [Nat]. *) Notation log2 := Nat.log2. From TLC Require Import LibTactics. Ltac unpack := jauto_set_hyps; intros. (* TEMPORARY also in TLCBuffer *) From iris_time.union_find.math Require Import LibFunOrd. (* ---------------------------------------------------------------------------- *) (* A few simplification lemmas. *) Lemma plus_lt_plus: forall a x y, x < y -> x + a < y + a. Proof using. intros. lia. Qed. Lemma plus_le_plus: forall a x y, x <= y -> x + a <= y + a. Proof using. intros. lia. Qed. (* ---------------------------------------------------------------------------- *) (* [a <= b] is equivalent to [b = a + n] for some unknown [n]. *) Lemma leq_to_eq_plus: forall a b, a <= b -> exists n, b = a + n. Proof. intros. exists (b - a). lia. Qed. (* ---------------------------------------------------------------------------- *) (* Make [lia] a hint. *) Hint Extern 1 => lia : lia. (* ---------------------------------------------------------------------------- *) (* This lemma allows simplifying a [max] expression, by cases. *) Lemma max_case: forall m1 m2, m2 <= m1 /\ max m1 m2 = m1 \/ m1 <= m2 /\ max m1 m2 = m2. Proof using. lia. Qed. (* This tactic looks for a [max] expression in the hypotheses or in the goal and applies the above lemma. *) Ltac max_case_m_n_as m n h := let i := fresh in destruct (max_case m n) as [ [ h i ] | [ h i ] ]; rewrite i in *; clear i. Ltac max_case_as h := match goal with | |- context[max ?m ?n] => max_case_m_n_as m n h | foo: context[max ?m ?n] |- _ => max_case_m_n_as m n h end. Ltac max_case := let h := fresh in max_case_as h. (* [max m1 m2] is an upper bound for [m1] and [m2]. This can be sufficient to reason about [max] without introducing a case split. *) Lemma max_ub: forall m1 m2, m1 <= max m1 m2 /\ m2 <= max m1 m2. Proof using. intros. eauto using Nat.le_max_l, Nat.le_max_r. Qed. Ltac max_ub_m_n_as m n h1 h2 := destruct (max_ub m n) as [ h1 h2 ]; generalize dependent (max m n); intros. Ltac max_ub_as h1 h2 := match goal with | |- context[max ?m ?n] => max_ub_m_n_as m n h1 h2 | foo: context[max ?m ?n] |- _ => max_ub_m_n_as m n h1 h2 end. Ltac max_ub := let h1 := fresh in let h2 := fresh in max_ub_as h1 h2. (* ---------------------------------------------------------------------------- *) (* Properties of multiplication. *) Lemma mult_positive: forall m n, 0 < m -> 0 < n -> 0 < m * n. Proof using. lia. Qed. Hint Resolve mult_positive : positive. Lemma mult_magnifies_left: forall m n, 0 < n -> m <= n * m. Proof using. intros. destruct n; [ lia | simpl ]. generalize (n * m); intro. lia. Qed. Lemma mult_magnifies_right: forall m n, 0 < n -> m <= m * n. Proof using. nia. Qed. Lemma mult_magnifies_right_strict: forall m n, 0 < m -> 1 < n -> m < m * n. Proof using. nia. Qed. (* ---------------------------------------------------------------------------- *) (* Properties of division. *) (* It is strange that the Coq standard library offers [divmod_spec], but lacks its corollary [div_spec]. *) Lemma div_spec: forall n k, 0 < k -> exists r, k * (n / k) + r = n /\ 0 <= r < k. Proof using. intros. unfold Nat.div. destruct k; [ false; lia | simpl ]. forwards: Nat.divmod_spec n k 0 k. eauto. destruct (Nat.divmod n k 0 k) as [ q r ]. unpack. simpl. exists (k - r). lia. Qed. (* Avoid undesired simplifications. *) (* TEMPORARY [plus] should be opaque too? *) Global Opaque mult Nat.div max. (* A tactic to reason about [n/2] in terms of its specification. *) Ltac div2 := match goal with |- context[?n/2] => let h := fresh in forwards h: div_spec n 2; [ lia | gen h; generalize (n/2); intros; unpack ] end. (* [./2] is monotonic. *) Lemma div2_monotonic: forall m n, m <= n -> m / 2 <= n / 2. Proof using. intros. repeat div2. lia. Qed. Lemma div2_step: forall n, (n + 2) / 2 = n/2 + 1. Proof using. intros. repeat div2. lia. Qed. Lemma div2_monotonic_strict: forall m n, m + 2 <= n -> m / 2 < n / 2. Proof using. intros. cut (m/2 + 1 <= n/2). lia. rewrite <- div2_step. eauto using div2_monotonic. Qed. Lemma mult_div_2: forall n, 2 * (n / 2) <= n. Proof using. intros. div2. lia. Qed. Lemma div_mult_2: forall n, (2 * n) / 2 = n. Proof using. intros. div2. lia. Qed. (* A collection of lemmas about division by two and ordering. *) Lemma prove_div2_le: forall m n, m <= 2 * n + 1 -> (* tight *) m / 2 <= n. Proof using. intros. div2. lia. Qed. Lemma use_div2_plus1_le: forall m n, (n + 1) / 2 <= m -> (* tight *) n <= 2 * m. Proof using. intros m n. div2. lia. Qed. Lemma use_div2_le: forall m n, n / 2 <= m -> (* tight *) n <= 2 * m + 1. Proof using. intros m n. div2. lia. Qed. Lemma prove_le_div2: forall m n, 2 * m <= n -> (* tight *) m <= n / 2. Proof using. intros. div2. lia. Qed. Lemma use_le_div2: forall m n, n <= m / 2 -> (* tight *) 2 * n <= m. Proof using. intros m n. div2. lia. Qed. Lemma prove_div2_lt: forall m n, m < 2 * n -> (* tight *) m / 2 < n. Proof using. intros. div2. lia. Qed. Lemma use_div2_lt: forall m n, m / 2 < n -> (* tight *) m < 2 * n. Proof using. intros m n. div2. lia. Qed. Lemma prove_lt_div2: forall m n, 2 * m < n - 1 -> (* tight *) m < n / 2. Proof using. intros. div2. lia. Qed. Lemma prove_lt_div2_zero: forall n, 1 < n -> (* tight *) 0 < n / 2. Proof using. intros. div2. lia. Qed. Lemma use_lt_div2: forall m n, m < (n + 1) / 2 -> (* tight *) 2 * m < n. Proof using. intros m n. div2. lia. Qed. Hint Resolve prove_lt_div2_zero : positive. Hint Resolve prove_div2_le use_div2_plus1_le use_div2_le prove_le_div2 use_le_div2 prove_div2_lt use_div2_lt prove_lt_div2 use_lt_div2 : div2. Goal forall n, n <= 2 * (n / 2) + 1. Proof using. eauto with div2. Qed. (* ---------------------------------------------------------------------------- *) (* The [pow] function. *) Lemma power_positive: forall k n, 0 < n -> 0 < n^k. Proof using. induction k; simpl; intros. lia. eauto using mult_positive. Qed. Hint Resolve power_positive : positive. Lemma power_plus: forall k1 k2 n, n^(k1 + k2) = n^k1 * n^k2. Proof using. induction k1; simpl; intros. lia. rewrite IHk1. ring. Qed. Lemma power_of_zero: forall k, 0 < k -> 0^k = 0. Proof using. induction k; simpl; intros; lia. Qed. Lemma power_monotonic_in_k: (* We must assume [n > 0], because [0^0] is 1, yet [0^1] is 0. *) forall n, 0 < n -> monotonic le le (fun k => n^k). Proof using. intros. intros k1 k2 ?. assert (f: k2 = k1 + (k2 - k1)). lia. rewrite f. rewrite power_plus. eapply mult_magnifies_right. eapply power_positive. assumption. Qed. Lemma power_strictly_monotonic_in_k: forall n, 1 < n -> monotonic lt lt (fun k => n^k). Proof using. intros. intros k1 k2 ?. assert (f: k2 = k1 + S (k2 - k1 - 1)). lia. rewrite f. rewrite power_plus. eapply mult_magnifies_right_strict. { eauto with positive lia. } { simpl. eapply Nat.lt_le_trans with (m := n). lia. eapply mult_magnifies_right. eauto with positive lia. } Qed. Lemma power_strictly_monotonic_in_n: forall k, 0 < k -> monotonic lt lt (fun n => n^k). Proof using. (* We first prove that this holds when [n1] is nonzero, and reformulate the hypothesis [k > 0] so that it is amenable to induction. *) assert (f: forall k n1 n2, 0 < n1 < n2 -> n1^(S k) < n2^(S k) ). { induction k; simpl; intros. lia. eapply Nat.lt_le_trans; [ eapply Mult.mult_lt_compat_r | eapply Mult.mult_le_compat_l ]. (* wow *) lia. eapply power_positive with (k := S k). lia. forwards: IHk. eauto. simpl in *. lia. } (* There remains to treat separately the case where [n1] is 0. *) intros. intros n1 n2 ?. destruct (Compare_dec.le_gt_dec n1 0). { assert (n1 = 0). lia. subst. rewrite power_of_zero by assumption. eapply power_positive. lia. } { destruct k; [ lia | ]. eapply f. lia. } (* ouf *) Qed. Hint Resolve power_monotonic_in_k power_strictly_monotonic_in_k power_strictly_monotonic_in_n : monotonic typeclass_instances. Lemma power_monotonic_in_n: forall k, monotonic le le (fun n => n^k). Proof using. intros. destruct k. { subst. simpl. repeat intro. lia. } { eauto with monotonic lia. } Qed. Hint Resolve power_monotonic_in_n : monotonic typeclass_instances. (* TEMPORARY maybe explicitly use [inverse_monotonic] in lemmas below *) Lemma power_inverse_monotonic_in_k: forall n, 1 < n -> forall k1 k2, n^k1 <= n^k2 -> k1 <= k2. Proof using. intros. eapply monotonic_lt_lt_implies_inverse_monotonic_le_le with (f := fun k => n^k); eauto using power_strictly_monotonic_in_k. Qed. Lemma power_strictly_inverse_monotonic_in_k: forall n k1 k2, 0 < n -> n^k1 < n^k2 -> k1 < k2. Proof using. intros. eapply monotonic_le_le_implies_inverse_monotonic_lt_lt with (f := fun k => n^k); eauto using power_monotonic_in_k. Qed. Lemma power_strictly_inverse_monotonic_in_k_variant: forall n k1 k2, 0 < n -> n^k1 < n^(1 + k2) -> k1 <= k2. Proof using. intros. cut (k1 < 1 + k2). { lia. } eauto using power_strictly_inverse_monotonic_in_k. Qed. Lemma power_strictly_inverse_monotonic_in_k_frame: forall n k1 k2, 1 < n -> n^k2 <= n^k1 < n^(1 + k2) -> k1 = k2. Proof using. intros. assert (k2 <= k1). { eapply power_inverse_monotonic_in_k with (n := n); eauto with lia. } assert (k1 < 1 + k2). { eapply power_strictly_inverse_monotonic_in_k with (n := n); eauto with lia. } lia. Qed. Lemma power_inverse_monotonic_in_n: forall k, 0 < k -> forall n1 n2, n1^k <= n2^k -> n1 <= n2. Proof using. intros. eapply monotonic_lt_lt_implies_inverse_monotonic_le_le with (f := fun n => n^k); eauto using power_strictly_monotonic_in_n. Qed. (* A lower bound on [2^n]. *) Lemma n_lt_power: forall n, n < 2^n. Proof using. induction n; simpl; lia. Qed. (* ---------------------------------------------------------------------------- *) (* Base 2 logarithm. *) (* The Coq standard library gives us the following: Lemma log2_spec : forall n, 0<n -> 2^(log2 n) <= n < 2^(S (log2 n)). *) Ltac log2_spec := match goal with |- context[log2 ?n] => let h := fresh in forwards h: Nat.log2_spec n; [ eauto with positive lia | gen h; generalize (log2 n); intros; unpack ] end. (* The above specification is functional, i.e., it defines [log2 n] in a unique manner. *) Lemma log2_uniqueness_half: forall n k1 k2, 2^k1 <= n < 2^(1 + k1) -> 2^k2 <= n < 2^(1 + k2) -> k1 <= k2. Proof using. simpl. intros. unpack. eapply power_strictly_inverse_monotonic_in_k_variant with (n := 2). lia. eauto using Nat.le_lt_trans. Qed. Lemma log2_uniqueness: forall n k1 k2, 2^k1 <= n < 2^(1 + k1) -> 2^k2 <= n < 2^(1 + k2) -> k1 = k2. Proof using. intros. forwards: log2_uniqueness_half n k1 k2; eauto. forwards: log2_uniqueness_half n k2 k1; eauto. lia. Qed. (* When applied to a power of two, [log2] yields the exponent. *) Lemma log2_pow: forall k, log2 (2^k) = k. Proof using. intros k. log2_spec. symmetry. eapply power_strictly_inverse_monotonic_in_k_frame with (n := 2). lia. eauto. Qed. (* This is just a repetition of one half of [log2_spec]. *) Lemma pow_log2: forall n, 0 < n -> 2 ^ (log2 n) <= n. Proof using. intros. eapply Nat.log2_spec. eauto. Qed. Lemma pow_succ_log2: forall n, n < 2^(1 + log2 n). Proof using. intros. destruct n. { subst. simpl. lia. } { eapply Nat.log2_spec. lia. } Qed. (* The inductive step of many arguments that involve divide-and-conquer. *) Lemma log2_step: forall n, 2 <= n -> 1 + log2 (n/2) = log2 n. Proof using. intros. repeat log2_spec. eapply log2_uniqueness; [ | eauto ]. simpl. eauto with div2. Qed. (* [log2] is monotonic. *) Lemma log2_monotonic: monotonic le le log2. Proof using. intros m n ?. (* A special case for [m = 0]. *) destruct m. { subst. unfold log2. simpl. lia. } (* Case [m > 0]. *) do 2 log2_spec. eapply power_strictly_inverse_monotonic_in_k_variant with (n := 2); simpl; lia. Qed. Hint Resolve log2_monotonic : monotonic typeclass_instances. (* A collection of lemmas involving [log2] and ordering. *) Lemma prove_le_log2: forall k n, 2^k <= n -> k <= log2 n. Proof using. intros. forwards: log2_monotonic. eauto. rewrite log2_pow in *. assumption. Qed. Lemma prove_log2_le: forall k n, n <= 2^k -> log2 n <= k. Proof using. intros. forwards: log2_monotonic. eauto. rewrite log2_pow in *. assumption. Qed. Lemma prove_log2_lt: forall k n, 0 < n -> n < 2^k -> log2 n < k. Proof using. intros. eapply monotonic_le_le_implies_inverse_monotonic_lt_lt with (f := fun n => 2^n). { eauto with monotonic. } eauto using Nat.le_lt_trans, pow_log2. Qed. Hint Resolve prove_le_log2 prove_log2_le prove_log2_lt : log2. (* An upper bound on [log2 n]. *) Lemma log2_lt_n: forall n, 0 < n -> log2 n < n. Proof using. eauto using prove_log2_lt, n_lt_power. Qed. (* ---------------------------------------------------------------------------- *) (* The existence of the function [log2] means that the sequence [n], [n/2], [n/4], etc. tends towards zero. We can exploit this by giving the following induction principle. *) Lemma div2_induction: forall (P : nat -> Prop), P 0 -> (forall n, P (n/2) -> P n) -> forall n, P n. Proof using. introv hbase hstep. assert (f: forall k n, log2 n < k -> P n). { induction k; intros. false. lia. (* Special cases for [n = 0] and [n = 1]. *) destruct n as [|n']. { eauto. } destruct n' as [|n'']. eauto. (* In the general case, [2 <= n], we use [log2_step]. *) eapply hstep. eapply IHk. cut (1 + log2 ((S (S n'')) / 2) <= k). { lia. } rewrite log2_step by lia. lia. } intros. eapply f with (k := log2 n + 1). lia. Qed. (* The following variant of the above induction principle allows establishing a property [P] that mentions both [log2 n] and [n]. *) Lemma log2_induction: forall (P : nat -> nat -> Prop), P 0 0 -> P 0 1 -> (forall k n, 2 <= n -> P k (n/2) -> P (1+k) n) -> forall n, P (log2 n) n. Proof using. introv h00 h01 hkn. (* Maybe one could give a direct proof; anyway, we choose to give a proof based on the previous induction principle. *) assert (forall n, 1 <= n -> P (log2 n) n). { eapply (@div2_induction (fun n => 1 <= n -> P (log2 n) n)). (* The base case cannot arise. *) { intro. false. lia. } (* Step. *) { intros n IH ?. (* Special case for [n = 1]. *) destruct (Nat.eq_decidable n 1); [ subst n; exact h01 | ]. (* In the general case, [2 <= n], we use [log2_step]. *) assert (2 <= n). { lia. } rewrite <- log2_step by assumption. eauto with div2. } } intro n. (* Special case for [n = 0]. *) destruct n; [ exact h00 | ]. (* General case. *) eauto with lia. Qed.
If $b$ is a real number and $w$ is an integer, then $b^w$ is a real number if and only if $(b^w)^{\frac{1}{w}}$ is a real number.
import Mathlib.Tactic.Contrapose open Classical -- Section 2.1 The Peano axioms -- Axiom 2.1. 0 is a natural number. -- Axiom 2.2. If n is a natural number, then n++ is also a natural number. inductive nat : Type | zero : nat | succ : nat → nat namespace nat -- Definition 2.1.3. def one : nat := succ nat.zero def two : nat := succ one def three : nat := succ two def four : nat := succ three def five : nat := succ four def six : nat := succ five -- Proposition 2.1.4. 3 is a natural number. #check three -- Axiom 2.3. 0 is not the successor of any natural number; i.e., -- we have n++ ̸= 0 for every natural number n. axiom zero_not_succ : ∀ n : nat, zero ≠ succ n -- Proposition 2.1.6. 4 is not equal to 0. theorem four_not_zero : four ≠ zero := have h1 : succ three = four := rfl have h2 : zero ≠ succ three := zero_not_succ three have h3 : zero ≠ four := h1 ▸ h2 show four ≠ zero from Ne.symm h3 -- Axiom 2.4. Different natural numbers must have -- different successors; i.e., if n, m are natural -- numbers and n ≠ m, then n++ ≠ m++. Equivalently, -- if n++ = m++, then we must have n = m. axiom succ_inj : ∀ n : nat, ∀ m : nat, n ≠ m → succ n ≠ succ m -- Proposition 2.1.8. 6 is not equal to 2. theorem six_not_two : six ≠ two := have h1 : four ≠ zero := four_not_zero have h2 : succ four ≠ succ zero := succ_inj four zero h1 have h3 : succ (succ four) ≠ succ (succ zero) := succ_inj (succ four) (succ zero) h2 show six ≠ two from h3 -- Axiom 2.5 (Principle of mathematical induction). Let -- P(n) be any property pertaining to a natural number n. -- Suppose that P(0) is true, and suppose that whenever -- P(n) is true, P(n++) is also true. Then P(n) is true -- for every natural number n. axiom induction : ∀ P : nat → Prop, P zero → (∀ n : nat, P n → P (succ n)) → ∀ n : nat, P n -- Remark: It appears Axiom 2.5 is unneded for Lean. -- Section 2.2 Addition def add : nat → nat → nat | zero, m => m | succ n, m => succ (add n m) -- Get to use the plus operator instance : Add nat where add := add -- Lemma 2.2.2. For any natural number n, n + 0 = n. theorem add_zero (n : nat) : add n zero = n := by induction n with | zero => rfl | succ n ih => rw [add, ih] -- Lemma 2.2.3. For any natural numbers n and m, -- n + (m++) = (n + m)++. theorem add_succ (n m : nat) : n + (succ m) = succ (n + m) := by induction n with | zero => rfl | succ n ih => have h1 : succ n + succ m = succ (n + succ m) := rfl repeat rw [h1, ih] rfl -- Proposition 2.2.4 (Addition is commutative). For any natural -- numbers n and m, n + m = m + n. theorem add_comm (n m : nat) : n + m = m + n := by induction n with | zero => have h1 : zero + m = m := by rfl have h2 : m + zero = m := by apply add_zero rw [h1, h2] | succ n ih => have h1 : succ n + m = succ (n + m) := by rfl have h2 : m + succ n = succ (m + n) := by apply add_succ rw [h1, ih, h2] -- Proposition 2.2.5 (Addition is associative). For any natural -- numbers a,b,c, we have (a+b)+c=a+(b+c). theorem add_assoc (a b c : nat) : (a + b) + c = a + (b + c) := by induction a with | zero => have h1 : (zero + b) + c = b + c := by rfl have h2 : zero + (b + c) = b + c := by rfl rw [h1, h2] | succ a ih => have h1 : succ a + (b + c) = succ (a + (b + c)) := by rfl have h2 : succ a + b + c = succ ((a + b) + c) := by rfl rw [h2, ih, h1] -- Proposition 2.2.6 (Cancellation law). Let a,b,c be natural -- numbers such that a+b=a+c. Then we have b=c. theorem cancellation_law (a b c : nat) : (a + b) = (a + c) → b = c := by intro h induction a with | zero => have h1 : b = zero + b := by rfl have h2 : c = zero + c := by rfl rw [h1, h2] exact h | succ a ih => have h1 : succ a + b = succ (a + b) := by rfl have h2 : succ a + c = succ (a + c) := by rfl rw [h1,h2] at h apply ih contrapose h apply succ_inj exact h end nat
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.pnat.basic import data.finset.intervals namespace pnat /-- `Ico l u` is the set of positive natural numbers `l ≤ k < u`. -/ def Ico (l u : ℕ+) : finset ℕ+ := (finset.Ico l u).attach.map { to_fun := λ n, ⟨(n : ℕ), lt_of_lt_of_le l.2 (finset.Ico.mem.1 n.2).1⟩, -- why can't we do this directly? inj' := λ n m h, subtype.eq (by { replace h := congr_arg subtype.val h, exact h }) } @[simp] lemma Ico.mem : ∀ {n m l : ℕ+}, l ∈ Ico n m ↔ n ≤ l ∧ l < m := by { rintro ⟨n, hn⟩ ⟨m, hm⟩ ⟨l, hl⟩, simp [pnat.Ico] } @[simp] lemma Ico.card (l u : ℕ+) : (Ico l u).card = u - l := by simp [pnat.Ico] end pnat
If $f$ is analytic on $S$ and $g$ is analytic on $f(S)$, then $g \circ f$ is analytic on $S$.
(* Author: Norbert Schirmer Maintainer: Norbert Schirmer, norbert.schirmer at web de License: LGPL *) (* Title: StateSpace.thy Author: Norbert Schirmer, TU Muenchen Copyright (C) 2004-2008 Norbert Schirmer Some rights reserved, TU Muenchen This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) section \<open>State Space Template\<close> theory StateSpace imports Hoare begin record 'g state = "globals"::'g definition upd_globals:: "('g \<Rightarrow> 'g) \<Rightarrow> ('g,'z) state_scheme \<Rightarrow> ('g,'z) state_scheme" where "upd_globals upd s = s\<lparr>globals := upd (globals s)\<rparr>" record ('g, 'n, 'val) stateSP = "'g state" + locals :: "'n \<Rightarrow> 'val" lemma upd_globals_conv: "upd_globals f = (\<lambda>s. s\<lparr>globals := f (globals s)\<rparr>)" by (rule ext) (simp add: upd_globals_def) end
using JSON using Gadfly include("./detectors/cusum.jl") function run_cusum() jcont = JSON.parsefile("./config.json") sig_dat = JSON.parsefile(jcont["in_art_sig1"]) y = sig_dat["sig"] chps_detected = cusum(y, update_width=10, expected_change=1.0, threshold=0.3) println("True changes :", sig_dat["changes"]) println("Detected changes:", chps_detected) ts = [1:length(y);] println(length(y)) if true l1 = layer(x=ts, y=y, Geom.point) l2 = layer(xintercept=chps_detected, Geom.vline(color="black")) l3 = layer(xintercept=sig_dat["changes"], Geom.vline(color="red")) draw(PNG(jcont["out_art_sig1_fig"], 12inch, 6inch), plot(l1, l2, l3, Guide.title("Read: changes, black: detections."))) println(".. Save PNG into ", jcont["out_art_sig1_fig"]) end end run_cusum()
/****************************************************************************** * Copyright (c) 2017 Thomas Faeulhammer * * 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. * ******************************************************************************/ #include <boost/format.hpp> #include <boost/program_options.hpp> #include <boost/serialization/vector.hpp> #include <glog/logging.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <v4r/apps/ObjectRecognizer.h> #include <v4r/io/filesystem.h> namespace po = boost::program_options; int main (int argc, char ** argv) { typedef pcl::PointXYZRGB PT; bf::path test_dir; bf::path out_dir = "/tmp/object_recognition_results/"; bf::path recognizer_config_dir = "cfg"; int verbosity = -1; po::options_description desc("Object Instance Recognizer\n======================================\n**Allowed options"); desc.add_options() ("help,h", "produce help message") ("test_dir,t", po::value<bf::path>(&test_dir)->required(), "Directory with test scenes stored as point clouds (.pcd). The camera pose is taken directly from the pcd header fields \"sensor_orientation_\" and \"sensor_origin_\" (if the test directory contains subdirectories, each subdirectory is considered as seperate sequence for multiview recognition)") ("out_dir,o", po::value<bf::path>(&out_dir)->default_value(out_dir), "Output directory where recognition results will be stored.") ("cfg", po::value<bf::path>(&recognizer_config_dir)->default_value(recognizer_config_dir), "Path to config directory containing the xml config files for the various recognition pipelines and parameters.") ("verbosity", po::value<int>(&verbosity)->default_value(verbosity), "set verbosity level for output (<0 minimal output)") ; po::variables_map vm; po::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(); std::vector<std::string> to_pass_further = po::collect_unrecognized(parsed.options, po::include_positional); po::store(parsed, vm); if (vm.count("help")) { std::cout << desc << std::endl; to_pass_further.push_back("-h"); } try { po::notify(vm); } catch(std::exception& e) { std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl; } if(verbosity>=0) { FLAGS_logtostderr = 1; FLAGS_v = verbosity; std::cout << "Enabling verbose logging." << std::endl; } google::InitGoogleLogging(argv[0]); v4r::apps::ObjectRecognizer<PT> recognizer; recognizer.initialize(to_pass_further, recognizer_config_dir); std::vector< std::string> sub_folder_names = v4r::io::getFoldersInDirectory( test_dir ); if(sub_folder_names.empty()) sub_folder_names.push_back(""); for (const std::string &sub_folder_name : sub_folder_names) { recognizer.resetMultiView(); std::vector< std::string > views = v4r::io::getFilesInDirectory( test_dir / sub_folder_name, ".*.pcd", false ); for (size_t v_id=0; v_id<views.size(); v_id++) { bf::path test_path = test_dir / sub_folder_name / views[v_id]; LOG(INFO) << "Recognizing file " << test_path.string(); pcl::PointCloud<PT>::Ptr cloud(new pcl::PointCloud<PT>()); pcl::io::loadPCDFile( test_path.string(), *cloud); //reset view point - otherwise this messes up PCL's visualization (this does not affect recognition results) // cloud->sensor_orientation_ = Eigen::Quaternionf::Identity(); // cloud->sensor_origin_ = Eigen::Vector4f::Zero(4); std::vector<v4r::ObjectHypothesesGroup > generated_object_hypotheses = recognizer.recognize(cloud); std::vector<std::pair<std::string, float> > elapsed_time = recognizer.getElapsedTimes(); if ( !out_dir.empty() ) // write results to disk (for each verified hypothesis add a row in the text file with object name, dummy confidence value and object pose in row-major order) { std::string out_basename = views[v_id]; boost::replace_last(out_basename, ".pcd", ".anno"); bf::path out_path = out_dir / sub_folder_name / out_basename; std::string out_path_generated_hypotheses = out_path.string(); boost::replace_last(out_path_generated_hypotheses, ".anno", ".generated_hyps"); std::string out_path_generated_hypotheses_serialized = out_path.string(); boost::replace_last(out_path_generated_hypotheses_serialized, ".anno", ".generated_hyps_serialized"); v4r::io::createDirForFileIfNotExist( out_path ); // save hypotheses std::ofstream f_generated ( out_path_generated_hypotheses.c_str() ); std::ofstream f_verified ( out_path.string().c_str() ); std::ofstream f_generated_serialized ( out_path_generated_hypotheses_serialized.c_str() ); boost::archive::text_oarchive oa(f_generated_serialized); oa << generated_object_hypotheses; f_generated_serialized.close(); for(size_t ohg_id=0; ohg_id<generated_object_hypotheses.size(); ohg_id++) { for(const v4r::ObjectHypothesis::Ptr &oh : generated_object_hypotheses[ohg_id].ohs_) { f_generated << oh->model_id_ << " (" << oh->confidence_ << "): "; const Eigen::Matrix4f tf = oh->pose_refinement_ * oh->transform_; for (size_t row=0; row <4; row++) for(size_t col=0; col<4; col++) f_generated << tf(row, col) << " "; f_generated << std::endl; if( oh->is_verified_ ) { f_verified << oh->model_id_ << " (" << oh->confidence_ << "): "; for (size_t row=0; row <4; row++) for(size_t col=0; col<4; col++) f_verified << tf(row, col) << " "; f_verified << std::endl; } } } f_generated.close(); f_verified.close(); // save elapsed time(s) std::string out_path_times = out_path.string(); boost::replace_last(out_path_times, ".anno", ".times"); f_verified.open( out_path_times.c_str() ); for( const std::pair<std::string,float> &t : elapsed_time) f_verified << t.second << " " << t.first << std::endl; f_verified.close(); } } } }
(* Copyright (C) 2017 M.A.L. Marques This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *) (* type: gga_exc *) $define gga_c_pbe_params $include "gga_c_pbe.mpl" $include "lda_c_2d_amgb.mpl" $undef xc_dimensions_2d rs2D_factor := 1.704: q2d_dd := 1e6: q2d_rs2D := (rs, xt) -> rs2D_factor*rs*sqrt(X2S*xt)/RS_FACTOR: q2d_fac := t -> t^4*(1 + t^2)/(q2d_dd + t^6): q2d_f := (rs, z, xt, xs0, xs1) -> (1 - q2d_fac(tt(rs, z, xt)))*f_pbe(rs, z, xt, xs0, xs1) + q2d_fac(tt(rs, z, xt))*f_amgb(q2d_rs2D(rs, xt), z): f := (rs, z, xt, xs0, xs1) -> q2d_f(rs, z, xt, xs0, xs1):
A loop $p$ is homotopic to itself if and only if $p$ is a path with image in $s$ and $p$ is closed.
Formal statement is: lemma sequentially_imp_eventually_at_left: fixes a :: "'a::{linorder_topology,first_countable_topology}" assumes b[simp]: "b < a" and *: "\<And>f. (\<And>n. b < f n) \<Longrightarrow> (\<And>n. f n < a) \<Longrightarrow> incseq f \<Longrightarrow> f \<longlonglongrightarrow> a \<Longrightarrow> eventually (\<lambda>n. P (f n)) sequentially" shows "eventually P (at_left a)" Informal statement is: If $b < a$ and for every sequence $f$ such that $b < f(n) < a$ for all $n$ and $f$ is increasing and converges to $a$, then $P(f(n))$ holds for all but finitely many $n$, then $P(x)$ holds for all but finitely many $x < a$.
[GOAL] α : Type u_1 p✝ : α → Prop inst✝ : DecidablePred p✝ l : List α a : α p : α → Bool ⊢ all l p = true ↔ ∀ (a : α), a ∈ l → p a = true [PROOFSTEP] induction' l with a l ih [GOAL] case nil α : Type u_1 p✝ : α → Prop inst✝ : DecidablePred p✝ l : List α a : α p : α → Bool ⊢ all [] p = true ↔ ∀ (a : α), a ∈ [] → p a = true [PROOFSTEP] exact iff_of_true rfl (forall_mem_nil _) [GOAL] case cons α : Type u_1 p✝ : α → Prop inst✝ : DecidablePred p✝ l✝ : List α a✝ : α p : α → Bool a : α l : List α ih : all l p = true ↔ ∀ (a : α), a ∈ l → p a = true ⊢ all (a :: l) p = true ↔ ∀ (a_1 : α), a_1 ∈ a :: l → p a_1 = true [PROOFSTEP] simp only [all_cons, Bool.and_coe_iff, ih, forall_mem_cons] [GOAL] α : Type u_1 p : α → Prop inst✝ : DecidablePred p l : List α a : α ⊢ (all l fun a => decide (p a)) = true ↔ ∀ (a : α), a ∈ l → p a [PROOFSTEP] simp only [all_iff_forall, Bool.of_decide_iff] [GOAL] α : Type u_1 p✝ : α → Prop inst✝ : DecidablePred p✝ l : List α a : α p : α → Bool ⊢ any l p = true ↔ ∃ a, a ∈ l ∧ p a = true [PROOFSTEP] induction' l with a l ih [GOAL] case nil α : Type u_1 p✝ : α → Prop inst✝ : DecidablePred p✝ l : List α a : α p : α → Bool ⊢ any [] p = true ↔ ∃ a, a ∈ [] ∧ p a = true [PROOFSTEP] exact iff_of_false Bool.not_false' (not_exists_mem_nil _) [GOAL] case cons α : Type u_1 p✝ : α → Prop inst✝ : DecidablePred p✝ l✝ : List α a✝ : α p : α → Bool a : α l : List α ih : any l p = true ↔ ∃ a, a ∈ l ∧ p a = true ⊢ any (a :: l) p = true ↔ ∃ a_1, a_1 ∈ a :: l ∧ p a_1 = true [PROOFSTEP] simp only [any_cons, Bool.or_coe_iff, ih, exists_mem_cons_iff] [GOAL] α : Type u_1 p : α → Prop inst✝ : DecidablePred p l : List α a : α ⊢ (any l fun a => decide (p a)) = true ↔ ∃ a, a ∈ l ∧ p a [PROOFSTEP] simp [any_iff_exists]
Formal statement is: lemma (in perfect_space) at_neq_bot [simp]: "at a \<noteq> bot" Informal statement is: In a perfect space, the filter at a point is never the empty filter.
library(shiny) library(xlsx) library(forecast) cpiU <- read.xlsx("./data/SeriesReport-20160224001724_bf095b.xlsx", sheetName = "BLS Data Series", startRow = 11, header = TRUE, endRow = 51) cpiU <- cpiU[-1,] #Remove 1977 row to align with 1978 cpiUts <- ts(cpiU$Annual, start = c(1978), end = c(2014), frequency = 1) #Time series obj of yearly average cpiUper <- cpiUts/lag(cpiUts,-1) - 1 #Annual inflation based on CPI-U shinyServer( function(input, output) { cpiUperm <- meanf(cpiUper, h=86, level = c(80,99), fan = FALSE, lambda = NULL) #86 yr Forecast from mean cpiUpern <- naive(cpiUper, h=86, level = c(80,99), fan = FALSE, lambda = NULL) #86 yr Forecast Naive method cpiUperd <- rwf(cpiUper, h=86, drift = TRUE, level = c(80,99), fan = FALSE, lambda = NULL)#86 yr Forecast from Random Walk with drift output$od2 <- renderPrint({input$id2}) output$od3 <- renderPrint({ as.numeric(input$id3) - 2014 #Calculate number of years }) output$od4 <- renderPrint({ p<-input$id1 #Principal y<-as.numeric(input$id3) - 2014 #Calculate number of years if (input$id2 == "Mean") for(i in 1:y) { p <- as.numeric(p*cpiUperm$upper[i,2]) + p } #Mean Upper 99% compound interest if (input$id2 == "Naive") for(i in 1:y) { p <- as.numeric(p*cpiUpern$upper[i,2]) + p } #Naive Upper 99% compound interest if (input$id2 == "Random Walk with Drift") for(i in 1:y) { p <- as.numeric(p*cpiUperd$upper[i,2]) + p } #Random Upper 99% compound interest paste0("$", round(p, digits=2)) #Return inflated result }) output$newPlot <- renderPlot({ Y<-as.numeric(input$id3) - 2014 #Calculate number of years #Recalculate forecast for specific year input cpiUm <- meanf(cpiUper, h=Y, level = c(80,99), fan = FALSE, lambda = NULL) cpiUn <- naive(cpiUper, h=Y, level = c(80,99), fan = FALSE, lambda = NULL) cpiUd <- rwf(cpiUper, h=Y, drift = TRUE, level = c(80,99), fan = FALSE, lambda = NULL) #Return custom plot if (input$id2 == "Mean") plot(cpiUm, xlab="Years", ylab="Delta", main = "Inflation Rate Forecast with Mean") legend("bottomleft",c("80 confidence level","99 confidence level","mean"),lwd=c(3,3,3), col=c("gray","gray60","blue")) if (input$id2 == "Naive") plot(cpiUn, xlab="Years", ylab="Delta", main = "Inflation Rate Forecast with Naive") legend("bottomleft",c("80 confidence level","99 confidence level","mean"),lwd=c(3,3,3), col=c("gray","gray60","blue")) if (input$id2 == "Random Walk with Drift") plot(cpiUd, xlab="Years", ylab="Delta", main = "Inflation Rate Forecast with RWF Drift") legend("bottomleft",c("80 confidence level","99 confidence level","mean"),lwd=c(3,3,3), col=c("gray","gray60","blue")) }) } )
[STATEMENT] lemma clauseTrueIffContainsTrueLiteral: fixes clause :: Clause and valuation :: Valuation shows "clauseTrue clause valuation = (\<exists> literal. literal el clause \<and> literalTrue literal valuation)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. clauseTrue clause valuation = (\<exists>literal. literal el clause \<and> literalTrue literal valuation) [PROOF STEP] by (induct clause) auto
{-# OPTIONS --without-K #-} module container.m.from-nat where open import container.m.from-nat.core public open import container.m.from-nat.cone public open import container.m.from-nat.coalgebra public open import container.m.from-nat.bisimulation public
\subsection{Integration} \noindent The area element is $\mathrm{d}A = \rho^2\sin{\phi}\mathrm{d}\theta\mathrm{d}\phi$.\\ The volume element is $\mathrm{d}V = \rho^2\sin{\phi}\mathrm{d}r\mathrm{d}\theta\mathrm{d}\phi$.\\ [INSERT IMAGE] \input{curvilinearCoordinates/sphereVolume}
\documentclass[12pt]{article} \usepackage{amsmath} \usepackage{amssymb} \usepackage{amsthm} \usepackage{hyperref} \usepackage[pdftex]{graphicx} %\usepackage{physymb} %\usepackage{wrapfig} \usepackage{braket} \usepackage{subcaption} \title{PH 304: Assignment 1} \author{Manish Goregaokar (120260006)} \date{January 25, 2015} \begin{document} \maketitle \section*{Problem 1} The probability of there not being a single 1 in four rolls is $\frac56\times\frac56\times\frac56\times\frac56 = \frac{625}{1296}$ since we restrict each die roll to the space of 2-6 (5 possibilities) out of its actual space of 6. The inverse of this, i.e. the probability of there being at least one 1 in four rolls, is $\boxed{1 - \frac{625}{1296} = \frac{671}{1296} = 0.517747}\hfill \text{Ans (i)}$ When a pair of dice are rolled 24 times, the probability of never getting a double 1 is $\left(\frac{35}{36}\right)^{24}$ since the (equiprobable) sample space for a single roll has 36 candidates, of which one is a double-1. Thus the probability of having at least one double 1 is $\boxed{1-\left(\frac{35}{36}\right)^{24} = 0.491404}\hfill\text{Ans (ii)}$ \section*{Problem 2} Let the probability for a single ameoba to die or have its progeny eventually die out be $d$. \begin{align*} d & = P(\text{amoeba dies}) + P(\text{amoeba lives but descendants die})\\ &= 1-p + p(P(\text{amoeba or descendants die out})^2)\\ &= 1-p + pd^2\\ \therefore d &= 1-p + pd^2\\ \therefore 0 &=pd^2 -d +1-p\\ \therefore d &= \frac{1\pm \sqrt{1-4p(1-p)}}{2p}\\ &= \frac{1\pm \sqrt{4p^2 - 4p + 1}}{2p}\\ &= \frac{1\pm \sqrt{(2p - 1)^2}}{2p}\\ &= \frac{1\pm (2p -1)}{2p} \end{align*} For $p<\frac12$, the solution with the $+$ is the only possible one, and thus $d=1$. For $p>\frac12$, it is the solution with the $-$, and we get the probability of death as $\frac{1-p}{p}$. Thus, the minimum value of $p$ for there to be a non-zero probability of survival ($d<1$) is $\boxed{\frac12}$. For $p=3/4$, $d=\frac13$, so the probability of survival is $1-d = \boxed{\frac23}$ \section*{Problem 3} Given: $P(\text{twin}) = 0.02, P(\text{identical twin}) = 0.002$ We want $P(\text{identical}|\text{twin})$, which by Bayes' theorem is $$\frac{P(\text{twin}|\text{identical})P(\text{identical})}{P(\text{twin})}=\frac{P(\text{identical})}{P(\text{twin})}=0.1$$ Thus the probability that he was an identical twin is $\boxed{0.1}\hfill \text{Ans.}$ \section*{Problem 4} The distribution is $P(n|N) = {n\choose N}p^n(1-p)^{N-n}$, and thus the characteristic function is \begin{align*}\tilde{P}(k) &= \Braket{e^{-ikn}}\\ &= \sum_{n=0}^N e^{-ikn}{n\choose N}p^n(1-p)^{N-n}\\ &= \sum_{n=0}^N {n\choose N}\left(e^{-ik}\cdot p\right)^n(1-p)^{N-n}\\ &= (1 - p(e^{-ik}-1))^N \end{align*} $\therefore \boxed{\tilde{P}(k) = (1 - p(e^{-ik}-1))^N}\hfill \text{Ans.}$ Cumulant generating function \begin{align*} Q(k) & = \ln\tilde{P}(k)\\ &= \ln (1 - p(e^{-ik}-1))^N\\ &= N \ln (1 - p(e^{-ik}-1)) \end{align*} $\therefore \boxed{\ln\tilde{P}(k) = N\ln (1 - p(e^{-ik}-1))}\hfill \text{Ans.}$ ~\\ If $-ik = y$, then $Q(k) = \ln\tilde{P}(k) = \sum_n \frac{y^n}{n!}\Braket{x^n}_C$. This means that $\left.Q^{(j)}(k)\right|_{k=0} = \Braket{x^j}_C$. Thus the first moment is $Q(0) = 0$, and the second moment is calculated as: \begin{align*} Q'(0) &= \left.\frac{d}{dk}N\ln (1 - p(e^{-ik}-1))\right|_{k=0}\\ &= \left.\frac{N p e^y}{1-p \left(e^y-1\right)}\right|_{k=0}\\ &= Np \end{align*} Thus the first two cumulants are $\boxed{0}$ and $\boxed{Np}\hfill$ Ans. \section*{Problem 5} $$p(x) = \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{(x-\lambda)^2}{2\sigma^2}\right]$$ \begin{align*} \therefore \tilde{p}(k) &= \int_{-\infty}^{\infty} e^{-ikx} \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{(x-\lambda)^2}{2\sigma^2}\right] dx\\ &=\int \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{(x-\lambda)^2 + 2ikx\sigma^2}{2\sigma^2}\right] dx\\ &=\int \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{x^2 + \lambda^2 - 2x\lambda + 2ikx\sigma^2}{2\sigma^2}\right] dx\\ &=\int \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{x^2 - 2x(\lambda - ik\sigma^2) + \lambda^2 }{2\sigma^2}\right] dx\\ &=\int \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{x^2 - 2x(\lambda - ik\sigma^2) + (\lambda - ik\sigma^2)^2 -2\lambda ik\sigma^2 +i^2k^2\sigma^4 }{2\sigma^2}\right] dx\\ &=\int \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{(x -(\lambda - ik\sigma^2))^2 -2\lambda ik\sigma^2 +i^2k^2\sigma^4 }{2\sigma^2}\right] dx\\ &=e^{-\lambda ik + \frac12 i^2k^2\sigma^2}\int \frac1{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{(x -(\lambda - ik\sigma^2))^2}{2\sigma^2}\right] dx\\ &= e^{-\lambda ik +\frac12 i^2k^2\sigma^2} \cdot 1\\ &= e^{-\lambda ik +\frac12 i^2k^2\sigma^2} \end{align*} Thus cumulant generating function is just $Q(k) = \ln \tilde{p}(k) = -\lambda ik + \frac12 i^2k^2\sigma^2$. If $-ik = y$, $Q(y) = y + \frac12 y^2\sigma^2$ Thus the cumulants are $\Braket{x^n}_C = (y + \frac12 y^2\sigma^2)^{(n)}$, giving us : $\boxed{\Braket{x}_C = 1}$, $\boxed{\Braket{x^2}_C = \frac12\sigma^2}$, and for $n>2$, $\boxed{\Braket{x^n}_C = 0}$ \section*{Problem 6} If we break T into $n$ intervals of $dt$ each ($dt = T/n$), probability of exactly $M$ of these having an event is (where $\lambda$ is the proportionality constant such that individual probability is $\lambda dt$): $$P(M)_n = {n\choose M}(\lambda dt)^M (1-\lambda dt)^{n-M}$$ Assuming no simultaneous events, we can limit $n$ to infinity: \begin{align*} \lim_{n\to\infty} P(M)_n &= \lim_{n\to\infty} {n\choose M}(\lambda dt)^M (1-\lambda dt)^{n-M}\\ &= \lim_{n\to\infty} \frac{n(n-1)....(n-m+2)(n-m+1)}{M!}\left(\lambda \frac{T}{n}\right)^M \left(1-\lambda \frac{T}{n}\right)^{n-M}\\ &= \lim_{n\to\infty} \frac{n(n-1)....(n-m+2)(n-m+1)}{n^M}\frac{\left(\lambda T\right)^M}{M!} \left(1-\lambda \frac{T}{n}\right)^n\left(1-\lambda \frac{T}{n}\right)^{-M}\\ &=1\cdot \frac{\left(\lambda T\right)^M}{M!} \cdot e^{-\lambda T} \cdot 1\\ &= \frac{k^M e^{-k}}{M!}\qquad\qquad (k = T\lambda) \end{align*} Thus, the probability distribution, in terms of the proportionality constant $\lambda$ is: $\boxed{P(M) = \frac{(T\lambda)^M e^{-T\lambda}}{M!}}$ The characteristic function can be calculated as (rewriting $T\lambda$ as $\lambda$) \begin{align*} \tilde{P}(k) &= \sum_{M=0}^\infty \frac{\lambda^M e^{-\lambda}}{M!}e^{-ikM}\\ &= e^{-\lambda}\sum_{M=0}^\infty \frac{e^{(ln\lambda-ik) M}}{M!}\\ &= \exp{e^{ln\lambda-ik}-\lambda} \end{align*} Thus the cumulant generating function is $e^{ln\lambda-ik}-\lambda = \lambda (e^{y} - 1)$, giving us $\boxed{\Braket{x^n}_C = \lambda}$. \end{document}
function [ rgb ] = jmol_color( Z ) %JMOL_COLOR Get color assigned to an element. % rgb = JMOL_COLOR(Z) returns a vector containing the RGB color assigned % to the element with atomic number Z. See % http://jmol.sourceforge.net/jscolors/ % % rgb = JMOL_COLOR(symbol) returns a vector containing the RGB color % assigned to the element with the given chemical symbol if ischar(Z) Z = chemsym2number(Z); end colors = [... [255,255,255];... H [217,255,255];... He [204,128,255];... Li [194,255,0];... Be [255,181,181];... B [144,144,144];... C [48,80,248];... N [255,13,13];... O [144,224,80];... F [179,227,245];... Ne [171,92,242];... Na [138,255,0];... Mg [191,166,166];... Al [240,200,160];... Si [255,128,0];... P [255,255,48];... S [31,240,31];... Cl [128,209,227];... Ar [143,64,212];... K [61,255,0];... Ca [230,230,230];... Sc [191,194,199];... Ti [166,166,171];... V [138,153,199];... Cr [156,122,199];... Mn [224,102,51];... Fe [240,144,160];... Co [80,208,80];... Ni [200,128,51];... Cu [125,128,176];... Zn [194,143,143];... Ga [102,143,143];... Ge [189,128,227];... As [255,161,0];... Se [166,41,41];... Br [92,184,209];... Kr [112,46,176];... Rb [0,255,0];... Sr [148,255,255];... Y [148,224,224];... Zr [115,194,201];... Nb [84,181,181];... Mo [59,158,158];... Tc [36,143,143];... Ru [10,125,140];... Rh [0,105,133];... Pd [192,192,192];... Ag [255,217,143];... Cd [166,117,115];... In [102,128,128];... Sn [158,99,181];... Sb [212,122,0];... Te [148,0,148];... I [66,158,176];... Xe [87,23,143];... Cs [0,201,0];... Ba [112,212,255];... La [255,255,199];... Ce [217,255,199];... Pr [199,255,199];... Nd [163,255,199];... Pm [143,255,199];... Sm [97,255,199];... Eu [69,255,199];... Gd [48,255,199];... Tb [31,255,199];... Dy [0,255,156];... Ho [0,230,117];... Er [0,212,82];... Tm [0,191,56];... Yb [0,171,36];... Lu [77,194,255];... Hf [77,166,255];... Ta [33,148,214];... W [38,125,171];... Re [38,102,150];... Os [23,84,135];... Ir [208,208,224];... Pt [255,209,35];... Au [184,184,208];... Hg [166,84,77];... Tl [87,89,97];... Pb [158,79,181];... Bi [171,92,0];... Po [117,79,69];... At [66,130,150];... Rn [66,0,102];... Fr [0,125,0];... Ra [112,171,250];... Ac [0,186,255];... Th [0,161,255];... Pa [0,143,255];... U [0,128,255];... Np [0,107,255];... Pu [84,92,242];... Am [120,92,227];... Cm [138,79,227];... Bk [161,54,212];... Cf [179,31,212];... Es [179,31,186];... Fm [179,13,166];... Md [189,13,135];... No [199,0,102];... Lr [204,0,89];... Rf [209,0,79];... Db [217,0,69];... Sg [224,0,56];... Bh [230,0,46];... Hs [235,0,38];... Mt ]; rgb = colors(Z,:); end
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir ! This file was ported from Lean 3 source module data.real.hyperreal ! leanprover-community/mathlib commit f2ce6086713c78a7f880485f7917ea547a215982 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Order.Filter.FilterProduct import Mathbin.Analysis.SpecificLimits.Basic /-! # Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ open Filter Filter.Germ open Topology Classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ def Hyperreal : Type := Germ (hyperfilter ℕ : Filter ℕ) ℝ deriving LinearOrderedField, Inhabited #align hyperreal Hyperreal namespace Hyperreal -- mathport name: «exprℝ*» notation "ℝ*" => Hyperreal noncomputable instance : CoeTC ℝ ℝ* := ⟨fun x => (↑x : Germ _ _)⟩ @[simp, norm_cast] theorem coe_eq_coe {x y : ℝ} : (x : ℝ*) = y ↔ x = y := Germ.const_inj #align hyperreal.coe_eq_coe Hyperreal.coe_eq_coe theorem coe_ne_coe {x y : ℝ} : (x : ℝ*) ≠ y ↔ x ≠ y := coe_eq_coe.Not #align hyperreal.coe_ne_coe Hyperreal.coe_ne_coe @[simp, norm_cast] theorem coe_eq_zero {x : ℝ} : (x : ℝ*) = 0 ↔ x = 0 := coe_eq_coe #align hyperreal.coe_eq_zero Hyperreal.coe_eq_zero @[simp, norm_cast] theorem coe_eq_one {x : ℝ} : (x : ℝ*) = 1 ↔ x = 1 := coe_eq_coe #align hyperreal.coe_eq_one Hyperreal.coe_eq_one @[norm_cast] theorem coe_ne_zero {x : ℝ} : (x : ℝ*) ≠ 0 ↔ x ≠ 0 := coe_ne_coe #align hyperreal.coe_ne_zero Hyperreal.coe_ne_zero @[norm_cast] theorem coe_ne_one {x : ℝ} : (x : ℝ*) ≠ 1 ↔ x ≠ 1 := coe_ne_coe #align hyperreal.coe_ne_one Hyperreal.coe_ne_one @[simp, norm_cast] theorem coe_one : ↑(1 : ℝ) = (1 : ℝ*) := rfl #align hyperreal.coe_one Hyperreal.coe_one @[simp, norm_cast] theorem coe_zero : ↑(0 : ℝ) = (0 : ℝ*) := rfl #align hyperreal.coe_zero Hyperreal.coe_zero @[simp, norm_cast] theorem coe_inv (x : ℝ) : ↑x⁻¹ = (x⁻¹ : ℝ*) := rfl #align hyperreal.coe_inv Hyperreal.coe_inv @[simp, norm_cast] theorem coe_neg (x : ℝ) : ↑(-x) = (-x : ℝ*) := rfl #align hyperreal.coe_neg Hyperreal.coe_neg @[simp, norm_cast] theorem coe_add (x y : ℝ) : ↑(x + y) = (x + y : ℝ*) := rfl #align hyperreal.coe_add Hyperreal.coe_add @[simp, norm_cast] theorem coe_bit0 (x : ℝ) : ↑(bit0 x) = (bit0 x : ℝ*) := rfl #align hyperreal.coe_bit0 Hyperreal.coe_bit0 @[simp, norm_cast] theorem coe_bit1 (x : ℝ) : ↑(bit1 x) = (bit1 x : ℝ*) := rfl #align hyperreal.coe_bit1 Hyperreal.coe_bit1 @[simp, norm_cast] theorem coe_mul (x y : ℝ) : ↑(x * y) = (x * y : ℝ*) := rfl #align hyperreal.coe_mul Hyperreal.coe_mul @[simp, norm_cast] theorem coe_div (x y : ℝ) : ↑(x / y) = (x / y : ℝ*) := rfl #align hyperreal.coe_div Hyperreal.coe_div @[simp, norm_cast] theorem coe_sub (x y : ℝ) : ↑(x - y) = (x - y : ℝ*) := rfl #align hyperreal.coe_sub Hyperreal.coe_sub @[simp, norm_cast] theorem coe_le_coe {x y : ℝ} : (x : ℝ*) ≤ y ↔ x ≤ y := Germ.const_le_iff #align hyperreal.coe_le_coe Hyperreal.coe_le_coe @[simp, norm_cast] theorem coe_lt_coe {x y : ℝ} : (x : ℝ*) < y ↔ x < y := Germ.const_lt_iff #align hyperreal.coe_lt_coe Hyperreal.coe_lt_coe @[simp, norm_cast] theorem coe_nonneg {x : ℝ} : 0 ≤ (x : ℝ*) ↔ 0 ≤ x := coe_le_coe #align hyperreal.coe_nonneg Hyperreal.coe_nonneg @[simp, norm_cast] theorem coe_pos {x : ℝ} : 0 < (x : ℝ*) ↔ 0 < x := coe_lt_coe #align hyperreal.coe_pos Hyperreal.coe_pos @[simp, norm_cast] theorem coe_abs (x : ℝ) : ((|x| : ℝ) : ℝ*) = |x| := const_abs x #align hyperreal.coe_abs Hyperreal.coe_abs @[simp, norm_cast] theorem coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max x y := Germ.const_max _ _ #align hyperreal.coe_max Hyperreal.coe_max @[simp, norm_cast] theorem coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min x y := Germ.const_min _ _ #align hyperreal.coe_min Hyperreal.coe_min /-- Construct a hyperreal number from a sequence of real numbers. -/ noncomputable def ofSeq (f : ℕ → ℝ) : ℝ* := (↑f : Germ (hyperfilter ℕ : Filter ℕ) ℝ) #align hyperreal.of_seq Hyperreal.ofSeq /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := ofSeq fun n => n⁻¹ #align hyperreal.epsilon Hyperreal.epsilon /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := ofSeq coe #align hyperreal.omega Hyperreal.omega -- mathport name: hyperreal.epsilon scoped notation "ε" => Hyperreal.epsilon -- mathport name: hyperreal.omega scoped notation "ω" => Hyperreal.omega @[simp] theorem inv_omega : ω⁻¹ = ε := rfl #align hyperreal.inv_omega Hyperreal.inv_omega @[simp] theorem inv_epsilon : ε⁻¹ = ω := @inv_inv _ _ ω #align hyperreal.inv_epsilon Hyperreal.inv_epsilon theorem omega_pos : 0 < ω := Germ.coe_pos.2 <| mem_hyperfilter_of_finite_compl <| by convert Set.finite_singleton 0 simp [Set.eq_singleton_iff_unique_mem] #align hyperreal.omega_pos Hyperreal.omega_pos theorem epsilon_pos : 0 < ε := inv_pos_of_pos omega_pos #align hyperreal.epsilon_pos Hyperreal.epsilon_pos theorem epsilon_ne_zero : ε ≠ 0 := epsilon_pos.ne' #align hyperreal.epsilon_ne_zero Hyperreal.epsilon_ne_zero theorem omega_ne_zero : ω ≠ 0 := omega_pos.ne' #align hyperreal.omega_ne_zero Hyperreal.omega_ne_zero theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero #align hyperreal.epsilon_mul_omega Hyperreal.epsilon_mul_omega theorem lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : Tendsto f atTop (𝓝 0)) : ∀ {r : ℝ}, 0 < r → ofSeq f < (r : ℝ*) := by simp only [Metric.tendsto_atTop, Real.dist_eq, sub_zero, lt_def] at hf⊢ intro r hr; cases' hf r hr with N hf' have hs : { i : ℕ | f i < r }ᶜ ⊆ { i : ℕ | i ≤ N } := fun i hi1 => le_of_lt (by simp only [lt_iff_not_ge] <;> exact fun hi2 => hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N) exact mem_hyperfilter_of_finite_compl ((Set.finite_le_nat N).Subset hs) #align hyperreal.lt_of_tendsto_zero_of_pos Hyperreal.lt_of_tendsto_zero_of_pos theorem neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : Tendsto f atTop (𝓝 0)) : ∀ {r : ℝ}, 0 < r → (-r : ℝ*) < ofSeq f := fun r hr => have hg := hf.neg neg_lt_of_neg_lt (by rw [neg_zero] at hg <;> exact lt_of_tendsto_zero_of_pos hg hr) #align hyperreal.neg_lt_of_tendsto_zero_of_pos Hyperreal.neg_lt_of_tendsto_zero_of_pos theorem gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : Tendsto f atTop (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < ofSeq f := fun r hr => by rw [← neg_neg r, coe_neg] <;> exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) #align hyperreal.gt_of_tendsto_zero_of_neg Hyperreal.gt_of_tendsto_zero_of_neg theorem epsilon_lt_pos (x : ℝ) : 0 < x → ε < x := lt_of_tendsto_zero_of_pos tendsto_inverse_atTop_nhds_0_nat #align hyperreal.epsilon_lt_pos Hyperreal.epsilon_lt_pos /-- Standard part predicate -/ def IsSt (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, 0 < δ → (r - δ : ℝ*) < x ∧ x < r + δ #align hyperreal.is_st Hyperreal.IsSt /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := fun x => if h : ∃ r, IsSt x r then Classical.choose h else 0 #align hyperreal.st Hyperreal.st /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def Infinitesimal (x : ℝ*) := IsSt x 0 #align hyperreal.infinitesimal Hyperreal.Infinitesimal /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def InfinitePos (x : ℝ*) := ∀ r : ℝ, ↑r < x #align hyperreal.infinite_pos Hyperreal.InfinitePos /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def InfiniteNeg (x : ℝ*) := ∀ r : ℝ, x < r #align hyperreal.infinite_neg Hyperreal.InfiniteNeg /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def Infinite (x : ℝ*) := InfinitePos x ∨ InfiniteNeg x #align hyperreal.infinite Hyperreal.Infinite /-! ### Some facts about `st` -/ private theorem is_st_unique' (x : ℝ*) (r s : ℝ) (hr : IsSt x r) (hs : IsSt x s) (hrs : r < s) : False := by have hrs' := half_pos <| sub_pos_of_lt hrs have hr' := (hr _ hrs').2 have hs' := (hs _ hrs').1 have h : s - (s - r) / 2 = r + (s - r) / 2 := by linarith norm_cast at * rw [h] at hs' exact not_lt_of_lt hs' hr' #align hyperreal.is_st_unique' hyperreal.is_st_unique' theorem isSt_unique {x : ℝ*} {r s : ℝ} (hr : IsSt x r) (hs : IsSt x s) : r = s := by rcases lt_trichotomy r s with (h | h | h) · exact False.elim (is_st_unique' x r s hr hs h) · exact h · exact False.elim (is_st_unique' x s r hs hr h) #align hyperreal.is_st_unique Hyperreal.isSt_unique theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, IsSt x r) → ¬Infinite x := fun he hi => Exists.dcases_on he fun r hr => hi.elim (fun hip => not_lt_of_lt (hr 2 zero_lt_two).2 (hip <| r + 2)) fun hin => not_lt_of_lt (hr 2 zero_lt_two).1 (hin <| r - 2) #align hyperreal.not_infinite_of_exists_st Hyperreal.not_infinite_of_exists_st theorem isSt_supₛ {x : ℝ*} (hni : ¬Infinite x) : IsSt x (supₛ { y : ℝ | (y : ℝ*) < x }) := let S : Set ℝ := { y : ℝ | (y : ℝ*) < x } let R : _ := supₛ S have hnile := not_forall.mp (not_or.mp hni).1 have hnige := not_forall.mp (not_or.mp hni).2 Exists.dcases_on hnile <| Exists.dcases_on hnige fun r₁ hr₁ r₂ hr₂ => have HR₁ : S.Nonempty := ⟨r₁ - 1, lt_of_lt_of_le (coe_lt_coe.2 <| sub_one_lt _) (not_lt.mp hr₁)⟩ have HR₂ : BddAbove S := ⟨r₂, fun y hy => le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hr₂)))⟩ fun δ hδ => ⟨lt_of_not_le fun c => have hc : ∀ y ∈ S, y ≤ R - δ := fun y hy => coe_le_coe.1 <| le_of_lt <| lt_of_lt_of_le hy c not_lt_of_le (csupₛ_le HR₁ hc) <| sub_lt_self R hδ, lt_of_not_le fun c => have hc : ↑(R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hδ)) R) c not_lt_of_le (le_csupₛ HR₂ hc) <| (lt_add_iff_pos_right _).mpr <| half_pos hδ⟩ #align hyperreal.is_st_Sup Hyperreal.isSt_supₛ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬Infinite x) : ∃ r : ℝ, IsSt x r := ⟨supₛ { y : ℝ | (y : ℝ*) < x }, isSt_supₛ hni⟩ #align hyperreal.exists_st_of_not_infinite Hyperreal.exists_st_of_not_infinite theorem st_eq_supₛ {x : ℝ*} : st x = supₛ { y : ℝ | (y : ℝ*) < x } := by unfold st; split_ifs · exact is_st_unique (Classical.choose_spec h) (is_st_Sup (not_infinite_of_exists_st h)) · cases' not_imp_comm.mp exists_st_of_not_infinite h with H H · rw [(Set.ext fun i => ⟨fun hi => Set.mem_univ i, fun hi => H i⟩ : { y : ℝ | (y : ℝ*) < x } = Set.univ)] exact real.Sup_univ.symm · rw [(Set.ext fun i => ⟨fun hi => False.elim (not_lt_of_lt (H i) hi), fun hi => False.elim (Set.not_mem_empty i hi)⟩ : { y : ℝ | (y : ℝ*) < x } = ∅)] exact real.Sup_empty.symm #align hyperreal.st_eq_Sup Hyperreal.st_eq_supₛ theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, IsSt x r) ↔ ¬Infinite x := ⟨not_infinite_of_exists_st, exists_st_of_not_infinite⟩ #align hyperreal.exists_st_iff_not_infinite Hyperreal.exists_st_iff_not_infinite theorem infinite_iff_not_exists_st {x : ℝ*} : Infinite x ↔ ¬∃ r : ℝ, IsSt x r := iff_not_comm.mp exists_st_iff_not_infinite #align hyperreal.infinite_iff_not_exists_st Hyperreal.infinite_iff_not_exists_st theorem st_infinite {x : ℝ*} (hi : Infinite x) : st x = 0 := by unfold st; split_ifs · exact False.elim ((infinite_iff_not_exists_st.mp hi) h) · rfl #align hyperreal.st_infinite Hyperreal.st_infinite theorem st_of_isSt {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : st x = r := by unfold st; split_ifs · exact is_st_unique (Classical.choose_spec h) hxr · exact False.elim (h ⟨r, hxr⟩) #align hyperreal.st_of_is_st Hyperreal.st_of_isSt theorem isSt_st_of_isSt {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : IsSt x (st x) := by rwa [st_of_is_st hxr] #align hyperreal.is_st_st_of_is_st Hyperreal.isSt_st_of_isSt theorem isSt_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, IsSt x r) : IsSt x (st x) := Exists.dcases_on hx fun r => isSt_st_of_isSt #align hyperreal.is_st_st_of_exists_st Hyperreal.isSt_st_of_exists_st theorem isSt_st {x : ℝ*} (hx : st x ≠ 0) : IsSt x (st x) := by unfold st; split_ifs · exact Classical.choose_spec h · exact False.elim (hx (by unfold st <;> split_ifs <;> rfl)) #align hyperreal.is_st_st Hyperreal.isSt_st theorem isSt_st' {x : ℝ*} (hx : ¬Infinite x) : IsSt x (st x) := isSt_st_of_exists_st <| exists_st_of_not_infinite hx #align hyperreal.is_st_st' Hyperreal.isSt_st' theorem isSt_refl_real (r : ℝ) : IsSt r r := fun δ hδ => ⟨sub_lt_self _ (coe_lt_coe.2 hδ), lt_add_of_pos_right _ (coe_lt_coe.2 hδ)⟩ #align hyperreal.is_st_refl_real Hyperreal.isSt_refl_real theorem st_id_real (r : ℝ) : st r = r := st_of_isSt (isSt_refl_real r) #align hyperreal.st_id_real Hyperreal.st_id_real theorem eq_of_isSt_real {r s : ℝ} : IsSt r s → r = s := isSt_unique (isSt_refl_real r) #align hyperreal.eq_of_is_st_real Hyperreal.eq_of_isSt_real theorem isSt_real_iff_eq {r s : ℝ} : IsSt r s ↔ r = s := ⟨eq_of_isSt_real, fun hrs => by rw [hrs] <;> exact is_st_refl_real s⟩ #align hyperreal.is_st_real_iff_eq Hyperreal.isSt_real_iff_eq theorem isSt_symm_real {r s : ℝ} : IsSt r s ↔ IsSt s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] #align hyperreal.is_st_symm_real Hyperreal.isSt_symm_real theorem isSt_trans_real {r s t : ℝ} : IsSt r s → IsSt s t → IsSt r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq] <;> exact Eq.trans #align hyperreal.is_st_trans_real Hyperreal.isSt_trans_real theorem isSt_inj_real {r₁ r₂ s : ℝ} (h1 : IsSt r₁ s) (h2 : IsSt r₂ s) : r₁ = r₂ := Eq.trans (eq_of_isSt_real h1) (eq_of_isSt_real h2).symm #align hyperreal.is_st_inj_real Hyperreal.isSt_inj_real theorem isSt_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : IsSt x r ↔ ∀ δ : ℝ, 0 < δ → |x - r| < δ := by simp only [abs_sub_lt_iff, sub_lt_iff_lt_add, is_st, and_comm', add_comm] #align hyperreal.is_st_iff_abs_sub_lt_delta Hyperreal.isSt_iff_abs_sub_lt_delta theorem isSt_add {x y : ℝ*} {r s : ℝ} : IsSt x r → IsSt y s → IsSt (x + y) (r + s) := fun hxr hys d hd => have hxr' := hxr (d / 2) (half_pos hd) have hys' := hys (d / 2) (half_pos hd) ⟨by convert add_lt_add hxr'.1 hys'.1 using 1 <;> norm_cast <;> linarith, by convert add_lt_add hxr'.2 hys'.2 using 1 <;> norm_cast <;> linarith⟩ #align hyperreal.is_st_add Hyperreal.isSt_add theorem isSt_neg {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : IsSt (-x) (-r) := fun d hd => show -(r : ℝ*) - d < -x ∧ -x < -r + d by cases hxr d hd <;> constructor <;> linarith #align hyperreal.is_st_neg Hyperreal.isSt_neg theorem isSt_sub {x y : ℝ*} {r s : ℝ} : IsSt x r → IsSt y s → IsSt (x - y) (r - s) := fun hxr hys => by rw [sub_eq_add_neg, sub_eq_add_neg] <;> exact is_st_add hxr (is_st_neg hys) #align hyperreal.is_st_sub Hyperreal.isSt_sub -- (st x < st y) → (x < y) → (x ≤ y) → (st x ≤ st y) theorem lt_of_isSt_lt {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) : r < s → x < y := fun hrs => by have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs) have hxr' := (hxr _ hrs').2 have hys' := (hys _ hrs').1 have H1 : r + (s - r) / 2 = (r + s) / 2 := by linarith have H2 : s - (s - r) / 2 = (r + s) / 2 := by linarith norm_cast at * rw [H1] at hxr' rw [H2] at hys' exact lt_trans hxr' hys' #align hyperreal.lt_of_is_st_lt Hyperreal.lt_of_isSt_lt theorem isSt_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : IsSt x r) (hsy : IsSt y s) : x ≤ y → r ≤ s := by rw [← not_lt, ← not_lt, not_imp_not] <;> exact lt_of_is_st_lt hsy hrx #align hyperreal.is_st_le_of_le Hyperreal.isSt_le_of_le theorem st_le_of_le {x y : ℝ*} (hix : ¬Infinite x) (hiy : ¬Infinite y) : x ≤ y → st x ≤ st y := have hx' := isSt_st' hix have hy' := isSt_st' hiy isSt_le_of_le hx' hy' #align hyperreal.st_le_of_le Hyperreal.st_le_of_le theorem lt_of_st_lt {x y : ℝ*} (hix : ¬Infinite x) (hiy : ¬Infinite y) : st x < st y → x < y := have hx' := isSt_st' hix have hy' := isSt_st' hiy lt_of_isSt_lt hx' hy' #align hyperreal.lt_of_st_lt Hyperreal.lt_of_st_lt /-! ### Basic lemmas about infinite -/ theorem infinitePos_def {x : ℝ*} : InfinitePos x ↔ ∀ r : ℝ, ↑r < x := by rw [iff_eq_eq] <;> rfl #align hyperreal.infinite_pos_def Hyperreal.infinitePos_def theorem infiniteNeg_def {x : ℝ*} : InfiniteNeg x ↔ ∀ r : ℝ, x < r := by rw [iff_eq_eq] <;> rfl #align hyperreal.infinite_neg_def Hyperreal.infiniteNeg_def theorem ne_zero_of_infinite {x : ℝ*} : Infinite x → x ≠ 0 := fun hI h0 => Or.cases_on hI (fun hip => lt_irrefl (0 : ℝ*) ((by rwa [← h0] : InfinitePos 0) 0)) fun hin => lt_irrefl (0 : ℝ*) ((by rwa [← h0] : InfiniteNeg 0) 0) #align hyperreal.ne_zero_of_infinite Hyperreal.ne_zero_of_infinite theorem not_infinite_zero : ¬Infinite 0 := fun hI => ne_zero_of_infinite hI rfl #align hyperreal.not_infinite_zero Hyperreal.not_infinite_zero theorem pos_of_infinitePos {x : ℝ*} : InfinitePos x → 0 < x := fun hip => hip 0 #align hyperreal.pos_of_infinite_pos Hyperreal.pos_of_infinitePos theorem neg_of_infiniteNeg {x : ℝ*} : InfiniteNeg x → x < 0 := fun hin => hin 0 #align hyperreal.neg_of_infinite_neg Hyperreal.neg_of_infiniteNeg theorem not_infinitePos_of_infiniteNeg {x : ℝ*} : InfiniteNeg x → ¬InfinitePos x := fun hn hp => not_lt_of_lt (hn 1) (hp 1) #align hyperreal.not_infinite_pos_of_infinite_neg Hyperreal.not_infinitePos_of_infiniteNeg theorem not_infiniteNeg_of_infinitePos {x : ℝ*} : InfinitePos x → ¬InfiniteNeg x := imp_not_comm.mp not_infinitePos_of_infiniteNeg #align hyperreal.not_infinite_neg_of_infinite_pos Hyperreal.not_infiniteNeg_of_infinitePos theorem infiniteNeg_neg_of_infinitePos {x : ℝ*} : InfinitePos x → InfiniteNeg (-x) := fun hp r => neg_lt.mp (hp (-r)) #align hyperreal.infinite_neg_neg_of_infinite_pos Hyperreal.infiniteNeg_neg_of_infinitePos theorem infinitePos_neg_of_infiniteNeg {x : ℝ*} : InfiniteNeg x → InfinitePos (-x) := fun hp r => lt_neg.mp (hp (-r)) #align hyperreal.infinite_pos_neg_of_infinite_neg Hyperreal.infinitePos_neg_of_infiniteNeg theorem infinitePos_iff_infiniteNeg_neg {x : ℝ*} : InfinitePos x ↔ InfiniteNeg (-x) := ⟨infiniteNeg_neg_of_infinitePos, fun hin => neg_neg x ▸ infinitePos_neg_of_infiniteNeg hin⟩ #align hyperreal.infinite_pos_iff_infinite_neg_neg Hyperreal.infinitePos_iff_infiniteNeg_neg theorem infiniteNeg_iff_infinitePos_neg {x : ℝ*} : InfiniteNeg x ↔ InfinitePos (-x) := ⟨infinitePos_neg_of_infiniteNeg, fun hin => neg_neg x ▸ infiniteNeg_neg_of_infinitePos hin⟩ #align hyperreal.infinite_neg_iff_infinite_pos_neg Hyperreal.infiniteNeg_iff_infinitePos_neg theorem infinite_iff_infinite_neg {x : ℝ*} : Infinite x ↔ Infinite (-x) := ⟨fun hi => Or.cases_on hi (fun hip => Or.inr (infiniteNeg_neg_of_infinitePos hip)) fun hin => Or.inl (infinitePos_neg_of_infiniteNeg hin), fun hi => Or.cases_on hi (fun hipn => Or.inr (infiniteNeg_iff_infinitePos_neg.mpr hipn)) fun hinp => Or.inl (infinitePos_iff_infiniteNeg_neg.mpr hinp)⟩ #align hyperreal.infinite_iff_infinite_neg Hyperreal.infinite_iff_infinite_neg theorem not_infinite_of_infinitesimal {x : ℝ*} : Infinitesimal x → ¬Infinite x := fun hi hI => have hi' := hi 2 zero_lt_two Or.dcases_on hI (fun hip => have hip' := hip 2 not_lt_of_lt hip' (by convert hi'.2 <;> exact (zero_add 2).symm)) fun hin => have hin' := hin (-2) not_lt_of_lt hin' (by convert hi'.1 <;> exact (zero_sub 2).symm) #align hyperreal.not_infinite_of_infinitesimal Hyperreal.not_infinite_of_infinitesimal theorem not_infinitesimal_of_infinite {x : ℝ*} : Infinite x → ¬Infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal #align hyperreal.not_infinitesimal_of_infinite Hyperreal.not_infinitesimal_of_infinite theorem not_infinitesimal_of_infinitePos {x : ℝ*} : InfinitePos x → ¬Infinitesimal x := fun hp => not_infinitesimal_of_infinite (Or.inl hp) #align hyperreal.not_infinitesimal_of_infinite_pos Hyperreal.not_infinitesimal_of_infinitePos theorem not_infinitesimal_of_infiniteNeg {x : ℝ*} : InfiniteNeg x → ¬Infinitesimal x := fun hn => not_infinitesimal_of_infinite (Or.inr hn) #align hyperreal.not_infinitesimal_of_infinite_neg Hyperreal.not_infinitesimal_of_infiniteNeg theorem infinitePos_iff_infinite_and_pos {x : ℝ*} : InfinitePos x ↔ Infinite x ∧ 0 < x := ⟨fun hip => ⟨Or.inl hip, hip 0⟩, fun ⟨hi, hp⟩ => hi.casesOn (fun hip => hip) fun hin => False.elim (not_lt_of_lt hp (hin 0))⟩ #align hyperreal.infinite_pos_iff_infinite_and_pos Hyperreal.infinitePos_iff_infinite_and_pos theorem infiniteNeg_iff_infinite_and_neg {x : ℝ*} : InfiniteNeg x ↔ Infinite x ∧ x < 0 := ⟨fun hip => ⟨Or.inr hip, hip 0⟩, fun ⟨hi, hp⟩ => hi.casesOn (fun hin => False.elim (not_lt_of_lt hp (hin 0))) fun hip => hip⟩ #align hyperreal.infinite_neg_iff_infinite_and_neg Hyperreal.infiniteNeg_iff_infinite_and_neg theorem infinitePos_iff_infinite_of_pos {x : ℝ*} (hp : 0 < x) : InfinitePos x ↔ Infinite x := by rw [infinite_pos_iff_infinite_and_pos] <;> exact ⟨fun hI => hI.1, fun hI => ⟨hI, hp⟩⟩ #align hyperreal.infinite_pos_iff_infinite_of_pos Hyperreal.infinitePos_iff_infinite_of_pos theorem infinitePos_iff_infinite_of_nonneg {x : ℝ*} (hp : 0 ≤ x) : InfinitePos x ↔ Infinite x := Or.cases_on (lt_or_eq_of_le hp) infinitePos_iff_infinite_of_pos fun h => by rw [h.symm] <;> exact ⟨fun hIP => False.elim (not_infinite_zero (Or.inl hIP)), fun hI => False.elim (not_infinite_zero hI)⟩ #align hyperreal.infinite_pos_iff_infinite_of_nonneg Hyperreal.infinitePos_iff_infinite_of_nonneg theorem infiniteNeg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : InfiniteNeg x ↔ Infinite x := by rw [infinite_neg_iff_infinite_and_neg] <;> exact ⟨fun hI => hI.1, fun hI => ⟨hI, hn⟩⟩ #align hyperreal.infinite_neg_iff_infinite_of_neg Hyperreal.infiniteNeg_iff_infinite_of_neg theorem infinitePos_abs_iff_infinite_abs {x : ℝ*} : InfinitePos (|x|) ↔ Infinite (|x|) := infinitePos_iff_infinite_of_nonneg (abs_nonneg _) #align hyperreal.infinite_pos_abs_iff_infinite_abs Hyperreal.infinitePos_abs_iff_infinite_abs theorem infinite_iff_infinitePos_abs {x : ℝ*} : Infinite x ↔ InfinitePos (|x|) := ⟨fun hi d => Or.cases_on hi (fun hip => by rw [abs_of_pos (hip 0)] <;> exact hip d) fun hin => by rw [abs_of_neg (hin 0)] <;> exact lt_neg.mp (hin (-d)), fun hipa => by rcases lt_trichotomy x 0 with (h | h | h) · exact Or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa [abs_of_neg h] at hipa)) · exact False.elim (ne_zero_of_infinite (Or.inl (by rw [h] <;> rwa [h, abs_zero] at hipa)) h) · exact Or.inl (by rwa [abs_of_pos h] at hipa)⟩ #align hyperreal.infinite_iff_infinite_pos_abs Hyperreal.infinite_iff_infinitePos_abs theorem infinite_iff_infinite_abs {x : ℝ*} : Infinite x ↔ Infinite (|x|) := by rw [← infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] #align hyperreal.infinite_iff_infinite_abs Hyperreal.infinite_iff_infinite_abs theorem infinite_iff_abs_lt_abs {x : ℝ*} : Infinite x ↔ ∀ r : ℝ, (|r| : ℝ*) < |x| := ⟨fun hI r => coe_abs r ▸ infinite_iff_infinitePos_abs.mp hI (|r|), fun hR => Or.cases_on (max_choice x (-x)) (fun h => Or.inl fun r => lt_of_le_of_lt (le_abs_self _) (h ▸ hR r)) fun h => Or.inr fun r => neg_lt_neg_iff.mp <| lt_of_le_of_lt (neg_le_abs_self _) (h ▸ hR r)⟩ #align hyperreal.infinite_iff_abs_lt_abs Hyperreal.infinite_iff_abs_lt_abs theorem infinitePos_add_not_infiniteNeg {x y : ℝ*} : InfinitePos x → ¬InfiniteNeg y → InfinitePos (x + y) := by intro hip hnin r cases' not_forall.mp hnin with r₂ hr₂ convert add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂) using 1 simp #align hyperreal.infinite_pos_add_not_infinite_neg Hyperreal.infinitePos_add_not_infiniteNeg theorem not_infiniteNeg_add_infinitePos {x y : ℝ*} : ¬InfiniteNeg x → InfinitePos y → InfinitePos (x + y) := fun hx hy => by rw [add_comm] <;> exact infinite_pos_add_not_infinite_neg hy hx #align hyperreal.not_infinite_neg_add_infinite_pos Hyperreal.not_infiniteNeg_add_infinitePos theorem infiniteNeg_add_not_infinitePos {x y : ℝ*} : InfiniteNeg x → ¬InfinitePos y → InfiniteNeg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add] <;> exact infinite_pos_add_not_infinite_neg #align hyperreal.infinite_neg_add_not_infinite_pos Hyperreal.infiniteNeg_add_not_infinitePos theorem not_infinitePos_add_infiniteNeg {x y : ℝ*} : ¬InfinitePos x → InfiniteNeg y → InfiniteNeg (x + y) := fun hx hy => by rw [add_comm] <;> exact infinite_neg_add_not_infinite_pos hy hx #align hyperreal.not_infinite_pos_add_infinite_neg Hyperreal.not_infinitePos_add_infiniteNeg theorem infinitePos_add_infinitePos {x y : ℝ*} : InfinitePos x → InfinitePos y → InfinitePos (x + y) := fun hx hy => infinitePos_add_not_infiniteNeg hx (not_infiniteNeg_of_infinitePos hy) #align hyperreal.infinite_pos_add_infinite_pos Hyperreal.infinitePos_add_infinitePos theorem infiniteNeg_add_infiniteNeg {x y : ℝ*} : InfiniteNeg x → InfiniteNeg y → InfiniteNeg (x + y) := fun hx hy => infiniteNeg_add_not_infinitePos hx (not_infinitePos_of_infiniteNeg hy) #align hyperreal.infinite_neg_add_infinite_neg Hyperreal.infiniteNeg_add_infiniteNeg theorem infinitePos_add_not_infinite {x y : ℝ*} : InfinitePos x → ¬Infinite y → InfinitePos (x + y) := fun hx hy => infinitePos_add_not_infiniteNeg hx (not_or.mp hy).2 #align hyperreal.infinite_pos_add_not_infinite Hyperreal.infinitePos_add_not_infinite theorem infiniteNeg_add_not_infinite {x y : ℝ*} : InfiniteNeg x → ¬Infinite y → InfiniteNeg (x + y) := fun hx hy => infiniteNeg_add_not_infinitePos hx (not_or.mp hy).1 #align hyperreal.infinite_neg_add_not_infinite Hyperreal.infiniteNeg_add_not_infinite theorem infinitePos_of_tendsto_top {f : ℕ → ℝ} (hf : Tendsto f atTop atTop) : InfinitePos (ofSeq f) := fun r => have hf' := tendsto_atTop_atTop.mp hf Exists.cases_on (hf' (r + 1)) fun i hi => have hi' : ∀ a : ℕ, f a < r + 1 → a < i := fun a => by rw [← not_le, ← not_le] <;> exact not_imp_not.mpr (hi a) have hS : { a : ℕ | r < f a }ᶜ ⊆ { a : ℕ | a ≤ i } := by simp only [Set.compl_setOf, not_lt] <;> exact fun a har => le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))) Germ.coe_lt.2 <| mem_hyperfilter_of_finite_compl <| (Set.finite_le_nat _).Subset hS #align hyperreal.infinite_pos_of_tendsto_top Hyperreal.infinitePos_of_tendsto_top theorem infiniteNeg_of_tendsto_bot {f : ℕ → ℝ} (hf : Tendsto f atTop atBot) : InfiniteNeg (ofSeq f) := fun r => have hf' := tendsto_atTop_atBot.mp hf Exists.cases_on (hf' (r - 1)) fun i hi => have hi' : ∀ a : ℕ, r - 1 < f a → a < i := fun a => by rw [← not_le, ← not_le] <;> exact not_imp_not.mpr (hi a) have hS : { a : ℕ | f a < r }ᶜ ⊆ { a : ℕ | a ≤ i } := by simp only [Set.compl_setOf, not_lt] <;> exact fun a har => le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)) Germ.coe_lt.2 <| mem_hyperfilter_of_finite_compl <| (Set.finite_le_nat _).Subset hS #align hyperreal.infinite_neg_of_tendsto_bot Hyperreal.infiniteNeg_of_tendsto_bot theorem not_infinite_neg {x : ℝ*} : ¬Infinite x → ¬Infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr #align hyperreal.not_infinite_neg Hyperreal.not_infinite_neg theorem not_infinite_add {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : ¬Infinite (x + y) := have hx' := exists_st_of_not_infinite hx have hy' := exists_st_of_not_infinite hy Exists.cases_on hx' <| Exists.cases_on hy' fun r hr s hs => not_infinite_of_exists_st <| ⟨s + r, isSt_add hs hr⟩ #align hyperreal.not_infinite_add Hyperreal.not_infinite_add theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬Infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨fun hni => Exists.dcases_on (not_forall.mp (not_or.mp hni).1) <| Exists.dcases_on (not_forall.mp (not_or.mp hni).2) fun r hr s hs => by rw [not_lt] at hr hs <;> exact ⟨r - 1, s + 1, ⟨lt_of_lt_of_le (by rw [sub_eq_add_neg] <;> norm_num) hr, lt_of_le_of_lt hs (by norm_num)⟩⟩, fun hrs => Exists.dcases_on hrs fun r hr => Exists.dcases_on hr fun s hs => not_or.mpr ⟨not_forall.mpr ⟨s, lt_asymm hs.2⟩, not_forall.mpr ⟨r, lt_asymm hs.1⟩⟩⟩ #align hyperreal.not_infinite_iff_exist_lt_gt Hyperreal.not_infinite_iff_exist_lt_gt theorem not_infinite_real (r : ℝ) : ¬Infinite r := by rw [not_infinite_iff_exist_lt_gt] <;> exact ⟨r - 1, r + 1, coe_lt_coe.2 <| sub_one_lt r, coe_lt_coe.2 <| lt_add_one r⟩ #align hyperreal.not_infinite_real Hyperreal.not_infinite_real theorem not_real_of_infinite {x : ℝ*} : Infinite x → ∀ r : ℝ, x ≠ r := fun hi r hr => not_infinite_real r <| @Eq.subst _ Infinite _ _ hr hi #align hyperreal.not_real_of_infinite Hyperreal.not_real_of_infinite /-! ### Facts about `st` that require some infinite machinery -/ private theorem is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) (hs : s ≠ 0) : IsSt (x * y) (r * s) := have hxr' := isSt_iff_abs_sub_lt_delta.mp hxr have hys' := isSt_iff_abs_sub_lt_delta.mp hys have h := not_infinite_iff_exist_lt_gt.mp <| not_imp_not.mpr infinite_iff_infinite_abs.mpr <| not_infinite_of_exists_st ⟨r, hxr⟩ Exists.cases_on h fun u h' => Exists.cases_on h' fun t ⟨hu, ht⟩ => isSt_iff_abs_sub_lt_delta.mpr fun d hd => calc |x * y - r * s| = |x * (y - s) + (x - r) * s| := by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] _ ≤ |x * (y - s)| + |(x - r) * s| := (abs_add _ _) _ ≤ |x| * |y - s| + |x - r| * |s| := by simp only [abs_mul] _ ≤ |x| * (d / t / 2 : ℝ) + (d / |s| / 2 : ℝ) * |s| := (add_le_add (mul_le_mul_of_nonneg_left (le_of_lt <| hys' _ <| half_pos <| div_pos hd <| coe_pos.1 <| lt_of_le_of_lt (abs_nonneg x) ht) <| abs_nonneg _) (mul_le_mul_of_nonneg_right (le_of_lt <| hxr' _ <| half_pos <| div_pos hd <| abs_pos.2 hs) <| abs_nonneg _)) _ = (d / 2 * (|x| / t) + d / 2 : ℝ*) := by push_cast [-Filter.Germ.const_div] -- TODO: Why wasn't `hyperreal.coe_div` used? have : (|s| : ℝ*) ≠ 0 := by simpa have : (2 : ℝ*) ≠ 0 := two_ne_zero field_simp [*, add_mul, mul_add, mul_assoc, mul_comm, mul_left_comm] _ < (d / 2 * 1 + d / 2 : ℝ*) := (add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one <| lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) <| half_pos <| coe_pos.2 hd) _) _ = (d : ℝ*) := by rw [mul_one, add_halves] #align hyperreal.is_st_mul' hyperreal.is_st_mul' theorem isSt_mul {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) : IsSt (x * y) (r * s) := have h := not_infinite_iff_exist_lt_gt.mp <| not_imp_not.mpr infinite_iff_infinite_abs.mpr <| not_infinite_of_exists_st ⟨r, hxr⟩ Exists.cases_on h fun u h' => Exists.cases_on h' fun t ⟨hu, ht⟩ => by by_cases hs : s = 0 · apply is_st_iff_abs_sub_lt_delta.mpr intro d hd have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd (coe_pos.1 (lt_of_le_of_lt (abs_nonneg x) ht))) rw [hs, coe_zero, sub_zero] at hys' rw [hs, MulZeroClass.mul_zero, coe_zero, sub_zero, abs_mul, mul_comm, ← div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ← coe_div] exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) exact is_st_mul' hxr hys hs #align hyperreal.is_st_mul Hyperreal.isSt_mul --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY theorem not_infinite_mul {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : ¬Infinite (x * y) := have hx' := exists_st_of_not_infinite hx have hy' := exists_st_of_not_infinite hy Exists.cases_on hx' <| Exists.cases_on hy' fun r hr s hs => not_infinite_of_exists_st <| ⟨s * r, isSt_mul hs hr⟩ #align hyperreal.not_infinite_mul Hyperreal.not_infinite_mul --- theorem st_add {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : st (x + y) = st x + st y := have hx' := isSt_st' hx have hy' := isSt_st' hy have hxy := isSt_st' (not_infinite_add hx hy) have hxy' := isSt_add hx' hy' isSt_unique hxy hxy' #align hyperreal.st_add Hyperreal.st_add theorem st_neg (x : ℝ*) : st (-x) = -st x := if h : Infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else isSt_unique (isSt_st' (not_infinite_neg h)) (isSt_neg (isSt_st' h)) #align hyperreal.st_neg Hyperreal.st_neg theorem st_mul {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : st (x * y) = st x * st y := have hx' := isSt_st' hx have hy' := isSt_st' hy have hxy := isSt_st' (not_infinite_mul hx hy) have hxy' := isSt_mul hx' hy' isSt_unique hxy hxy' #align hyperreal.st_mul Hyperreal.st_mul /-! ### Basic lemmas about infinitesimal -/ theorem infinitesimal_def {x : ℝ*} : Infinitesimal x ↔ ∀ r : ℝ, 0 < r → -(r : ℝ*) < x ∧ x < r := ⟨fun hi r hr => by convert hi r hr <;> simp, fun hi d hd => by convert hi d hd <;> simp⟩ #align hyperreal.infinitesimal_def Hyperreal.infinitesimal_def theorem lt_of_pos_of_infinitesimal {x : ℝ*} : Infinitesimal x → ∀ r : ℝ, 0 < r → x < r := fun hi r hr => ((infinitesimal_def.mp hi) r hr).2 #align hyperreal.lt_of_pos_of_infinitesimal Hyperreal.lt_of_pos_of_infinitesimal theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : Infinitesimal x → ∀ r : ℝ, 0 < r → -↑r < x := fun hi r hr => ((infinitesimal_def.mp hi) r hr).1 #align hyperreal.lt_neg_of_pos_of_infinitesimal Hyperreal.lt_neg_of_pos_of_infinitesimal theorem gt_of_neg_of_infinitesimal {x : ℝ*} : Infinitesimal x → ∀ r : ℝ, r < 0 → ↑r < x := fun hi r hr => by convert((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1 <;> exact (neg_neg ↑r).symm #align hyperreal.gt_of_neg_of_infinitesimal Hyperreal.gt_of_neg_of_infinitesimal theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : Infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → |x| < |r| := ⟨fun hi r hr => abs_lt.mpr (by rw [← coe_abs] <;> exact infinitesimal_def.mp hi (|r|) (abs_pos.2 hr)), fun hR => infinitesimal_def.mpr fun r hr => abs_lt.mp <| (abs_of_pos <| coe_pos.2 hr) ▸ hR r <| ne_of_gt hr⟩ #align hyperreal.abs_lt_real_iff_infinitesimal Hyperreal.abs_lt_real_iff_infinitesimal theorem infinitesimal_zero : Infinitesimal 0 := isSt_refl_real 0 #align hyperreal.infinitesimal_zero Hyperreal.infinitesimal_zero theorem zero_of_infinitesimal_real {r : ℝ} : Infinitesimal r → r = 0 := eq_of_isSt_real #align hyperreal.zero_of_infinitesimal_real Hyperreal.zero_of_infinitesimal_real theorem zero_iff_infinitesimal_real {r : ℝ} : Infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, fun hr => by rw [hr] <;> exact infinitesimal_zero⟩ #align hyperreal.zero_iff_infinitesimal_real Hyperreal.zero_iff_infinitesimal_real theorem infinitesimal_add {x y : ℝ*} (hx : Infinitesimal x) (hy : Infinitesimal y) : Infinitesimal (x + y) := by simpa only [add_zero] using is_st_add hx hy #align hyperreal.infinitesimal_add Hyperreal.infinitesimal_add theorem infinitesimal_neg {x : ℝ*} (hx : Infinitesimal x) : Infinitesimal (-x) := by simpa only [neg_zero] using is_st_neg hx #align hyperreal.infinitesimal_neg Hyperreal.infinitesimal_neg theorem infinitesimal_neg_iff {x : ℝ*} : Infinitesimal x ↔ Infinitesimal (-x) := ⟨infinitesimal_neg, fun h => neg_neg x ▸ @infinitesimal_neg (-x) h⟩ #align hyperreal.infinitesimal_neg_iff Hyperreal.infinitesimal_neg_iff theorem infinitesimal_mul {x y : ℝ*} (hx : Infinitesimal x) (hy : Infinitesimal y) : Infinitesimal (x * y) := by simpa only [MulZeroClass.mul_zero] using is_st_mul hx hy #align hyperreal.infinitesimal_mul Hyperreal.infinitesimal_mul theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} : Tendsto f atTop (𝓝 0) → Infinitesimal (ofSeq f) := fun hf d hd => by rw [sub_eq_add_neg, ← coe_neg, ← coe_add, ← coe_add, zero_add, zero_add] <;> exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ #align hyperreal.infinitesimal_of_tendsto_zero Hyperreal.infinitesimal_of_tendsto_zero theorem infinitesimal_epsilon : Infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_atTop_nhds_0_nat #align hyperreal.infinitesimal_epsilon Hyperreal.infinitesimal_epsilon theorem not_real_of_infinitesimal_ne_zero (x : ℝ*) : Infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ r := fun hi hx r hr => hx <| hr.trans <| coe_eq_zero.2 <| isSt_unique (hr.symm ▸ isSt_refl_real r : IsSt x r) hi #align hyperreal.not_real_of_infinitesimal_ne_zero Hyperreal.not_real_of_infinitesimal_ne_zero theorem infinitesimal_sub_isSt {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : Infinitesimal (x - r) := show IsSt (x - r) 0 by rw [sub_eq_add_neg, ← add_neg_self r] exact is_st_add hxr (is_st_refl_real (-r)) #align hyperreal.infinitesimal_sub_is_st Hyperreal.infinitesimal_sub_isSt theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬Infinite x) : Infinitesimal (x - st x) := infinitesimal_sub_isSt <| isSt_st' hx #align hyperreal.infinitesimal_sub_st Hyperreal.infinitesimal_sub_st theorem infinitePos_iff_infinitesimal_inv_pos {x : ℝ*} : InfinitePos x ↔ Infinitesimal x⁻¹ ∧ 0 < x⁻¹ := ⟨fun hip => ⟨infinitesimal_def.mpr fun r hr => ⟨lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip r⁻¹)⟩, inv_pos.2 <| hip 0⟩, fun ⟨hi, hp⟩ r => @by_cases (r = 0) (↑r < x) (fun h => Eq.substr h (inv_pos.mp hp)) fun h => lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos.2 h))).mp ((infinitesimal_def.mp hi) (|r|)⁻¹ (inv_pos.2 (abs_pos.2 h))).2)⟩ #align hyperreal.infinite_pos_iff_infinitesimal_inv_pos Hyperreal.infinitePos_iff_infinitesimal_inv_pos theorem infiniteNeg_iff_infinitesimal_inv_neg {x : ℝ*} : InfiniteNeg x ↔ Infinitesimal x⁻¹ ∧ x⁻¹ < 0 := ⟨fun hin => by have hin' := infinitePos_iff_infinitesimal_inv_pos.mp (infinitePos_neg_of_infiniteNeg hin) rwa [infinitesimal_neg_iff, ← neg_pos, neg_inv], fun hin => by rwa [← neg_pos, infinitesimal_neg_iff, neg_inv, ← infinite_pos_iff_infinitesimal_inv_pos, ← infinite_neg_iff_infinite_pos_neg] at hin⟩ #align hyperreal.infinite_neg_iff_infinitesimal_inv_neg Hyperreal.infiniteNeg_iff_infinitesimal_inv_neg theorem infinitesimal_inv_of_infinite {x : ℝ*} : Infinite x → Infinitesimal x⁻¹ := fun hi => Or.cases_on hi (fun hip => (infinitePos_iff_infinitesimal_inv_pos.mp hip).1) fun hin => (infiniteNeg_iff_infinitesimal_inv_neg.mp hin).1 #align hyperreal.infinitesimal_inv_of_infinite Hyperreal.infinitesimal_inv_of_infinite theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : Infinitesimal x⁻¹) : Infinite x := by cases' lt_or_gt_of_ne h0 with hn hp · exact Or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) · exact Or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) #align hyperreal.infinite_of_infinitesimal_inv Hyperreal.infinite_of_infinitesimal_inv theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : Infinite x ↔ Infinitesimal x⁻¹ := ⟨infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0⟩ #align hyperreal.infinite_iff_infinitesimal_inv Hyperreal.infinite_iff_infinitesimal_inv theorem infinitesimal_pos_iff_infinitePos_inv {x : ℝ*} : InfinitePos x⁻¹ ↔ Infinitesimal x ∧ 0 < x := by convert infinite_pos_iff_infinitesimal_inv_pos <;> simp only [inv_inv] #align hyperreal.infinitesimal_pos_iff_infinite_pos_inv Hyperreal.infinitesimal_pos_iff_infinitePos_inv theorem infinitesimal_neg_iff_infiniteNeg_inv {x : ℝ*} : InfiniteNeg x⁻¹ ↔ Infinitesimal x ∧ x < 0 := by convert infinite_neg_iff_infinitesimal_inv_neg <;> simp only [inv_inv] #align hyperreal.infinitesimal_neg_iff_infinite_neg_inv Hyperreal.infinitesimal_neg_iff_infiniteNeg_inv theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : Infinitesimal x ↔ Infinite x⁻¹ := by convert(infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm <;> simp only [inv_inv] #align hyperreal.infinitesimal_iff_infinite_inv Hyperreal.infinitesimal_iff_infinite_inv /-! ### `st` stuff that requires infinitesimal machinery -/ theorem isSt_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : Tendsto f atTop (𝓝 r)) : IsSt (ofSeq f) r := by have hg : Tendsto (fun n => f n - r) atTop (𝓝 0) := sub_self r ▸ hf.sub tendsto_const_nhds rw [← zero_add r, ← sub_add_cancel f fun n => r] <;> exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) #align hyperreal.is_st_of_tendsto Hyperreal.isSt_of_tendsto theorem isSt_inv {x : ℝ*} {r : ℝ} (hi : ¬Infinitesimal x) : IsSt x r → IsSt x⁻¹ r⁻¹ := fun hxr => have h : x ≠ 0 := fun h => hi (h.symm ▸ infinitesimal_zero) have H := exists_st_of_not_infinite <| not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi Exists.cases_on H fun s hs => have H' : IsSt 1 (r * s) := mul_inv_cancel h ▸ isSt_mul hxr hs have H'' : s = r⁻¹ := one_div r ▸ eq_one_div_of_mul_eq_one_right (eq_of_isSt_real H').symm H'' ▸ hs #align hyperreal.is_st_inv Hyperreal.isSt_inv theorem st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := by by_cases h0 : x = 0 rw [h0, inv_zero, ← coe_zero, st_id_real, inv_zero] by_cases h1 : infinitesimal x rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero] by_cases h2 : Infinite x rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero] exact st_of_is_st (is_st_inv h1 (is_st_st' h2)) #align hyperreal.st_inv Hyperreal.st_inv /-! ### Infinite stuff that requires infinitesimal machinery -/ theorem infinitePos_omega : InfinitePos ω := infinitePos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ #align hyperreal.infinite_pos_omega Hyperreal.infinitePos_omega theorem infinite_omega : Infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon #align hyperreal.infinite_omega Hyperreal.infinite_omega theorem infinitePos_mul_of_infinitePos_not_infinitesimal_pos {x y : ℝ*} : InfinitePos x → ¬Infinitesimal y → 0 < y → InfinitePos (x * y) := fun hx hy₁ hy₂ r => have hy₁' := not_forall.mp (by rw [infinitesimal_def] at hy₁ <;> exact hy₁) Exists.dcases_on hy₁' fun r₁ hy₁'' => by have hyr := by rw [not_imp, ← abs_lt, not_lt, abs_of_pos hy₂] at hy₁'' <;> exact hy₁'' rw [← div_mul_cancel r (ne_of_gt hyr.1), coe_mul] <;> exact mul_lt_mul (hx (r / r₁)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0)) #align hyperreal.infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hyperreal.infinitePos_mul_of_infinitePos_not_infinitesimal_pos theorem infinitePos_mul_of_not_infinitesimal_pos_infinitePos {x y : ℝ*} : ¬Infinitesimal x → 0 < x → InfinitePos y → InfinitePos (x * y) := fun hx hp hy => by rw [mul_comm] <;> exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp #align hyperreal.infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos Hyperreal.infinitePos_mul_of_not_infinitesimal_pos_infinitePos theorem infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg {x y : ℝ*} : InfiniteNeg x → ¬Infinitesimal y → y < 0 → InfinitePos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ← neg_pos, ← neg_mul_neg, infinitesimal_neg_iff] <;> exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos #align hyperreal.infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hyperreal.infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg theorem infinitePos_mul_of_not_infinitesimal_neg_infiniteNeg {x y : ℝ*} : ¬Infinitesimal x → x < 0 → InfiniteNeg y → InfinitePos (x * y) := fun hx hp hy => by rw [mul_comm] <;> exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp #align hyperreal.infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg Hyperreal.infinitePos_mul_of_not_infinitesimal_neg_infiniteNeg theorem infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg {x y : ℝ*} : InfinitePos x → ¬Infinitesimal y → y < 0 → InfiniteNeg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ← neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff] <;> exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos #align hyperreal.infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hyperreal.infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg theorem infiniteNeg_mul_of_not_infinitesimal_neg_infinitePos {x y : ℝ*} : ¬Infinitesimal x → x < 0 → InfinitePos y → InfiniteNeg (x * y) := fun hx hp hy => by rw [mul_comm] <;> exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp #align hyperreal.infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos Hyperreal.infiniteNeg_mul_of_not_infinitesimal_neg_infinitePos theorem infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos {x y : ℝ*} : InfiniteNeg x → ¬Infinitesimal y → 0 < y → InfiniteNeg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul] <;> exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos #align hyperreal.infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hyperreal.infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos theorem infiniteNeg_mul_of_not_infinitesimal_pos_infiniteNeg {x y : ℝ*} : ¬Infinitesimal x → 0 < x → InfiniteNeg y → InfiniteNeg (x * y) := fun hx hp hy => by rw [mul_comm] <;> exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp #align hyperreal.infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg Hyperreal.infiniteNeg_mul_of_not_infinitesimal_pos_infiniteNeg theorem infinitePos_mul_infinitePos {x y : ℝ*} : InfinitePos x → InfinitePos y → InfinitePos (x * y) := fun hx hy => infinitePos_mul_of_infinitePos_not_infinitesimal_pos hx (not_infinitesimal_of_infinitePos hy) (hy 0) #align hyperreal.infinite_pos_mul_infinite_pos Hyperreal.infinitePos_mul_infinitePos theorem infiniteNeg_mul_infiniteNeg {x y : ℝ*} : InfiniteNeg x → InfiniteNeg y → InfinitePos (x * y) := fun hx hy => infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg hx (not_infinitesimal_of_infiniteNeg hy) (hy 0) #align hyperreal.infinite_neg_mul_infinite_neg Hyperreal.infiniteNeg_mul_infiniteNeg theorem infinitePos_mul_infiniteNeg {x y : ℝ*} : InfinitePos x → InfiniteNeg y → InfiniteNeg (x * y) := fun hx hy => infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg hx (not_infinitesimal_of_infiniteNeg hy) (hy 0) #align hyperreal.infinite_pos_mul_infinite_neg Hyperreal.infinitePos_mul_infiniteNeg theorem infiniteNeg_mul_infinitePos {x y : ℝ*} : InfiniteNeg x → InfinitePos y → InfiniteNeg (x * y) := fun hx hy => infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos hx (not_infinitesimal_of_infinitePos hy) (hy 0) #align hyperreal.infinite_neg_mul_infinite_pos Hyperreal.infiniteNeg_mul_infinitePos theorem infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : Infinite x → ¬Infinitesimal y → Infinite (x * y) := fun hx hy => have h0 : y < 0 ∨ 0 < y := lt_or_gt_of_ne fun H0 => hy (Eq.substr H0 (isSt_refl_real 0)) Or.dcases_on hx (Or.dcases_on h0 (fun H0 Hx => Or.inr (infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg Hx hy H0)) fun H0 Hx => Or.inl (infinitePos_mul_of_infinitePos_not_infinitesimal_pos Hx hy H0)) (Or.dcases_on h0 (fun H0 Hx => Or.inl (infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg Hx hy H0)) fun H0 Hx => Or.inr (infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos Hx hy H0)) #align hyperreal.infinite_mul_of_infinite_not_infinitesimal Hyperreal.infinite_mul_of_infinite_not_infinitesimal theorem infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬Infinitesimal x → Infinite y → Infinite (x * y) := fun hx hy => by rw [mul_comm] <;> exact infinite_mul_of_infinite_not_infinitesimal hy hx #align hyperreal.infinite_mul_of_not_infinitesimal_infinite Hyperreal.infinite_mul_of_not_infinitesimal_infinite theorem Infinite.mul {x y : ℝ*} : Infinite x → Infinite y → Infinite (x * y) := fun hx hy => infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) #align hyperreal.infinite.mul Hyperreal.Infinite.mul end Hyperreal namespace Tactic open Positivity private theorem hyperreal_coe_ne_zero {r : ℝ} : r ≠ 0 → (r : ℝ*) ≠ 0 := Hyperreal.coe_ne_zero.2 #align tactic.hyperreal_coe_ne_zero tactic.hyperreal_coe_ne_zero private theorem hyperreal_coe_nonneg {r : ℝ} : 0 ≤ r → 0 ≤ (r : ℝ*) := Hyperreal.coe_nonneg.2 #align tactic.hyperreal_coe_nonneg tactic.hyperreal_coe_nonneg private theorem hyperreal_coe_pos {r : ℝ} : 0 < r → 0 < (r : ℝ*) := Hyperreal.coe_pos.2 #align tactic.hyperreal_coe_pos tactic.hyperreal_coe_pos /-- Extension for the `positivity` tactic: cast from `ℝ` to `ℝ*`. -/ @[positivity] unsafe def positivity_coe_real_hyperreal : expr → tactic strictness | q(@coe _ _ $(inst) $(a)) => do unify inst q(@coeToLift _ _ Hyperreal.hasCoeT) let strictness_a ← core a match strictness_a with | positive p => positive <$> mk_app `` hyperreal_coe_pos [p] | nonnegative p => nonnegative <$> mk_app `` hyperreal_coe_nonneg [p] | nonzero p => nonzero <$> mk_app `` hyperreal_coe_ne_zero [p] | e => pp e >>= fail ∘ format.bracket "The expression " " is not of the form `(r : ℝ*)` for `r : ℝ`" #align tactic.positivity_coe_real_hyperreal tactic.positivity_coe_real_hyperreal end Tactic
State Before: α : Type u_1 β : Type u_2 γ : Type ?u.465891 δ : Type ?u.465894 inst✝⁵ : MeasurableSpace α μ ν : Measure α inst✝⁴ : TopologicalSpace β inst✝³ : TopologicalSpace γ inst✝² : TopologicalSpace δ inst✝¹ : SemilatticeInf β inst✝ : ContinuousInf β f g : α →ₘ[μ] β ⊢ f ⊓ g ≤ g State After: α : Type u_1 β : Type u_2 γ : Type ?u.465891 δ : Type ?u.465894 inst✝⁵ : MeasurableSpace α μ ν : Measure α inst✝⁴ : TopologicalSpace β inst✝³ : TopologicalSpace γ inst✝² : TopologicalSpace δ inst✝¹ : SemilatticeInf β inst✝ : ContinuousInf β f g : α →ₘ[μ] β ⊢ ↑(f ⊓ g) ≤ᵐ[μ] ↑g Tactic: rw [← coeFn_le] State Before: α : Type u_1 β : Type u_2 γ : Type ?u.465891 δ : Type ?u.465894 inst✝⁵ : MeasurableSpace α μ ν : Measure α inst✝⁴ : TopologicalSpace β inst✝³ : TopologicalSpace γ inst✝² : TopologicalSpace δ inst✝¹ : SemilatticeInf β inst✝ : ContinuousInf β f g : α →ₘ[μ] β ⊢ ↑(f ⊓ g) ≤ᵐ[μ] ↑g State After: case h α : Type u_1 β : Type u_2 γ : Type ?u.465891 δ : Type ?u.465894 inst✝⁵ : MeasurableSpace α μ ν : Measure α inst✝⁴ : TopologicalSpace β inst✝³ : TopologicalSpace γ inst✝² : TopologicalSpace δ inst✝¹ : SemilatticeInf β inst✝ : ContinuousInf β f g : α →ₘ[μ] β a✝ : α ha : ↑(f ⊓ g) a✝ = ↑f a✝ ⊓ ↑g a✝ ⊢ ↑(f ⊓ g) a✝ ≤ ↑g a✝ Tactic: filter_upwards [coeFn_inf f g] with _ ha State Before: case h α : Type u_1 β : Type u_2 γ : Type ?u.465891 δ : Type ?u.465894 inst✝⁵ : MeasurableSpace α μ ν : Measure α inst✝⁴ : TopologicalSpace β inst✝³ : TopologicalSpace γ inst✝² : TopologicalSpace δ inst✝¹ : SemilatticeInf β inst✝ : ContinuousInf β f g : α →ₘ[μ] β a✝ : α ha : ↑(f ⊓ g) a✝ = ↑f a✝ ⊓ ↑g a✝ ⊢ ↑(f ⊓ g) a✝ ≤ ↑g a✝ State After: case h α : Type u_1 β : Type u_2 γ : Type ?u.465891 δ : Type ?u.465894 inst✝⁵ : MeasurableSpace α μ ν : Measure α inst✝⁴ : TopologicalSpace β inst✝³ : TopologicalSpace γ inst✝² : TopologicalSpace δ inst✝¹ : SemilatticeInf β inst✝ : ContinuousInf β f g : α →ₘ[μ] β a✝ : α ha : ↑(f ⊓ g) a✝ = ↑f a✝ ⊓ ↑g a✝ ⊢ ↑f a✝ ⊓ ↑g a✝ ≤ ↑g a✝ Tactic: rw [ha] State Before: case h α : Type u_1 β : Type u_2 γ : Type ?u.465891 δ : Type ?u.465894 inst✝⁵ : MeasurableSpace α μ ν : Measure α inst✝⁴ : TopologicalSpace β inst✝³ : TopologicalSpace γ inst✝² : TopologicalSpace δ inst✝¹ : SemilatticeInf β inst✝ : ContinuousInf β f g : α →ₘ[μ] β a✝ : α ha : ↑(f ⊓ g) a✝ = ↑f a✝ ⊓ ↑g a✝ ⊢ ↑f a✝ ⊓ ↑g a✝ ≤ ↑g a✝ State After: no goals Tactic: exact inf_le_right
@mrtgll33 Hello Murat ! And welcome to the family mate. Hi friends, my name is Lionel alias "yoyo" and i come from France. @Ancelloti33 Hello there Lionel and welcome to our little fun corner. So, is yoyo your nick name buddy? Did I get this right? Haha. Oh I'm curious about what this Yoyo stands for or how it was created. But nevermind Lionel. @Ancelloti33 Don't worry mate. To my eyes you will always be the eternal teenager. Besides we are all like little or big kids around here. Haha. And yes you are right Lionel. It is my birthday in a few days and this crazy Capricorn ( that is : Moi ) was lucky to live one more year. :rofl: How about you? When is your birthday? P.S. Your fave player is Messi ( bien sur) . Is it because of his skills or maybe cause you two share the same birth name? My name is Rob, 24 years old and I'm from The Netherlands. I play OSM since 2013 and since 2014 I'm a moderator of the Dutch section of the forum. My favourite football club is Ajax from Amsterdam. I follow football and other kind of sports as much as possible. @I-Love-Niken Hello to you too Dimas Restu and welcome to our company. My friend I couldn't agree more with your motto. @TheTransporter_NL And you like darts too and action movies and possibly one of your fave actors is Jason Statham. Plus you love hot blondes . :rofl: Correct me if I'm wrong Rob. My imagination is always running wild. Welcome to our fun corner buddy. I don't have to correct it. @scarle4 Happy New Year my dearest Aris! How are you bro? Just Fine! I wish you all the best for the forthcoming year! @I-Love-Niken I'd prefer it if you could just call me Sofie. Haha. And thank you for your lovely post my friend. Ditto buddy! I hope 2017 will bring to your arms everything that your heart desires!
Formal statement is: lemma norm_triangle_ineq4: "norm (a - b) \<le> norm a + norm b" Informal statement is: The norm of the difference of two vectors is less than or equal to the sum of their norms.
Please note that Ndifuna Ukwazi (NU) is a registered Public Benefit Organisation (PBO) with S18A status in South Africa, meaning that neither you nor NU pays donations tax on donations, and that donations are deductible from your taxable income. NU is also a registered Non-Profit Organisation. Donations can be made through direct deposit into the NU bank account by internet or at the nearest branch of Standard Bank.
Formal statement is: proposition separate_compact_closed: fixes s t :: "'a::heine_borel set" assumes "compact s" and t: "closed t" "s \<inter> t = {}" shows "\<exists>d>0. \<forall>x\<in>s. \<forall>y\<in>t. d \<le> dist x y" Informal statement is: If $s$ is a compact set and $t$ is a closed set with $s \cap t = \emptyset$, then there exists a positive real number $d$ such that for all $x \in s$ and $y \in t$, we have $d \leq \|x - y\|$.
import tactic import data.real.basic import data.set.function noncomputable theory open_locale classical open set function @[protect_proj] class subset (A : Type*) (B : out_param $ Type*) := (mem : B → A → Prop) namespace subset -- The following allows us to use the symbol `∈` instance {A : Type*} {B : Type*} [subset A B] : has_mem B A := ⟨subset.mem⟩ -- This says that two "subset"s are equivalent (written `≈`, type with \approx) when -- they have the same points. instance {A : Type*} {B : Type*} [subset A B] : has_equiv A := ⟨λ X Y, ∀ t, t ∈ X ↔ t ∈ Y⟩ @[simp] lemma equiv_iff {A : Type*} {B : Type*} [subset A B] (X Y : A) : X ≈ Y ↔ ∀ t, t ∈ X ↔ t ∈ Y := iff.rfl -- A "subset" can always be considered as an actual subset, in Lean this is `set B` instance {A : Type*} {B : Type*} [subset A B] : has_coe_t A (set B) := ⟨λ x p, p ∈ x⟩ @[simp] lemma mem_pts {A : Type*} {B : Type*} [subset A B] (a : A) (P : B) : P ∈ (a : set B) ↔ P ∈ a := iff.rfl end subset @[simp] def pts {A : Type*} {B : Type*} [subset A B] : A → set B := λ a, {x : B | x ∈ a} /-- We define an incidence plane as having the undefined terms `Point` and `Line`, a function `distance` that takes every two points to a real number, and a predicate `belongs` that relates points and lines. There are essentially two axioms: existence of two distinct points, and the incidence postulate. -/ class IncidencePlane (Point : Type*) := (distance : Point → Point → ℝ) (Line : Type*) (belongs : Point → Line → Prop) (infix `∈`:100 := belongs) -- Existence postulate (existence : ∃ P Q : Point, P ≠ Q) -- Incidence postulate is divided into 4 statements (line_through : Point → Point → Line) (line_through_left (P Q : Point) : P ∈ (line_through P Q)) (line_through_right (P Q : Point) : Q ∈ (line_through P Q)) (incidence {P Q : Point} {ℓ : Line} : P ≠ Q → P ∈ ℓ → Q ∈ ℓ → ℓ = line_through P Q) namespace IncidencePlane variables {Ω : Type*} [IncidencePlane Ω] -- From here on, we can use the symbol `∈` for Lines instance : subset (Line Ω) Ω := {mem := belongs} -- Here we state that Ω is nonempty (in fact it must have at least two distinct points!) instance : nonempty Ω := nonempty_of_exists IncidencePlane.existence /-- This lemma is a rephrasing of the incidence axiom that doesn't mention `line_through` -/ lemma equal_lines_of_contain_two_points {A B : Ω} {r s : Line Ω} (hAB: A ≠ B) (hAr: A ∈ r) (hAs: A ∈ s) (hBr: B ∈ r) (hBs: B ∈ s) : r = s := by rw [incidence hAB hAr hBr, incidence hAB hAs hBs] -- Define collinearity of a set of points to mean that they all lie on some line def collinear (S : set Ω) : Prop := ∃ (ℓ : Line Ω), ∀ {P : Ω}, P ∈ S → P ∈ ℓ -- The next lemmas allow us to deal with collinearity of sets meta def extfinish : tactic unit := `[ext, finish] lemma collinear_of_equal (S T : set Ω) (h : S = T . extfinish) : (collinear S ↔ collinear T) := iff_of_eq (congr_arg collinear h) lemma collinear_subset (S T : set Ω) (hST : S ⊆ T) : collinear T → collinear S := begin intro h, obtain ⟨ℓ, hℓ⟩ := h, exact ⟨ℓ, λ P hP, hℓ (hST hP)⟩, end lemma collinear_union (S T : set Ω) {P Q : Ω} (h : P ≠ Q) (hS : collinear S) (hT : collinear T) (hPS : P ∈ S) (hPT : P ∈ T) (hQS : Q ∈ S) (hQT : Q ∈ T) : collinear (S ∪ T) := begin obtain ⟨u, hu⟩ := hS, obtain ⟨v, hv⟩ := hT, use u, have huv : u = v := equal_lines_of_contain_two_points h (hu hPS) (hv hPT) (hu hQS) (hv hQT), simp [←huv] at hv, finish, end /-- Say that B is between A and C if they are collinear and AB + BC = AC. We will write A * B * C. Note that this means that always A * A * C and A * C * C, in particular. -/ def between (A B C : Ω) := collinear ({A, B, C} : set Ω) ∧ distance A B + distance B C = distance A C notation A `*` B `*` C := IncidencePlane.between A B C /-- Two lines intersect if they share a point -/ def intersect (r s : Line Ω) : Prop := ∃ A, A ∈ r ∧ A ∈ s /-- Two lines are parallel if they dont intersect (so a line is never parallel to itself) -/ def parallel (r s : Line Ω) : Prop := ¬ intersect r s /-- Next we introduce the notion of a Segment. A segment is the giving two points, A and B. We will use the notation A⬝B to denote the segment denoted by A and B. The segment A⬝B consists of all the points X such that A * X * B. We will identify A⬝B with B⬝A, using the symbol ≈. -/ structure Segment (Point : Type*) := (A : Point) (B : Point) infix `⬝`:100 := Segment.mk namespace Segment -- Declare when P ∈ A⬝B instance : subset (Segment Ω) Ω := { mem := λ P S, S.A * P * S.B } @[simp] lemma mem_pts (S : Segment Ω) (P : Ω) : P ∈ S ↔ (S.A * P * S.B) := iff.rfl /-- The length of a segment is defined to be the distance between its two endpoints If S if a segment, we can use this definition writing `S.length` -/ @[simp] def length (S : Segment Ω) := distance S.A S.B /-- Two segments are said to be congruent (written ≅) if they have the same length -/ @[simp] def congruent (S T : Segment Ω) := length S = length T infix `≅`:100 := congruent end Segment /-- A set of points is convex if given two points P and Q in the set, the segment P⬝Q is contained in the set -/ def is_convex (S : set Ω) := ∀ P Q : Ω, P ∈ S → Q ∈ S → pts (P⬝Q) ⊆ S /-- Two points P and Q lie on the same side of a line ℓ if the segment P⬝Q doesn't intersect ℓ -/ def same_side (ℓ : Line Ω) (P Q : Ω) := pts (P⬝Q) ∩ ℓ = ∅ /-- The half-plane determined by a line ℓ and a point P consists of all the points lying on the same side of P Note : with this definition, the half plane determined by a point in ℓ is the empty set. -/ def half_plane (ℓ : Line Ω) (P : Ω) := {Q | same_side ℓ P Q} /-- Sometimes we will want to consider the closed half plane: all the points lying on the same side of P, together with the line ℓ -/ def closed_half_plane (ℓ : Line Ω) ( P : Ω) := (half_plane ℓ P) ∪ ℓ structure Ray (Point : Type*):= (origin : Point) (target : Point) infix `=>`:100 := Ray.mk namespace Ray instance : subset (Ray Ω) Ω := {mem := λ P r, (r.origin * P * r.target) ∨ (r.origin * r.target * P)} @[simp] lemma mem_pts (r : Ray Ω) (P : Ω) : P ∈ r ↔ (r.origin * P * r.target) ∨ (r.origin * r.target * P) := iff.rfl /-- The line determined by a ray -/ def line (r : Ray Ω) : Line Ω := line_through r.origin r.target /-- A ray is degenerate if its origin and target are the same -/ @[simp] def degenerate (r : Ray Ω) := r.origin = r.target /-- We say that non-degenerate rays r and s are `opposite` if they have the same origin, which is between the two targets -/ def opposite (r s : Ray Ω) := ¬ r.degenerate ∧ ¬ s.degenerate ∧ r.origin = s.origin ∧ r.target * r.origin * s.target end Ray /- ANGLES -/ structure Angle (Point : Type*) := (A : Point) (O : Point) (B : Point) notation `∟`:100 := Angle.mk namespace Angle def degenerate (α : Angle Ω) := collinear ({α.A, α.O, α.B} : set Ω) def interior (α : Angle Ω) := closed_half_plane (line_through α.O α.A) α.B ∩ closed_half_plane (line_through α.O α.A) α.A instance : has_equiv (Angle Ω) := ⟨λ α β, ((α.O => α.A ≈ β.O => β.A) ∧ (α.O => α.B ≈ β.O => β.B)) ∨ ((α.O => α.A ≈ β.O => β.B) ∧ (α.O => α.B ≈ β.O => β.A))⟩ end Angle structure Triangle (Point : Type*) := (A : Point) (B : Point) (C : Point) notation `▵`:100 := Triangle.mk namespace Triangle def degenerate (T: Triangle Ω) := collinear ({T.A, T.B, T.C} : set Ω) def vertices (T : Triangle Ω) := [T.A, T.B, T.C] def sides (T : Triangle Ω) := [(T.A⬝T.B).length, (T.B⬝T.C).length, (T.A⬝T.C).length] instance : subset (Triangle Ω) Ω := {mem := λ P T, P ∈ T.A⬝T.B ∨ P ∈ T.B⬝T.C ∨ P ∈ T.A⬝T.C} end Triangle namespace Ray def between (r s t : Ray Ω) := r.origin = s.origin ∧ s.origin = t.origin ∧ s.target ∈ Angle.interior (∟ r.target r.origin t.target) end Ray end IncidencePlane
/* Copyright (C) 2017 IBM Corp. * 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. */ /************************************************************** * A program for testing the sampleG module **************************************************************/ //#include <mpfr.h> #include <NTL/lzz_p.h> NTL_CLIENT #include "../utils/argmap.h" #include "../TDMatrix.h" #define NFACTORS 8 long tinyFactors[NFACTORS] = { 2, 3, 5, 7, 11, 13, 17, 19 }; int main(int argc, char *argv[]) { #ifdef DEBUG NTL::SetSeed((unsigned char*)"test_sampleG",12); #endif ArgMapping amap; long k = 2; amap.arg("k", k, "number of factors (~ log q)"); long n = 2; amap.arg("n", n, "the small dimension"); // no default info long e=2; amap.arg("e", e, "the power of each factor"); amap.parse(argc, argv); // parses and overrides initail values // for each parameter, one per line, assert (k <= NFACTORS); // for this test we don't want many factors long m = (2+ k*e)*n; TDMatrixParams params(n,k,e,m); Vec<long>& factors = params.factors; cout << "n="<<n<<", m="<<m<<", k="<<k<<", e="<<e<<", q="<<params.getQ()<<endl; Vec<vec_zz_p> syndrome(INIT_SIZE, k); for (long i=0; i<k; i++) { params.zzp_context[i].restore(); syndrome[i].SetLength(n); for (long j=0; j<n; j++) syndrome[i][j] = random_zz_p(); cout << "syndrome mod " << power_long(factors[i],e)<<"= "<<syndrome[i]<<endl <<flush; } // Sample x such that G*x = syndrome Vec<long> x; sampleG(x, syndrome, &params); cout << "sampled vector="<<x<<endl; assert(x.length()== n*e*k); // check that we have the right answer modulo p^e for all factors for (long i=0; i<k; i++) { params.zzp_context[i].restore(); vec_zz_p xMod = conv<vec_zz_p>(x); long index = 0; for (long j=0; j<n; j++) { // check the next syndrome entry mod f_i zz_p xp = to_zz_p(0L); zz_p curFactor = to_zz_p(1L); for (long f=0; f<k; f++) for (long ei=0; ei<e; ei++) { xp += (curFactor * x[index++]); curFactor *= factors[f]; } assert(syndrome[i][j] == xp); } } cout << "PASSED\n"; return 0; }
If $c \neq 0$, then the distribution of $cX$ is the same as the distribution of $X$ scaled by $\lvert c \rvert$.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! EVB-QMDFF - RPMD molecular dynamics and rate constant calculations on ! black-box generated potential energy surfaces ! ! Copyright (c) 2021 by Julien Steffen ([email protected]) ! Stefan Grimme ([email protected]) (QMDFF code) ! ! 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. ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ! ! subroutine trproj: drives projection of hessian out of the ! space of translational and rotational motions: ! first get xyz c.m.; second get transl. and rot. projection matrix ! ! part of QMDFF ! subroutine trproj(natoms,nat3,xyz,hess,ldebug) logical,intent(in)::ldebug integer,intent(in)::natoms,nat3 real(kind=8),dimension(3,natoms)::xyz real(kind=8),dimension(nat3*(nat3+1)/2)::hess integer::i real(kind=8)::xm,ym,zm real(kind=8),dimension(3,natoms)::xyzucm xyzucm(:,:) = xyz(:,:) xm = 0.0d0 ym = 0.0d0 zm = 0.0d0 ! ! move cartesian coordinates ! do i=1,natoms xm = xm + xyzucm(1,i) ym = ym + xyzucm(2,i) zm = zm + xyzucm(3,i) end do xm = xm/natoms ym = ym/natoms zm = zm/natoms do i=1,natoms xyzucm(1,i) = xyzucm(1,i) - xm xyzucm(2,i) = xyzucm(2,i) - ym xyzucm(3,i) = xyzucm(3,i) - zm end do ! ! get translational and rotational projection matrix ! call gtrprojm(natoms,nat3,xyzucm,hess,ldebug) return end subroutine trproj
header {* Algebra of Monotonic Boolean Transformers *} theory Mono_Bool_Tran_Algebra imports Mono_Bool_Tran begin text{* In this section we introduce the {\em algebra of monotonic boolean transformers}. This is a bounded distributive lattice with a monoid operation, a dual operator and an iteration operator. The standard model for this algebra is the set of monotonic boolean transformers introduced in the previous section. *} class dual = fixes dual::"'a \<Rightarrow> 'a" ("_ ^ o" [81] 80) class omega = fixes omega::"'a \<Rightarrow> 'a" ("_ ^ \<omega>" [81] 80) class star = fixes star::"'a \<Rightarrow> 'a" ("(_ ^ *)" [81] 80) class dual_star = fixes dual_star::"'a \<Rightarrow> 'a" ("(_ ^ \<otimes>)" [81] 80) class mbt_algebra = monoid_mult + dual + omega + distrib_lattice + order_top + order_bot + star + dual_star + assumes dual_le: "(x \<le> y) = (y ^ o \<le> x ^ o)" and dual_dual [simp]: "(x ^ o) ^ o = x" and dual_comp: "(x * y) ^ o = x ^ o * y ^ o" and dual_one [simp]: "1 ^ o = 1" and top_comp [simp]: "\<top> * x = \<top>" and inf_comp: "(x \<sqinter> y) * z = (x * z) \<sqinter> (y * z)" and le_comp: "x \<le> y \<Longrightarrow> z * x \<le> z * y" and dual_neg: "(x * \<top>) \<sqinter> (x ^ o * \<bottom>) = \<bottom>" and omega_fix: "x ^ \<omega> = (x * (x ^ \<omega>)) \<sqinter> 1" and omega_least: "(x * z) \<sqinter> y \<le> z \<Longrightarrow> (x ^ \<omega>) * y \<le> z" and star_fix: "x ^ * = (x * (x ^ *)) \<sqinter> 1" and star_greatest: "z \<le> (x * z) \<sqinter> y \<Longrightarrow> z \<le> (x ^ *) * y" and dual_star_def: "(x ^ \<otimes>) = (((x ^ o) ^ *) ^ o)" begin lemma le_comp_right: "x \<le> y \<Longrightarrow> x * z \<le> y * z" apply (cut_tac x = x and y = y and z = z in inf_comp) apply (simp add: inf_absorb1) apply (subgoal_tac "x * z \<sqinter> (y * z) \<le> y * z") apply simp by (rule inf_le2) subclass bounded_lattice proof qed end instantiation MonoTran :: (complete_boolean_algebra) mbt_algebra begin lift_definition dual_MonoTran :: "'a MonoTran \<Rightarrow> 'a MonoTran" is dual_fun by (fact mono_dual_fun) lift_definition omega_MonoTran :: "'a MonoTran \<Rightarrow> 'a MonoTran" is omega_fun by (fact mono_omega_fun) lift_definition star_MonoTran :: "'a MonoTran \<Rightarrow> 'a MonoTran" is star_fun by (fact mono_star_fun) definition dual_star_MonoTran :: "'a MonoTran \<Rightarrow> 'a MonoTran" where "(x::('a MonoTran)) ^ \<otimes> = ((x ^ o) ^ *) ^ o" instance proof fix x y :: "'a MonoTran" show "(x \<le> y) = (y ^ o \<le> x ^ o)" apply transfer apply (auto simp add: fun_eq_iff le_fun_def) apply (drule_tac x = "-xa" in spec) apply simp done next fix x :: "'a MonoTran" show "(x ^ o) ^ o = x" apply transfer apply (simp add: fun_eq_iff) done next fix x y :: "'a MonoTran" show "(x * y) ^ o = x ^ o * y ^ o" apply transfer apply (simp add: fun_eq_iff) done next show "(1\<Colon>'a MonoTran) ^ o = 1" apply transfer apply (simp add: fun_eq_iff) done next fix x :: "'a MonoTran" show "\<top> * x = \<top>" apply transfer apply (simp add: fun_eq_iff) done next fix x y z :: "'a MonoTran" show "(x \<sqinter> y) * z = (x * z) \<sqinter> (y * z)" apply transfer apply (simp add: fun_eq_iff) done next fix x y z :: "'a MonoTran" assume A: "x \<le> y" from A show " z * x \<le> z * y" apply transfer apply (auto simp add: le_fun_def elim: monoE) done next fix x :: "'a MonoTran" show "x * \<top> \<sqinter> (x ^ o * \<bottom>) = \<bottom>" apply transfer apply (simp add: fun_eq_iff inf_compl_bot) done next fix x :: "'a MonoTran" show "x ^ \<omega> = x * x ^ \<omega> \<sqinter> 1" apply transfer apply (simp add: fun_eq_iff) apply (simp add: omega_fun_def Omega_fun_def) apply (subst lfp_unfold, simp_all add: ac_simps) apply (auto intro!: mono_comp mono_comp_fun) done next fix x y z :: "'a MonoTran" assume A: "x * z \<sqinter> y \<le> z" from A show "x ^ \<omega> * y \<le> z" apply transfer apply (auto simp add: lfp_omega lfp_def) apply (rule Inf_lower) apply (auto simp add: Omega_fun_def ac_simps) done next fix x :: "'a MonoTran" show "x ^ * = x * x ^ * \<sqinter> 1" apply transfer apply (auto simp add: star_fun_def Omega_fun_def) apply (subst gfp_unfold, simp_all add: ac_simps) apply (auto intro!: mono_comp mono_comp_fun) done next fix x y z :: "'a MonoTran" assume A: "z \<le> x * z \<sqinter> y" from A show "z \<le> x ^ * * y" apply transfer apply (auto simp add: gfp_star gfp_def) apply (rule Sup_upper) apply (auto simp add: Omega_fun_def) done next fix x :: "'a MonoTran" show "x ^ \<otimes> = ((x ^ o) ^ *) ^ o" by (simp add: dual_star_MonoTran_def) qed end context mbt_algebra begin lemma dual_top [simp]: "\<top> ^ o = \<bottom>" apply (rule antisym, simp_all) by (subst dual_le, simp) lemma dual_bot [simp]: "\<bottom> ^ o = \<top>" apply (rule antisym, simp_all) by (subst dual_le, simp) lemma dual_inf: "(x \<sqinter> y) ^ o = (x ^ o) \<squnion> (y ^ o)" apply (rule antisym, simp_all, safe) apply (subst dual_le, simp, safe) apply (subst dual_le, simp) apply (subst dual_le, simp) apply (subst dual_le, simp) by (subst dual_le, simp) lemma dual_sup: "(x \<squnion> y) ^ o = (x ^ o) \<sqinter> (y ^ o)" apply (rule antisym, simp_all, safe) apply (subst dual_le, simp) apply (subst dual_le, simp) apply (subst dual_le, simp, safe) apply (subst dual_le, simp) by (subst dual_le, simp) lemma sup_comp: "(x \<squnion> y) * z = (x * z) \<squnion> (y * z)" apply (subgoal_tac "((x ^ o \<sqinter> y ^ o) * z ^ o) ^ o = ((x ^ o * z ^ o) \<sqinter> (y ^ o * z ^ o)) ^ o") apply (simp add: dual_inf dual_comp) by (simp add: inf_comp) lemma dual_eq: "x ^ o = y ^ o \<Longrightarrow> x = y" apply (subgoal_tac "(x ^ o) ^ o = (y ^ o) ^ o") apply (subst (asm) dual_dual) apply (subst (asm) dual_dual) by simp_all lemma dual_neg_top [simp]: "(x ^ o * \<bottom>) \<squnion> (x * \<top>) = \<top>" apply (rule dual_eq) by(simp add: dual_sup dual_comp dual_neg) lemma [simp]: "(x * \<bottom>) * y = x * \<bottom>" by (simp add: mult.assoc) lemma gt_one_comp: "1 \<le> x \<Longrightarrow> y \<le> x * y" by (cut_tac x = 1 and y = x and z = y in le_comp_right, simp_all) theorem omega_comp_fix: "x ^ \<omega> * y = (x * (x ^ \<omega>) * y) \<sqinter> y" apply (subst omega_fix) by (simp add: inf_comp) theorem dual_star_fix: "x^\<otimes> = (x * (x^\<otimes>)) \<squnion> 1" by (metis dual_comp dual_dual dual_inf dual_one dual_star_def star_fix) theorem star_comp_fix: "x ^ * * y = (x * (x ^ *) * y) \<sqinter> y" apply (subst star_fix) by (simp add: inf_comp) theorem dual_star_comp_fix: "x^\<otimes> * y = (x * (x^\<otimes>) * y) \<squnion> y" apply (subst dual_star_fix) by (simp add: sup_comp) theorem dual_star_least: "(x * z) \<squnion> y \<le> z \<Longrightarrow> (x^\<otimes>) * y \<le> z" apply (subst dual_le) apply (simp add: dual_star_def dual_comp) apply (rule star_greatest) apply (subst dual_le) by (simp add: dual_inf dual_comp) lemma omega_one [simp]: "1 ^ \<omega> = \<bottom>" apply (rule antisym, simp_all) by (cut_tac x = "1::'a" and y = 1 and z = \<bottom> in omega_least, simp_all) lemma omega_mono: "x \<le> y \<Longrightarrow> x ^ \<omega> \<le> y ^ \<omega>" apply (cut_tac x = x and y = 1 and z = "y ^ \<omega>" in omega_least, simp_all) apply (subst (2) omega_fix, simp_all) apply (rule_tac y = "x * y ^ \<omega>" in order_trans, simp) by (rule le_comp_right, simp) end sublocale mbt_algebra < conjunctive "inf" "inf" "times" done sublocale mbt_algebra < disjunctive "sup" "sup" "times" done context mbt_algebra begin lemma dual_conjunctive: "x \<in> conjunctive \<Longrightarrow> x ^ o \<in> disjunctive" apply (simp add: conjunctive_def disjunctive_def) apply safe apply (rule dual_eq) by (simp add: dual_comp dual_sup) lemma dual_disjunctive: "x \<in> disjunctive \<Longrightarrow> x ^ o \<in> conjunctive" apply (simp add: conjunctive_def disjunctive_def) apply safe apply (rule dual_eq) by (simp add: dual_comp dual_inf) lemma comp_pres_conj: "x \<in> conjunctive \<Longrightarrow> y \<in> conjunctive \<Longrightarrow> x * y \<in> conjunctive" apply (subst conjunctive_def, safe) by (simp add: mult.assoc conjunctiveD) lemma comp_pres_disj: "x \<in> disjunctive \<Longrightarrow> y \<in> disjunctive \<Longrightarrow> x * y \<in> disjunctive" apply (subst disjunctive_def, safe) by (simp add: mult.assoc disjunctiveD) lemma start_pres_conj: "x \<in> conjunctive \<Longrightarrow> (x ^ *) \<in> conjunctive" apply (subst conjunctive_def, safe) apply (rule antisym, simp_all) apply (metis inf_le1 inf_le2 le_comp) apply (rule star_greatest) apply (subst conjunctiveD, simp) apply (subst star_comp_fix) apply (subst star_comp_fix) by (metis inf.assoc inf_left_commute mult.assoc order_refl) lemma dual_star_pres_disj: "x \<in> disjunctive \<Longrightarrow> x^\<otimes> \<in> disjunctive" apply (simp add: dual_star_def) apply (rule dual_conjunctive) apply (rule start_pres_conj) by (rule dual_disjunctive, simp) subsection{*Assertions*} text{* Usually, in Kleene algebra with tests or in other progrm algebras, tests or assertions or assumptions are defined using an existential quantifier. An element of the algebra is a test if it has a complement with respect to $\bot$ and $1$. In this formalization assertions can be defined much simpler using the dual operator. *} definition "assertion = {x . x \<le> 1 \<and> (x * \<top>) \<sqinter> (x ^ o) = x}" lemma assertion_prop: "x \<in> assertion \<Longrightarrow> (x * \<top>) \<sqinter> 1 = x" apply (simp add: assertion_def) apply safe apply (rule antisym) apply simp_all proof - assume [simp]: "x \<le> 1" assume A: "x * \<top> \<sqinter> x ^ o = x" have "x * \<top> \<sqinter> 1 \<le> x * \<top> \<sqinter> x ^ o" apply simp apply (rule_tac y = 1 in order_trans) apply simp apply (subst dual_le) by simp also have "\<dots> = x" by (cut_tac A, simp) finally show "x * \<top> \<sqinter> 1 \<le> x" . next assume A: "x * \<top> \<sqinter> x ^ o = x" have "x = x * \<top> \<sqinter> x ^ o" by (simp add: A) also have "\<dots> \<le> x * \<top>" by simp finally show "x \<le> x * \<top>" . qed lemma dual_assertion_prop: "x \<in> assertion \<Longrightarrow> ((x ^ o) * \<bottom>) \<squnion> 1 = x ^ o" apply (rule dual_eq) by (simp add: dual_sup dual_comp assertion_prop) lemma assertion_disjunctive: "x \<in> assertion \<Longrightarrow> x \<in> disjunctive" apply (simp add: disjunctive_def, safe) apply (drule assertion_prop) proof - assume A: "x * \<top> \<sqinter> 1 = x" fix y z::"'a" have "x * (y \<squnion> z) = (x * \<top> \<sqinter> 1) * (y \<squnion> z)" by (cut_tac A, simp) also have "\<dots> = (x * \<top>) \<sqinter> (y \<squnion> z)" by (simp add: inf_comp) also have "\<dots> = ((x * \<top>) \<sqinter> y) \<squnion> ((x * \<top>) \<sqinter> z)" by (simp add: inf_sup_distrib) also have "\<dots> = (((x * \<top>) \<sqinter> 1) * y) \<squnion> (((x * \<top>) \<sqinter> 1) * z)" by (simp add: inf_comp) also have "\<dots> = x * y \<squnion> x * z" by (cut_tac A, simp) finally show "x * (y \<squnion> z) = x * y \<squnion> x * z" . qed lemma Abs_MonoTran_injective: "mono x \<Longrightarrow> mono y \<Longrightarrow> Abs_MonoTran x = Abs_MonoTran y \<Longrightarrow> x = y" apply (subgoal_tac "Rep_MonoTran (Abs_MonoTran x) = Rep_MonoTran (Abs_MonoTran y)") apply (subst (asm) Abs_MonoTran_inverse, simp) by (subst (asm) Abs_MonoTran_inverse, simp_all) end lemma mbta_MonoTran_disjunctive: "Rep_MonoTran ` disjunctive = Apply.disjunctive" apply (simp add: disjunctive_def Apply.disjunctive_def) apply transfer apply auto proof - fix f :: "'a \<Rightarrow> 'a" and a b assume prem: "\<forall>y. mono y \<longrightarrow> (\<forall>z. mono z \<longrightarrow> f \<circ> y \<squnion> z = (f \<circ> y) \<squnion> (f \<circ> z))" { fix g h :: "'b \<Rightarrow> 'a" assume "mono g" and "mono h" then have "f \<circ> g \<squnion> h = (f \<circ> g) \<squnion> (f \<circ> h)" using prem by blast } note * = this assume "mono f" show "f (a \<squnion> b) = f a \<squnion> f b" (is "?P = ?Q") proof (rule order_antisym) show "?P \<le> ?Q" using * [of "\<lambda>_. a" "\<lambda>_. b"] by (simp add: comp_def fun_eq_iff) next from `mono f` show "?Q \<le> ?P" by (rule Lattices.semilattice_sup_class.mono_sup) qed next fix f :: "'a \<Rightarrow> 'a" assume "\<forall>y z. f (y \<squnion> z) = f y \<squnion> f z" then have *: "\<And>y z. f (y \<squnion> z) = f y \<squnion> f z" by blast show "mono f" proof fix a b :: 'a assume "a \<le> b" then show "f a \<le> f b" unfolding sup.order_iff * [symmetric] by simp qed qed lemma assertion_MonoTran: "assertion = Abs_MonoTran ` assertion_fun" apply (safe) apply (subst assertion_fun_disj_less_one) apply (simp add: image_def) apply (rule_tac x = "Rep_MonoTran x" in bexI) apply (simp add: Rep_MonoTran_inverse) apply safe apply (drule assertion_disjunctive) apply (unfold mbta_MonoTran_disjunctive [THEN sym], simp) apply (simp add: assertion_def less_eq_MonoTran_def one_MonoTran_def Abs_MonoTran_inverse) apply (simp add: assertion_def) by (simp_all add: inf_MonoTran_def less_eq_MonoTran_def times_MonoTran_def dual_MonoTran_def top_MonoTran_def Abs_MonoTran_inverse one_MonoTran_def assertion_fun_dual) context mbt_algebra begin lemma assertion_conjunctive: "x \<in> assertion \<Longrightarrow> x \<in> conjunctive" apply (simp add: conjunctive_def, safe) apply (drule assertion_prop) proof - assume A: "x * \<top> \<sqinter> 1 = x" fix y z::"'a" have "x * (y \<sqinter> z) = (x * \<top> \<sqinter> 1) * (y \<sqinter> z)" by (cut_tac A, simp) also have "\<dots> = (x * \<top>) \<sqinter> (y \<sqinter> z)" by (simp add: inf_comp) also have "\<dots> = ((x * \<top>) \<sqinter> y) \<sqinter> ((x * \<top>) \<sqinter> z)" apply (rule antisym, simp_all, safe) apply (rule_tac y = "y \<sqinter> z" in order_trans) apply (rule inf_le2) apply simp apply (rule_tac y = "y \<sqinter> z" in order_trans) apply (rule inf_le2) apply simp_all apply (simp add: inf_assoc) apply (rule_tac y = " x * \<top> \<sqinter> y" in order_trans) apply (rule inf_le1) apply simp apply (rule_tac y = " x * \<top> \<sqinter> z" in order_trans) apply (rule inf_le2) by simp also have "\<dots> = (((x * \<top>) \<sqinter> 1) * y) \<sqinter> (((x * \<top>) \<sqinter> 1) * z)" by (simp add: inf_comp) also have "\<dots> = (x * y) \<sqinter> (x * z)" by (cut_tac A, simp) finally show "x * (y \<sqinter> z) = (x * y) \<sqinter> (x * z)" . qed lemma dual_assertion_conjunctive: "x \<in> assertion \<Longrightarrow> x ^ o \<in> conjunctive" apply (drule assertion_disjunctive) by (rule dual_disjunctive, simp) lemma dual_assertion_disjunct: "x \<in> assertion \<Longrightarrow> x ^ o \<in> disjunctive" apply (drule assertion_conjunctive) by (rule dual_conjunctive, simp) lemma [simp]: "x \<in> assertion \<Longrightarrow> y \<in> assertion \<Longrightarrow> x \<sqinter> y \<le> x * y" apply (simp add: assertion_def, safe) proof - assume A: "x \<le> 1" assume B: "x * \<top> \<sqinter> x ^ o = x" assume C: "y \<le> 1" assume D: "y * \<top> \<sqinter> y ^ o = y" have "x \<sqinter> y = (x * \<top> \<sqinter> x ^ o) \<sqinter> (y * \<top> \<sqinter> y ^ o)" by (cut_tac B D, simp) also have "\<dots> \<le> (x * \<top>) \<sqinter> (((x^o) * (y * \<top>)) \<sqinter> ((x^o) * (y^o)))" apply (simp, safe) apply (rule_tac y = "x * \<top> \<sqinter> x ^ o" in order_trans) apply (rule inf_le1) apply simp apply (rule_tac y = "y * \<top>" in order_trans) apply (rule_tac y = "y * \<top> \<sqinter> y ^ o" in order_trans) apply (rule inf_le2) apply simp apply (rule gt_one_comp) apply (subst dual_le, simp add: A) apply (rule_tac y = "y ^ o" in order_trans) apply (rule_tac y = "y * \<top> \<sqinter> y ^ o" in order_trans) apply (rule inf_le2) apply simp apply (rule gt_one_comp) by (subst dual_le, simp add: A) also have "... = ((x * \<top>) \<sqinter> (x ^ o)) * ((y * \<top>) \<sqinter> (y ^ o))" apply (cut_tac x = x in dual_assertion_conjunctive) apply (cut_tac A, cut_tac B, simp add: assertion_def) by (simp add: inf_comp conjunctiveD) also have "... = x * y" by (cut_tac B, cut_tac D, simp) finally show "x \<sqinter> y \<le> x * y" . qed lemma [simp]: "x \<in> assertion \<Longrightarrow> x * y \<le> y" by (unfold assertion_def, cut_tac x = x and y = 1 and z = y in le_comp_right, simp_all) lemma [simp]: "x \<in> assertion \<Longrightarrow> y \<in> assertion \<Longrightarrow> x * y \<le> x" apply (subgoal_tac "x * y \<le> (x * \<top>) \<sqinter> (x ^ o)") apply (simp add: assertion_def) apply (simp, safe) apply (rule le_comp, simp) apply (rule_tac y = 1 in order_trans) apply (rule_tac y = y in order_trans) apply simp apply (simp add: assertion_def) by (subst dual_le, simp add: assertion_def) lemma assertion_inf_comp_eq: "x \<in> assertion \<Longrightarrow> y \<in> assertion \<Longrightarrow> x \<sqinter> y = x * y" by (rule antisym, simp_all) lemma one_right_assertion [simp]: "x \<in> assertion \<Longrightarrow> x * 1 = x" apply (drule assertion_prop) proof - assume A: "x * \<top> \<sqinter> 1 = x" have "x * 1 = (x * \<top> \<sqinter> 1) * 1" by (simp add: A) also have "\<dots> = x * \<top> \<sqinter> 1" by (simp add: inf_comp) also have "\<dots> = x" by (simp add: A) finally show ?thesis . qed lemma [simp]: "x \<in> assertion \<Longrightarrow> x \<squnion> 1 = 1" by (rule antisym, simp_all add: assertion_def) lemma [simp]: "x \<in> assertion \<Longrightarrow> 1 \<squnion> x = 1" by (rule antisym, simp_all add: assertion_def) lemma [simp]: "x \<in> assertion \<Longrightarrow> x \<sqinter> 1 = x" by (rule antisym, simp_all add: assertion_def) lemma [simp]: "x \<in> assertion \<Longrightarrow> 1 \<sqinter> x = x" by (rule antisym, simp_all add: assertion_def) lemma [simp]: "x \<in> assertion \<Longrightarrow> x \<le> x * \<top>" by (cut_tac x = 1 and y = \<top> and z = x in le_comp, simp_all) lemma [simp]: "x \<in> assertion \<Longrightarrow> x \<le> 1" by (simp add: assertion_def) definition "neg_assert (x::'a) = (x ^ o * \<bottom>) \<sqinter> 1" lemma sup_uminus[simp]: "x \<in> assertion \<Longrightarrow> x \<squnion> neg_assert x = 1" apply (simp add: neg_assert_def) apply (simp add: sup_inf_distrib) apply (rule antisym, simp_all) apply (unfold assertion_def) apply safe apply (subst dual_le) apply (simp add: dual_sup dual_comp) apply (subst inf_commute) by simp lemma inf_uminus[simp]: "x \<in> assertion \<Longrightarrow> x \<sqinter> neg_assert x = \<bottom>" apply (simp add: neg_assert_def) apply (rule antisym, simp_all) apply (rule_tac y = "x \<sqinter> (x ^ o * \<bottom>)" in order_trans) apply simp apply (rule_tac y = "x ^ o * \<bottom> \<sqinter> 1" in order_trans) apply (rule inf_le2) apply simp apply (rule_tac y = "(x * \<top>) \<sqinter> (x ^ o * \<bottom>)" in order_trans) apply simp apply (rule_tac y = x in order_trans) apply simp_all by (simp add: dual_neg) lemma uminus_assertion[simp]: "x \<in> assertion \<Longrightarrow> neg_assert x \<in> assertion" apply (subst assertion_def) apply (simp add: neg_assert_def) apply (simp add: inf_comp dual_inf dual_comp inf_sup_distrib) apply (subst inf_commute) by (simp add: dual_neg) lemma uminus_uminus [simp]: "x \<in> assertion \<Longrightarrow> neg_assert (neg_assert x) = x" apply (simp add: neg_assert_def) by (simp add: dual_inf dual_comp sup_comp assertion_prop) lemma dual_comp_neg [simp]: "x ^ o * y \<squnion> (neg_assert x) * \<top> = x ^ o * y" apply (simp add: neg_assert_def inf_comp) apply (rule antisym, simp_all) by (rule le_comp, simp) lemma [simp]: "(neg_assert x) ^ o * y \<squnion> x * \<top> = (neg_assert x) ^ o * y" apply (simp add: neg_assert_def inf_comp dual_inf dual_comp sup_comp) by (rule antisym, simp_all) lemma [simp]: " x * \<top> \<squnion> (neg_assert x) ^ o * y= (neg_assert x) ^ o * y" by (simp add: neg_assert_def inf_comp dual_inf dual_comp sup_comp) lemma inf_assertion [simp]: "x \<in> assertion \<Longrightarrow> y \<in> assertion \<Longrightarrow> x \<sqinter> y \<in> assertion" apply (subst assertion_def) apply safe apply (rule_tac y = x in order_trans) apply simp_all apply (simp add: assertion_inf_comp_eq) proof - assume A: "x \<in> assertion" assume B: "y \<in> assertion" have C: "(x * \<top>) \<sqinter> (x ^ o) = x" by (cut_tac A, unfold assertion_def, simp) have D: "(y * \<top>) \<sqinter> (y ^ o) = y" by (cut_tac B, unfold assertion_def, simp) have "x * y = ((x * \<top>) \<sqinter> (x ^ o)) * ((y * \<top>) \<sqinter> (y ^ o))" by (simp add: C D) also have "\<dots> = x * \<top> \<sqinter> ((x ^ o) * ((y * \<top>) \<sqinter> (y ^ o)))" by (simp add: inf_comp) also have "\<dots> = x * \<top> \<sqinter> ((x ^ o) * (y * \<top>)) \<sqinter> ((x ^ o) *(y ^ o))" by (cut_tac A, cut_tac x = x in dual_assertion_conjunctive, simp_all add: conjunctiveD inf_assoc) also have "\<dots> = (((x * \<top>) \<sqinter> (x ^ o)) * (y * \<top>)) \<sqinter> ((x ^ o) *(y ^ o))" by (simp add: inf_comp) also have "\<dots> = (x * y * \<top>) \<sqinter> ((x * y) ^ o)" by (simp add: C mult.assoc dual_comp) finally show "(x * y * \<top>) \<sqinter> ((x * y) ^ o) = x * y" by simp qed lemma comp_assertion [simp]: "x \<in> assertion \<Longrightarrow> y \<in> assertion \<Longrightarrow> x * y \<in> assertion" by (subst assertion_inf_comp_eq [THEN sym], simp_all) lemma sup_assertion [simp]: "x \<in> assertion \<Longrightarrow> y \<in> assertion \<Longrightarrow> x \<squnion> y \<in> assertion" apply (subst assertion_def) apply safe apply (unfold assertion_def) apply simp apply safe proof - assume [simp]: "x \<le> 1" assume [simp]: "y \<le> 1" assume A: "x * \<top> \<sqinter> x ^ o = x" assume B: "y * \<top> \<sqinter> y ^ o = y" have "(y * \<top>) \<sqinter> (x ^ o) \<sqinter> (y ^ o) = (x ^ o) \<sqinter> (y * \<top>) \<sqinter> (y ^ o)" by (simp add: inf_commute) also have "\<dots> = (x ^ o) \<sqinter> ((y * \<top>) \<sqinter> (y ^ o))" by (simp add: inf_assoc) also have "\<dots> = (x ^ o) \<sqinter> y" by (simp add: B) also have "\<dots> = y" apply (rule antisym, simp_all) apply (rule_tac y = 1 in order_trans) apply simp by (subst dual_le, simp) finally have [simp]: "(y * \<top>) \<sqinter> (x ^ o) \<sqinter> (y ^ o) = y" . have "x * \<top> \<sqinter> (x ^ o) \<sqinter> (y ^ o) = x \<sqinter> (y ^ o)" by (simp add: A) also have "\<dots> = x" apply (rule antisym, simp_all) apply (rule_tac y = 1 in order_trans) apply simp by (subst dual_le, simp) finally have [simp]: "x * \<top> \<sqinter> (x ^ o) \<sqinter> (y ^ o) = x" . have "(x \<squnion> y) * \<top> \<sqinter> (x \<squnion> y) ^ o = (x * \<top> \<squnion> y * \<top>) \<sqinter> ((x ^ o) \<sqinter> (y ^ o))" by (simp add: sup_comp dual_sup) also have "\<dots> = x \<squnion> y" by (simp add: inf_sup_distrib inf_assoc [THEN sym]) finally show "(x \<squnion> y) * \<top> \<sqinter> (x \<squnion> y) ^ o = x \<squnion> y" . qed lemma [simp]: "x \<in> assertion \<Longrightarrow> x * x = x" by (simp add: assertion_inf_comp_eq [THEN sym]) lemma [simp]: "x \<in> assertion \<Longrightarrow> (x ^ o) * (x ^ o) = x ^ o" apply (rule dual_eq) by (simp add: dual_comp assertion_inf_comp_eq [THEN sym]) lemma [simp]: "x \<in> assertion \<Longrightarrow> x * (x ^ o) = x" proof - assume A: "x \<in> assertion" have B: "x * \<top> \<sqinter> (x ^ o) = x" by (cut_tac A, unfold assertion_def, simp) have "x * x ^ o = (x * \<top> \<sqinter> (x ^ o)) * x ^ o" by (simp add: B) also have "\<dots> = x * \<top> \<sqinter> (x ^ o)" by (cut_tac A, simp add: inf_comp) also have "\<dots> = x" by (simp add: B) finally show ?thesis . qed lemma [simp]: "x \<in> assertion \<Longrightarrow> (x ^ o) * x = x ^ o" apply (rule dual_eq) by (simp add: dual_comp) lemma [simp]: "\<bottom> \<in> assertion" by (unfold assertion_def, simp) lemma [simp]: "1 \<in> assertion" by (unfold assertion_def, simp) subsection {*Weakest precondition of true*} definition "wpt x = (x * \<top>) \<sqinter> 1" lemma wpt_is_assertion [simp]: "wpt x \<in> assertion" apply (unfold wpt_def assertion_def, safe) apply simp apply (simp add: inf_comp dual_inf dual_comp inf_sup_distrib) apply (rule antisym) by (simp_all add: dual_neg) lemma wpt_comp: "(wpt x) * x = x" apply (simp add: wpt_def inf_comp) apply (rule antisym, simp_all) by (cut_tac x = 1 and y = \<top> and z = x in le_comp, simp_all) lemma wpt_comp_2: "wpt (x * y) = wpt (x * (wpt y))" by (simp add: wpt_def inf_comp mult.assoc) lemma wpt_assertion [simp]: "x \<in> assertion \<Longrightarrow> wpt x = x" by (simp add: wpt_def assertion_prop) lemma wpt_le_assertion: "x \<in> assertion \<Longrightarrow> x * y = y \<Longrightarrow> wpt y \<le> x" apply (simp add: wpt_def) proof - assume A: "x \<in> assertion" assume B: "x * y = y" have "y * \<top> \<sqinter> 1 = x * (y * \<top>) \<sqinter> 1" by (simp add: B mult.assoc [THEN sym]) also have "\<dots> \<le> x * \<top> \<sqinter> 1" apply simp apply (rule_tac y = "x * (y * \<top>)" in order_trans) apply simp_all by (rule le_comp, simp) also have "\<dots> = x" by (cut_tac A, simp add: assertion_prop) finally show "y * \<top> \<sqinter> 1 \<le> x" . qed lemma wpt_choice: "wpt (x \<sqinter> y) = wpt x \<sqinter> wpt y" apply (simp add: wpt_def inf_comp) proof - have "x * \<top> \<sqinter> 1 \<sqinter> (y * \<top> \<sqinter> 1) = x * \<top> \<sqinter> ((y * \<top> \<sqinter> 1) \<sqinter> 1)" apply (subst inf_assoc) by (simp add: inf_commute) also have "... = x * \<top> \<sqinter> (y * \<top> \<sqinter> 1)" by (subst inf_assoc, simp) also have "... = (x * \<top>) \<sqinter> (y * \<top>) \<sqinter> 1" by (subst inf_assoc, simp) finally show "x * \<top> \<sqinter> (y * \<top>) \<sqinter> 1 = x * \<top> \<sqinter> 1 \<sqinter> (y * \<top> \<sqinter> 1)" by simp qed end context lattice begin lemma [simp]: "x \<le> y \<Longrightarrow> x \<sqinter> y = x" by (simp add: inf_absorb1) end context mbt_algebra begin lemma wpt_dual_assertion_comp: "x \<in> assertion \<Longrightarrow> y \<in> assertion \<Longrightarrow> wpt ((x ^ o) * y) = (neg_assert x) \<squnion> y" apply (simp add: wpt_def neg_assert_def) proof - assume A: "x \<in> assertion" assume B: "y \<in> assertion" have C: "((x ^ o) * \<bottom>) \<squnion> 1 = x ^ o" by (rule dual_assertion_prop, rule A) have "x ^ o * y * \<top> \<sqinter> 1 = (((x ^ o) * \<bottom>) \<squnion> 1) * y * \<top> \<sqinter> 1" by (simp add: C) also have "\<dots> = ((x ^ o) * \<bottom> \<squnion> (y * \<top>)) \<sqinter> 1" by (simp add: sup_comp) also have "\<dots> = (((x ^ o) * \<bottom>) \<sqinter> 1) \<squnion> ((y * \<top>) \<sqinter> 1)" by (simp add: inf_sup_distrib2) also have "\<dots> = (((x ^ o) * \<bottom>) \<sqinter> 1) \<squnion> y" by (cut_tac B, drule assertion_prop, simp) finally show "x ^ o * y * \<top> \<sqinter> 1 = (((x ^ o) * \<bottom>) \<sqinter> 1) \<squnion> y" . qed lemma le_comp_left_right: "x \<le> y \<Longrightarrow> u \<le> v \<Longrightarrow> x * u \<le> y * v" apply (rule_tac y = "x * v" in order_trans) apply (rule le_comp, simp) by (rule le_comp_right, simp) lemma wpt_dual_assertion: "x \<in> assertion \<Longrightarrow> wpt (x ^ o) = 1" apply (simp add: wpt_def) apply (rule antisym) apply simp_all apply (cut_tac x = 1 and y = "x ^ o" and u = 1 and v = \<top> in le_comp_left_right) apply simp_all apply (subst dual_le) by simp lemma assertion_commute: "x \<in> assertion \<Longrightarrow> y \<in> conjunctive \<Longrightarrow> y * x = wpt(y * x) * y" apply (simp add: wpt_def) apply (simp add: inf_comp) apply (drule_tac x = y and y = "x * \<top>" and z = 1 in conjunctiveD) by (simp add: mult.assoc [THEN sym] assertion_prop) lemma wpt_mono: "x \<le> y \<Longrightarrow> wpt x \<le> wpt y" apply (simp add: wpt_def) apply (rule_tac y = "x * \<top>" in order_trans, simp_all) by (rule le_comp_right, simp) lemma "a \<in> conjunctive \<Longrightarrow> x * a \<le> a * y \<Longrightarrow> (x ^ \<omega>) * a \<le> a * (y ^ \<omega>)" apply (rule omega_least) apply (simp add: mult.assoc [THEN sym]) apply (rule_tac y = "a * y * y ^ \<omega> \<sqinter> a" in order_trans) apply (simp) apply (rule_tac y = "x * a * y ^ \<omega>" in order_trans, simp_all) apply (rule le_comp_right, simp) apply (simp add: mult.assoc) apply (subst (2) omega_fix) by (simp add: conjunctiveD) lemma [simp]: "x \<le> 1 \<Longrightarrow> y * x \<le> y" by (cut_tac x = x and y = 1 and z = y in le_comp, simp_all) lemma [simp]: "x \<le> x * \<top>" by (cut_tac x = 1 and y = \<top> and z = x in le_comp, simp_all) lemma [simp]: "x * \<bottom> \<le> x" by (cut_tac x = \<bottom> and y = 1 and z = x in le_comp, simp_all) end subsection{*Monotonic Boolean trasformers algebra with post condition statement*} definition "post_fun (p::'a::order) q = (if p \<le> q then (\<top>::'b::{order_bot,order_top}) else \<bottom>)" lemma mono_post_fun [simp]: "mono (post_fun (p::_::{order_bot,order_top}))" apply (simp add: post_fun_def mono_def, safe) apply (subgoal_tac "p \<le> y", simp) apply (rule_tac y = x in order_trans) apply simp_all done lemma post_refin [simp]: "mono S \<Longrightarrow> ((S p)::'a::bounded_lattice) \<sqinter> (post_fun p) x \<le> S x" apply (simp add: le_fun_def assert_fun_def post_fun_def, safe) by (rule_tac f = S in monoD, simp_all) class post_mbt_algebra = mbt_algebra + fixes post :: "'a \<Rightarrow> 'a" assumes post_1: "(post x) * x * \<top> = \<top>" and post_2: "y * x * \<top> \<sqinter> (post x) \<le> y" instantiation MonoTran :: (complete_boolean_algebra) post_mbt_algebra begin lift_definition post_MonoTran :: "'a::complete_boolean_algebra MonoTran \<Rightarrow> 'a::complete_boolean_algebra MonoTran" is "\<lambda>x. post_fun (x \<top>)" by (rule mono_post_fun) instance proof fix x :: "'a MonoTran" show "post x * x * \<top> = \<top>" apply transfer apply (simp add: fun_eq_iff) done fix x y :: "'a MonoTran" show "y * x * \<top> \<sqinter> post x \<le> y" apply transfer apply (simp add: le_fun_def) done qed end subsection{*Complete monotonic Boolean transformers algebra*} class complete_mbt_algebra = post_mbt_algebra + complete_distrib_lattice + assumes Inf_comp: "(Inf X) * z = (INF x : X . (x * z))" instance MonoTran :: (complete_boolean_algebra) complete_mbt_algebra apply intro_classes unfolding INF_def apply transfer apply (simp add: Inf_comp_fun INF_def [symmetric]) done context complete_mbt_algebra begin lemma dual_Inf: "(Inf X) ^ o = (SUP x: X . x ^ o)" apply (rule antisym) apply (subst dual_le, simp) apply (rule Inf_greatest) apply (subst dual_le, simp) apply (rule SUP_upper, simp) apply (rule SUP_least) apply (subst dual_le, simp) by (rule Inf_lower, simp) lemma dual_Sup: "(Sup X) ^ o = (INF x: X . x ^ o)" apply (rule antisym) apply (rule INF_greatest) apply (subst dual_le, simp) apply (rule Sup_upper, simp) apply (subst dual_le, simp) apply (rule Sup_least) apply (subst dual_le, simp) by (rule INF_lower, simp) lemma INF_comp: "(INFIMUM A f) * z = (INF a : A . (f a) * z)" unfolding INF_def Inf_comp apply (subgoal_tac "((\<lambda>x\<Colon>'a. x * z) ` f ` A) = ((\<lambda>a\<Colon>'b. f a * z) ` A)") by auto lemma dual_INF: "(INFIMUM A f) ^ o = (SUP a : A . (f a) ^ o)" unfolding INF_def SUP_def Inf_comp dual_Inf apply (subgoal_tac "(dual ` f ` A) = ((\<lambda>a\<Colon>'b. f a ^ o) ` A)") by auto lemma dual_SUP: "(SUPREMUM A f) ^ o = (INF a : A . (f a) ^ o)" unfolding INF_def dual_Sup SUP_def apply (subgoal_tac "(dual ` f ` A) = ((\<lambda>a\<Colon>'b. f a ^ o) ` A)") by auto lemma Sup_comp: "(Sup X) * z = (SUP x : X . (x * z))" apply (rule dual_eq) by (simp add: dual_comp dual_Sup dual_SUP INF_comp) lemma SUP_comp: "(SUPREMUM A f) * z = (SUP a : A . (f a) * z)" unfolding SUP_def Sup_comp apply (subgoal_tac "((\<lambda>x\<Colon>'a. x * z) ` f ` A) = ((\<lambda>a\<Colon>'b. f a * z) ` A)") by auto lemma Sup_assertion [simp]: "X \<subseteq> assertion \<Longrightarrow> Sup X \<in> assertion" apply (unfold assertion_def) apply safe apply (rule Sup_least) apply blast apply (simp add: Sup_comp dual_Sup SUP_def Sup_inf del: Sup_image_eq) apply (subgoal_tac "((\<lambda>y . y \<sqinter> INFIMUM X dual) ` (\<lambda>x . x * \<top>) ` X) = X") apply simp proof - assume A: "X \<subseteq> {x. x \<le> 1 \<and> x * \<top> \<sqinter> x ^ o = x}" have B [simp]: "!! x . x \<in> X \<Longrightarrow> x * \<top> \<sqinter> (INFIMUM X dual) = x" proof - fix x assume C: "x \<in> X" have "x * \<top> \<sqinter> INFIMUM X dual = x * \<top> \<sqinter> (x ^ o \<sqinter> INFIMUM X dual)" apply (subgoal_tac "INFIMUM X dual = (x ^ o \<sqinter> INFIMUM X dual)", simp) apply (rule antisym, simp_all) by (unfold INF_def, rule Inf_lower, cut_tac C, simp) also have "\<dots> = x \<sqinter> INFIMUM X dual" by (unfold inf_assoc [THEN sym], cut_tac A, cut_tac C, auto) also have "\<dots> = x" apply (rule antisym, simp_all) apply (rule INF_greatest) apply (cut_tac A C) apply (rule_tac y = 1 in order_trans) apply auto[1] by (subst dual_le, auto) finally show "x * \<top> \<sqinter> INFIMUM X dual = x" . qed show "(\<lambda>y. y \<sqinter> INFIMUM X dual) ` (\<lambda>x . x * \<top>) ` X = X" by (unfold image_def, auto) qed lemma Sup_range_assertion [simp]: "(!!w . p w \<in> assertion) \<Longrightarrow> Sup (range p) \<in> assertion" by (rule Sup_assertion, auto) lemma Sup_less_assertion [simp]: "(!!w . p w \<in> assertion) \<Longrightarrow> Sup_less p w \<in> assertion" by (unfold Sup_less_def, rule Sup_assertion, auto) theorem omega_lfp: "x ^ \<omega> * y = lfp (\<lambda> z . (x * z) \<sqinter> y)" apply (rule antisym) apply (rule lfp_greatest) apply (drule omega_least, simp) apply (rule lfp_lowerbound) apply (subst (2) omega_fix) by (simp add: inf_comp mult.assoc) end lemma [simp]: "mono (\<lambda> (t::'a::mbt_algebra) . x * t \<sqinter> y)" apply (simp add: mono_def, safe) apply (rule_tac y = "x * xa" in order_trans, simp) by (rule le_comp, simp) class mbt_algebra_fusion = mbt_algebra + assumes fusion: "(\<forall> t . x * t \<sqinter> y \<sqinter> z \<le> u * (t \<sqinter> z) \<sqinter> v) \<Longrightarrow> (x ^ \<omega>) * y \<sqinter> z \<le> (u ^ \<omega>) * v " lemma "class.mbt_algebra_fusion (1::'a::complete_mbt_algebra) (op *) (op \<sqinter>) (op \<le>) (op <) (op \<squnion>) dual dual_star omega star \<bottom> \<top>" apply unfold_locales apply (cut_tac h = "\<lambda> t . t \<sqinter> z" and f = "\<lambda> t . x * t \<sqinter> y" and g = "\<lambda> t . u * t \<sqinter> v" in weak_fusion) apply (rule inf_Disj) apply simp_all apply (simp add: le_fun_def) by (simp add: omega_lfp) context mbt_algebra_fusion begin lemma omega_pres_conj: "x \<in> conjunctive \<Longrightarrow> x ^ \<omega> \<in> conjunctive" apply (subst omega_star, simp) apply (rule comp_pres_conj) apply (rule assertion_conjunctive, simp) by (rule start_pres_conj, simp) end end
subroutine genpt(xr,ptmin,exact,pt,xjac) implicit none c--- given a random number xr between 0 and 1, generate a transverse c--- momentum pt according to the flag exact: c--- exact=true: generate according to dpt/pt down to ptmin c--- exact=false: generate down to pt=0 with a shape determined by ptmin c--- c--- returns: pt and xjac, the Jacobian of the transformation from pt dpt to dxr logical exact double precision xr,ptmin,pt,xjac,hmin,hmax,h,delh,ptmax include 'energy.f' ptmax=sqrts/2d0 if (exact) then hmin=1d0/ptmax hmax=1d0/ptmin delh=hmax-hmin h=hmin+xr*delh pt=1d0/h xjac=delh/h**3 else pt=2d0*ptmin*ptmax*xr/(2d0*ptmin+ptmax*(1d0-xr)) xjac=pt*ptmax/2d0/ptmin/(2d0*ptmin+ptmax)*(2d0*ptmin+pt)**2 endif return end
State Before: α : Type u inst✝ : Ring α x : α n : ℕ ⊢ (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n State After: α : Type u inst✝ : Ring α x : α n : ℕ this : -((∑ i in range n, x ^ i) * (x - 1)) = -(x ^ n - 1) ⊢ (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n Tactic: have := congr_arg Neg.neg (geom_sum_mul x n) State Before: α : Type u inst✝ : Ring α x : α n : ℕ this : -((∑ i in range n, x ^ i) * (x - 1)) = -(x ^ n - 1) ⊢ (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n State After: α : Type u inst✝ : Ring α x : α n : ℕ this : (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n ⊢ (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n Tactic: rw [neg_sub, ← mul_neg, neg_sub] at this State Before: α : Type u inst✝ : Ring α x : α n : ℕ this : (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n ⊢ (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n State After: no goals Tactic: exact this
% NOTE: % These templates make an effort to conform to the NTU Thesis specifications, % however the specifications can change. We recommend that you verify the % layout of your title page with your thesis advisor and/or the NTU % Libraries before printing your final copy. \title{A Fully Homomorphic Encryption Scheme} \author{Craig Gentry} \department{Department of Electrical Engineering and Computer Science} \degree{Bachelor of Science in Computer Science and Engineering} \degreemonth{September} \degreeyear{2009} \thesisdate{May 18, 2009} \supervisor{Dan Boneh}{Associate Professor} \maketitle \cleardoublepage \setcounter{savepage}{\thepage} \begin{abstractpage} \input{abstract} \end{abstractpage} \cleardoublepage \section*{Acknowledgments} This is the acknowledgements section. You should replace this with your own acknowledgements.
The item The Jewish war, by Josephus ; translated with an introd. by G. A. Williamson represents a specific, individual, material embodiment of a distinct intellectual or artistic creation found in University of Michigan Dearborn. Harmondsworth, Middlesex, Penguin Books, 1970.
module FDFD using Peacock include("solver_fdm.jl") export Solver, solve, FDFDBasis end
##### Chapter 2: Managing and Understanding Data ------------------- ##### R data structures -------------------- ## Vectors ----- # create vectors of data for three medical patients subject_name <- c("John Doe", "Jane Doe", "Steve Graves") temperature <- c(98.1, 98.6, 101.4) flu_status <- c(FALSE, FALSE, TRUE) # access the second element in body temperature vector temperature[2] ## examples of accessing items in vector # include items in the range 2 to 3 temperature[2:3] # exclude item 2 using the minus sign temperature[-2] # use a vector to indicate whether to include item temperature[c(TRUE, TRUE, FALSE)] ## Factors ----- # add gender factor gender <- factor(c("MALE", "FEMALE", "MALE")) gender # add blood type factor blood <- factor(c("O", "AB", "A"), levels = c("A", "B", "AB", "O")) blood # add ordered factor symptoms <- factor(c("SEVERE", "MILD", "MODERATE"), levels = c("MILD", "MODERATE", "SEVERE"), ordered = TRUE) symptoms # check for symptoms greater than moderate symptoms > "MODERATE" ## Lists ----- # display information for a patient subject_name[1] temperature[1] flu_status[1] gender[1] blood[1] symptoms[1] # create list for a patient subject1 <- list(fullname = subject_name[1], temperature = temperature[1], flu_status = flu_status[1], gender = gender[1], blood = blood[1], symptoms = symptoms[1]) # display the patient subject1 ## methods for accessing a list # get a single list value by position (returns a sub-list) subject1[2] # get a single list value by position (returns a numeric vector) subject1[[2]] # get a single list value by name subject1$temperature # get several list items by specifying a vector of names subject1[c("temperature", "flu_status")] ## access a list like a vector # get values 2 and 3 subject1[2:3] ## Data frames ----- # create a data frame from medical patient data pt_data <- data.frame(subject_name, temperature, flu_status, gender, blood, symptoms, stringsAsFactors = FALSE) # display the data frame pt_data ## accessing a data frame # get a single column pt_data$subject_name # get several columns by specifying a vector of names pt_data[c("temperature", "flu_status")] # this is the same as above, extracting temperature and flu_status pt_data[2:3] # accessing by row and column pt_data[1, 2] # accessing several rows and several columns using vectors pt_data[c(1, 3), c(2, 4)] ## Leave a row or column blank to extract all rows or columns # column 1, all rows pt_data[, 1] # row 1, all columns pt_data[1, ] # all rows and all columns pt_data[ , ] # the following are equivalent pt_data[c(1, 3), c("temperature", "gender")] pt_data[-2, c(-1, -3, -5, -6)] # creating a Celsius temperature column pt_data$temp_c <- (pt_data$temperature - 32) * (5 / 9) # comparing before and after pt_data[c("temperature", "temp_c")] ## Matrixes ----- # create a 2x2 matrix m <- matrix(c(1, 2, 3, 4), nrow = 2) m # equivalent to the above m <- matrix(c(1, 2, 3, 4), ncol = 2) m # create a 2x3 matrix m <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2) m # create a 3x2 matrix m <- matrix(c(1, 2, 3, 4, 5, 6), ncol = 2) m # extract values from matrixes m[1, 1] m[3, 2] # extract rows m[1, ] # extract columns m[, 1] ##### Managing data with R ------------ ## saving, loading, and removing R data structures # show all data structures in memory ls() # remove the m and subject1 objects rm(m, subject1) ls() rm(list=ls()) ##### Exploring and understanding data -------------------- ## data exploration example using used car data usedcars <- read.csv("usedcars.csv", stringsAsFactors = FALSE) # get structure of used car data str(usedcars) ## Exploring numeric variables ----- # summarize numeric variables summary(usedcars$year) summary(usedcars[c("price", "mileage")]) # calculate the mean income (36000 + 44000 + 56000) / 3 mean(c(36000, 44000, 56000)) # the median income median(c(36000, 44000, 56000)) # the min/max of used car prices range(usedcars$price) # the difference of the range diff(range(usedcars$price)) # IQR for used car prices IQR(usedcars$price) # use quantile to calculate five-number summary quantile(usedcars$price) # the 99th percentile quantile(usedcars$price, probs = c(0.01, 0.99)) # quintiles quantile(usedcars$price, seq(from = 0, to = 1, by = 0.20)) # boxplot of used car prices and mileage boxplot(usedcars$price, main="Boxplot of Used Car Prices", ylab="Price ($)") boxplot(usedcars$mileage, main="Boxplot of Used Car Mileage", ylab="Odometer (mi.)") # histograms of used car prices and mileage hist(usedcars$price, main = "Histogram of Used Car Prices", xlab = "Price ($)") hist(usedcars$mileage, main = "Histogram of Used Car Mileage", xlab = "Odometer (mi.)") # variance and standard deviation of the used car data var(usedcars$price) sd(usedcars$price) var(usedcars$mileage) sd(usedcars$mileage) ## Exploring numeric variables ----- # one-way tables for the used car data table(usedcars$year) table(usedcars$model) table(usedcars$color) # compute table proportions model_table <- table(usedcars$model) prop.table(model_table) # round the data color_table <- table(usedcars$color) color_pct <- prop.table(color_table) * 100 round(color_pct, digits = 1) ## Exploring relationships between variables ----- # scatterplot of price vs. mileage plot(x = usedcars$mileage, y = usedcars$price, main = "Scatterplot of Price vs. Mileage", xlab = "Used Car Odometer (mi.)", ylab = "Used Car Price ($)") # new variable indicating conservative colors usedcars$conservative <- usedcars$color %in% c("Black", "Gray", "Silver", "White") # checking our variable table(usedcars$conservative) # Crosstab of conservative by model library(gmodels) CrossTable(x = usedcars$model, y = usedcars$conservative)
subroutine srcfil(lundia ,filsrc ,error ,nsrc ,mnksrc , & & namsrc ,disint ,gdp ) !----- GPL --------------------------------------------------------------------- ! ! Copyright (C) Stichting Deltares, 2011-2016. ! ! This program is free software: you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation version 3. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License ! along with this program. If not, see <http://www.gnu.org/licenses/>. ! ! contact: [email protected] ! Stichting Deltares ! P.O. Box 177 ! 2600 MH Delft, The Netherlands ! ! All indications and logos of, and references to, "Delft3D" and "Deltares" ! are registered trademarks of Stichting Deltares, and remain the property of ! Stichting Deltares. All rights reserved. ! !------------------------------------------------------------------------------- ! $Id: srcfil.f90 5717 2016-01-12 11:35:24Z mourits $ ! $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/tags/6686/src/engines_gpl/flow2d3d/packages/io/src/input/srcfil.f90 $ !!--description----------------------------------------------------------------- ! ! Function: Reads the discharge location definitions from the ! attribute file ! Method used: ! !!--pseudo code and references-------------------------------------------------- ! NONE !!--declarations---------------------------------------------------------------- use precision use globaldata use string_module use system_utils, only: exifil ! implicit none ! type(globdat),target :: gdp ! ! The following list of pointer parameters is used to point inside the gdp structure ! real(fp), pointer :: maxTOutlet ! ! Global variables ! integer :: lundia ! Description and declaration in inout.igs integer , intent(in) :: nsrc ! Description and declaration in esm_alloc_int.f90 integer , dimension(7, nsrc), intent(out) :: mnksrc ! Description and declaration in esm_alloc_int.f90 logical :: error ! Flag=TRUE if an error is encountered character(*) :: filsrc ! Name of the relevant file character(1) , dimension(nsrc) :: disint ! Description and declaration in esm_alloc_char.f90 character(20), dimension(nsrc) :: namsrc ! Description and declaration in esm_alloc_char.f90 ! ! Local variables ! integer :: ibeg ! Begin position in the RECORD from where the search for data/record is started integer :: idef ! Help var. containing default va- lue(s) for integer variable integer :: iend ! Last position in the RECORD when the searched data/record is finished integer :: ier ! = 0 -> end of record encountered = 1 -> real value found = -1 -> length or number of data is larger then specified by the calling routine integer :: iocond ! IO status for reading integer :: lenc integer :: lfile ! Number of non blank characters of file name integer :: lr132 ! Standard length of a record in the attribute file = 132 integer :: luntmp ! Temporary file unit integer :: n integer, external :: newlun integer , dimension(3) :: ival ! Help array (integer) where the data, recently read from the MD-file, are stored temporarily real(fp) :: rdef real(fp), dimension(1) :: rval logical :: qType ! True when there is at least one Q-type powerstation present character(1) :: cdefi ! Default value for interpolotion (Y) character(1) :: chulpi ! Help string for reading interpolation character(20) :: cdefn ! Default value when CVAR not found character(132) :: rec132 ! Standard rec. length in an attribute file (132) character(300) :: message ! !! executable statements ------------------------------------------------------- ! maxTOutlet => gdp%gddischarge%maxTOutlet ! ! initialize local parameters ! cdefn = ' ' cdefi = 'Y' chulpi = cdefi idef = 0 rdef = -999.0_fp lr132 = 132 lenc = 1 qType = .false. ! ! test file existence ! call remove_leading_spaces(filsrc ,lfile ) ! error = .not.exifil(filsrc, lundia) if (error) goto 9999 ! ! open formatted file, if not formatted IOCOND <> 0 ! luntmp = newlun(gdp) open (luntmp, file = filsrc(:lfile), form = 'formatted', status = 'old', & & iostat = iocond) if (iocond /= 0) then error = .true. call prterr(lundia ,'G007' ,filsrc(:lfile) ) goto 9999 endif ! ! freeformatted file, skip lines starting with a '*' ! call skipstarlines(luntmp ) ! ! freeformatted file, read input and test iocond ! do n = 1, nsrc read (luntmp, '(a)', iostat = iocond) rec132 if (iocond /= 0) then if (iocond < 0) then call prterr(lundia ,'G006' ,filsrc(:lfile) ) else call prterr(lundia ,'G007' ,filsrc(:lfile) ) endif error = .true. exit endif ! ! define discharge location name ! namsrc(n) = rec132(:20) ! ! there must be a name defined !! ! if (namsrc(n) == cdefn) then error = .true. call prterr(lundia ,'V012' ,' ' ) exit endif ! ! read DISINT from record, default value not allowed ! lenc = 1 ibeg = 21 call read1c(rec132 ,lr132 ,ibeg ,iend ,chulpi , & & lenc ,ier ) if (ier <= 0) then call prterr(lundia ,'G007' ,filsrc(1:lfile) ) disint(n) = cdefi error = .true. exit endif disint(n) = chulpi ! ! test for interpolation option is 'Y' ! if (disint(n) == 'n') then disint(n) = 'N' endif if (disint(n) /= 'N') then disint(n) = cdefi(:1) endif ! ! read ival (3) from record, default value allowed ! ibeg = iend + 1 call readni(rec132 ,lr132 ,ibeg ,iend ,3 , & & ival ,idef ,ier ) if (ier <= 0) then call prterr(lundia ,'G007' ,filsrc(1:lfile) ) mnksrc(1, n) = idef mnksrc(2, n) = idef mnksrc(3, n) = idef mnksrc(4, n) = idef mnksrc(5, n) = idef mnksrc(6, n) = idef error = .true. exit endif ! ! discharge location is defined in M,N,K coordinates ! mnksrc(1, n) = ival(1) mnksrc(2, n) = ival(2) mnksrc(3, n) = ival(3) mnksrc(4, n) = ival(1) mnksrc(5, n) = ival(2) mnksrc(6, n) = ival(3) ! ! discharge location is walking discharge or power station ! lenc = 1 ibeg = iend + 1 call read1c(rec132 ,lr132 ,ibeg ,iend ,chulpi , & & lenc ,ier ) ! ! if error go on (probably Normal discharge point) ! if (ier <= 0) then chulpi = 'N' endif mnksrc(7, n) = 0 ! ! test if the discharge is walking discharge, powerstation or culvert ! if (chulpi=='w' .or. chulpi=='W') mnksrc(7, n) = 1 if (chulpi=='p' .or. chulpi=='P' .or. & & chulpi=='q' .or. chulpi=='Q' .or. & & chulpi=='c' .or. chulpi=='C' .or. & & chulpi=='d' .or. chulpi=='D' .or. & & chulpi=='e' .or. chulpi=='E' .or. & & chulpi=='f' .or. chulpi=='F' .or. & & chulpi=='u' .or. chulpi=='U') then ! ! read ival (3) from record, default value allowed ! ibeg = iend + 1 call readni(rec132 ,lr132 ,ibeg ,iend ,3 , & & ival ,idef ,ier ) if (ier <= 0) then write(message,'(2a)') 'Missing second set of coordinates in file ', trim(filsrc) call prterr(lundia, 'G007', trim(message)) mnksrc(4, n) = idef mnksrc(5, n) = idef mnksrc(6, n) = idef error = .true. exit endif mnksrc(4, n) = ival(1) mnksrc(5, n) = ival(2) mnksrc(6, n) = ival(3) if (chulpi=='p' .or. chulpi=='P') mnksrc(7, n) = 2 if (chulpi=='c' .or. chulpi=='C') mnksrc(7, n) = 3 if (chulpi=='e' .or. chulpi=='E') mnksrc(7, n) = 4 if (chulpi=='d' .or. chulpi=='D') mnksrc(7, n) = 5 if (chulpi=='q' .or. chulpi=='Q') then qType = .true. mnksrc(7, n) = 6 ibeg = iend + 1 call readnr(rec132 ,lr132 ,ibeg ,iend ,1 , & & rval ,rdef ,ier ) if (ier <= 0) then write(message,'(2a)') 'Missing regular temperature difference for Q-type power station in file ', trim(filsrc) call prterr(lundia, 'G007', trim(message)) error = .true. exit else maxTOutlet = rval(1) endif endif if (chulpi=='u' .or. chulpi=='U') mnksrc(7, n) = 7 if (chulpi=='f' .or. chulpi=='F') mnksrc(7, n) = 8 endif enddo ! ! close file ! close (luntmp) 9999 continue if (qType) then ! ! Allocate array for q-type powerstations ! if (associated(gdp%gddischarge%capacity)) deallocate(gdp%gddischarge%capacity, stat=ier) allocate (gdp%gddischarge%capacity(nsrc) , stat=ier) if (ier /= 0) then call prterr(lundia, 'U021', 'srcfil: memory alloc error for capacity array') call d3stop(1, gdp) endif gdp%gddischarge%capacity = 0.0_fp endif end subroutine srcfil
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 16 15:59:45 2020 @author: elijahsheridan """ import numpy as np import opt_helper as opt import scipy.optimize as op #import matplotlib.pyplot as plt def exp(x, p0, p1): return np.exp(p0 + p1 * x) def poly(x, p0, p1, p2, p3, p4): return p0 + p1 * x**-1 + p2 * x**-2 + p3 * x**-3 + p4 * x**-4 def poly2(x, p0, p1): return p0 + p1 * x**-4 lambdas = [1 + 0.5 * i for i in range(7)] cross_secs_1MeV = [10.16, 2.43, 1.083, 0.6791, 0.4453, 0.3285, 0.2555] cross_secs_1GeV = [10.09, 2.291, 1.068, 0.6473, 0.4395, 0.32, 0.2446] cross_secs_100GeV = [8.523, 1.777, 0.8011, 0.4779, 0.3227, 0.2344, 0.1788] cross_secs = [cross_secs_1MeV, cross_secs_1GeV, cross_secs_100GeV] #scalings = np.array([[cross_sec[0]/10.16] + [ # cs/cross_sec[0] for cs in cross_sec[1:]] for cross_sec in cross_secs]) # only using one significance, so need to divide EVERYTHING # by the cross sec for that sig? this is an error to be fixed I think scalings = np.array([[cs/cross_sec[0] for cs in cross_sec] for cross_sec in cross_secs]) ratio = 0.25 path = ('../optimization/second_sdEta_mjj_optimization/lumi_and_kin_plots/' + 'four_cuts_lum3000/Output/HTML/MadAnalysis5job_0/index.html') signal, _, bg, __ = opt.sig_and_bg_from_html(path) signals = signal * scalings sigs = signals / np.sqrt(signals + bg + (bg * ratio)**2) print(np.transpose(sigs)) poly_result_1MeV = op.curve_fit(poly, lambdas, sigs[0]) poly_result_1GeV = op.curve_fit(poly, lambdas, sigs[1]) poly_result_100GeV = op.curve_fit(poly, lambdas, sigs[2]) results = [poly_result_1MeV, poly_result_1GeV, poly_result_100GeV] return_lines = [] for result in results: params = result[0] return_line = 'return ({} + ({}) * L**-1 + ({}) * L**-2 + ({}) * L**-3 + ({}) * L**-4)'.format(*params) return_lines.append(return_line) for return_line in return_lines: print(return_line) #print(sigs.shape) #print(sigs) #exp_result = op.curve_fit(exp, lambdas, sigs[0]) #poly_result = op.curve_fit(poly, lambdas, sigs) #poly2_result = op.curve_fit(poly2, lambdas, sigs) #poly_result_1MeV = op.curve_fit(poly, lambdas, sigs[0]) #poly_result_1GeV = op.curve_fit(poly, lambdas, sigs[1]) #poly_result_100GeV = op.curve_fit(poly, lambdas, sigs[2]) #poly_result_1MeV = op.curve_fit(poly, lambdas, signals[0]) #poly_result_1GeV = op.curve_fit(poly, lambdas, signals[1]) #poly_result_100GeV = op.curve_fit(poly, lambdas, signals[2]) # #print(signals) #print(bg) #print(poly_result_1MeV[0]) #print(poly_result_1GeV[0]) #print(poly_result_100GeV[0]) #poly_fits = np.array([ # [poly(l, poly_result[0][0], poly_result[0][1], poly_result[0][2], # poly_result[0][3], poly_result[0][4]) for l in lambdas] # for poly_result in [poly_result_1MeV, poly_result_1GeV, # poly_result_100GeV]]) # #r_sq = [1 - (np.sum((sig - fit)**2)) / (np.sum((sig - np.mean(sig))**2)) # for sig, fit in zip(signals, poly_fits)] # #print(r_sq) #plt.plot(lambdas, poly_fits[0], label='Fit 1 MeV') #plt.plot(lambdas, signals[0], label='Real 1 MeV') #plt.legend() # #exp_fit = [exp(l, exp_result[0][0], exp_result[0][1]) for l in lambdas] #poly_fit = [poly(l, poly_result[0][0], poly_result[0][1], poly_result[0][2], # poly_result[0][3], poly_result[0][4]) for l in lambdas] #poly2_fit = [poly2(l, poly2_result[0][0], poly2_result[0][1]) for l in lambdas] # ##print(exp_result[1]) ##print(poly_result[1]) ##print(poly2_result[1]) # #plt.plot(lambdas, exp_fit, label='exp') #plt.plot(lambdas, poly_fit, label='poly') #plt.plot(lambdas, poly2_fit, label='poly2') #plt.plot(lambdas, sigs, label='real') #plt.legend() #fig = plt.gcf() #fig.set_size_inches(12, 8) # #r_sq = [1 - (np.sum((sigs - fit)**2))/(np.sum((sigs - np.mean(sigs))**2)) # for fit in [exp_fit, poly_fit, poly2_fit]] # #print(r_sq) #xs = lambdas #y1 = [axion_f1_signal(x) / np.sqrt(axion_f1_signal(x) + bg + (0.25 * bg)**2) # for x in xs] #y2 = [axion_f1(x) for x in xs] #plt.plot(xs, y1) #plt.plot(xs, y2) #print(y1) #print(y2)
Alphitonia blossom Red Ashis derived from the Greek αλφιτον (alphiton), barley meal, and refers to the dry, mealy quality of the mesocarp in the fruits; excelsa is from the Latin excelsus, elevated, high. The Red Ash grows in eucalypt forests, eucalypt and acacia savannas, gallery forests and rainforests of NSW from Mt Dromedary northwards along the coast through Queensland and the Northern Territory, into the northwest of Western Australia. It is also found in New Guinea and on some of the Pacific Islands. It is a small to medium tree, up to about 20 m tall, is a natural colonizer or pioneer in a huge range of conditions, and can sometimes regenerate from underground stems. It has a spreading, shade-producing habit where it is able to grow into a large tree, and has an overall greyish green appearance. detail of blossom blossom, fruits formingThe trunk and larger branches have fissured grey bark, with smaller branches having smoother grey or white bark. Lichens are often found on older specimens. The entire, simple, alternate leaves are 5 – 14 cm in length and 2 – 5 cm in width, elliptic in shape, and are dark glossy green above and silvery with fine hairs underneath, making an attractive contrast on windy days. Venation is prominent and yellowish below, and sunken above. In the dry season, many of the leaves are shed, and the remaining leaves hang vertically to reduce water loss. The tree bears small greenish white 5-petalled flowers in late autumn and early winter, followed by globular dark fruit about 1.5 cm in diameter, with a raised ring around the middle. The powdery red flesh of the drupe covers 2 hard cells, each containing a single seed. Seeds can persist on the branches for several months. When young shoots are bruised, they give off a typical odour of sarsaparilla. The flowers are fragrant in the evening. fruits ripe fruits When grown under cultivation, this is quite a quick-growing tree, and can have high visual appeal, especially as a street tree. Its tough timber is light brown to reddish in colour, and has been used in boat building and cabinet-making, particularly in Samoa, where the tree is known as toi. mature fruits Aborigines used the crushed leaves and berries as a fish poison. For medical use, they crushed the leaves into a paste, mixed that with water and applied it as a head bath to reduce headaches and treat sore eyes. Infusions of the bark and root were rubbed on the body to reduce muscular ache, and gargled to cure toothache. The leaves contain saponin, and so when crushed can be lathered to produce a bush soap. In Borneo, the sap from under the bark is collected, and used to treat skin diseases by mixing it in the bath water.
If $k > 0$ and $n \geq 1$, then $k$-th root of $n$ is the largest integer $x$ such that $x^k \leq n$.
[STATEMENT] lemma map_disjI: "dom h\<^sub>0 \<inter> dom h\<^sub>1 = {} \<Longrightarrow> h\<^sub>0 \<bottom> h\<^sub>1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. dom h\<^sub>0 \<inter> dom h\<^sub>1 = {} \<Longrightarrow> h\<^sub>0 \<bottom> h\<^sub>1 [PROOF STEP] by (simp add: map_disj_def)
\section{Problem definition} \epigraph{\textbf{mar - ket - place} 1. An open square or place in a town where markets or public sales are held. 2. The world of trade or economic activity.}{Merriam-Webster} To combat the issues associated with centralised marketplaces, Tsukiji aims to be a fully decentralised marketplace. A marketplace is a place where public sales are held. For our purposes, a marketplace is a place where people can place bids or asks. A bid is placed when a buyer wants to buy goods for a set price. An ask is placed when a seller wants to sell goods for a set price. Using the example of BitTorrent communities, a transaction would occur as follows: a seller places an "ask", wanting to sell 500 MBit for €3. An interested buyer sees the ask and requests a trade to be made. The buyer and seller exchange information necessary for the transaction to occur (e.g. bank account numbers). A trade is made and the original ask is taken down. A similar transaction occurs when a "bid" is placed. Current marketplaces are centralised. Usually, this type of centralised system follows the client-server model, where one server serves a large amount of clients. In this model, information passes through one central point. This means that if this central point fails, the entire marketplace is shut down. A decentralised system operates without such a single point. Instead of a central server connected to several users, peers are connected to each other. This follows the peer-to-peer model. If a single peer fails, this might impact the marketplace, but it will not shut it down. For a network of such peers to exist, peers first have to find each other. Peer discovery is generally done by exchanging information about other peers. When a peer first signs on, it knows of no other peers. We can bootstrap its network by having them connect to a predefined set of super peers, who are known to be well connected. From there, they can exchange information about other peers.
corollary isomorphisms_UNIV_UNIV: assumes "DIM('M) = DIM('N)" obtains f::"'M::euclidean_space \<Rightarrow>'N::euclidean_space" and g where "linear f" "linear g" "\<And>x. norm(f x) = norm x" "\<And>y. norm(g y) = norm y" "\<And>x. g (f x) = x" "\<And>y. f(g y) = y"
State Before: x✝ y✝ x y : ℝ ⊢ Real.le x y ↔ x < y ∨ x = y State After: no goals Tactic: rw [le_def]
struct DefaultInit <: DiffEqBase.DAEInitializationAlgorithm end struct NoInit <: DiffEqBase.DAEInitializationAlgorithm end struct ShampineCollocationInit{T} <: DiffEqBase.DAEInitializationAlgorithm initdt::T end ShampineCollocationInit() = ShampineCollocationInit(nothing) struct BrownFullBasicInit{T} <: DiffEqBase.DAEInitializationAlgorithm abstol::T end BrownFullBasicInit() = BrownFullBasicInit(1e-10) ## Notes #= differential_vars = [any(!iszero,x) for x in eachcol(M)] A column should be zero for an algebraic variable, since that means that the derivative term doesn't show up in any equations (i.e. is an algebraic variable). The rows are not necessarily non-zero, for example a flux condition between two differential variables. But if it's a condition that doesn't involve the algebraic variable, then the system is not Index 1! =# ## Expansion function DiffEqBase.initialize_dae!(integrator::ODEIntegrator, initializealg = integrator.initializealg) _initialize_dae!(integrator, integrator.sol.prob, initializealg, Val(DiffEqBase.isinplace(integrator.sol.prob))) end ## Default algorithms function _initialize_dae!(integrator, prob::ODEProblem, alg::DefaultInit, x::Val{true}) _initialize_dae!(integrator, prob, BrownFullBasicInit(), x) end function _initialize_dae!(integrator, prob::ODEProblem, alg::DefaultInit, x::Val{false}) _initialize_dae!(integrator, prob, BrownFullBasicInit(), x) end function _initialize_dae!(integrator, prob::DAEProblem, alg::DefaultInit, x::Val{false}) if prob.differential_vars === nothing _initialize_dae!(integrator, prob, ShampineCollocationInit(), x) else _initialize_dae!(integrator, prob, BrownFullBasicInit(), x) end end function _initialize_dae!(integrator, prob::DAEProblem, alg::DefaultInit, x::Val{true}) if prob.differential_vars === nothing _initialize_dae!(integrator, prob, ShampineCollocationInit(), x) else _initialize_dae!(integrator, prob, BrownFullBasicInit(), x) end end ## NoInit function _initialize_dae!(integrator, prob::ODEProblem, alg::NoInit, x::Val{true}) end function _initialize_dae!(integrator, prob::ODEProblem, alg::NoInit, x::Val{false}) end function _initialize_dae!(integrator, prob::DAEProblem, alg::NoInit, x::Val{false}) end function _initialize_dae!(integrator, prob::DAEProblem, alg::NoInit, x::Val{true}) end ## ShampineCollocationInit #= The method: du = (u-u0)/h Solve for `u` =# function _initialize_dae!(integrator, prob::ODEProblem, alg::ShampineCollocationInit, ::Val{true}) @unpack p, t, f = integrator M = integrator.f.mass_matrix dtmax = integrator.opts.dtmax tmp = first(get_tmp_cache(integrator)) u0 = integrator.u dt = t != 0 ? min(t/1000,dtmax) : dtmax # Haven't implemented norm reduction nlequation! = function (out,u) update_coefficients!(M,u,p,t) #M * (u-u0)/dt - f(u,p,t) @. tmp = (u - u0)/dt mul!(out,M,tmp) f(tmp,u,p,t) out .-= tmp nothing end update_coefficients!(M,u0,p,t) algebraic_vars = [all(iszero,x) for x in eachcol(M)] algebraic_eqs = [all(iszero,x) for x in eachrow(M)] (iszero(algebraic_vars) || iszero(algebraic_eqs)) && return f(tmp,u0,p,t) tmp .= algebraic_eqs .* tmp integrator.opts.internalnorm(tmp,t) <= integrator.opts.abstol && return integrator.u .= nlsolve(nlequation!, u0).zero recursivecopy!(integrator.uprev,integrator.u) if alg_extrapolates(integrator.alg) recursivecopy!(integrator.uprev2,integrator.uprev) end return nothing end function _initialize_dae!(integrator, prob::ODEProblem, alg::ShampineCollocationInit, ::Val{false}) @unpack p, t, f = integrator u0 = integrator.u M = integrator.f.mass_matrix dtmax = integrator.opts.dtmax dt = t != 0 ? min(t/1000,dtmax/10) : dtmax # Haven't implemented norm reduction update_coefficients!(M,u0,p,t) algebraic_vars = [all(iszero,x) for x in eachcol(M)] algebraic_eqs = [all(iszero,x) for x in eachrow(M)] (iszero(algebraic_vars) || iszero(algebraic_eqs)) && return du = f(u0,p,t) resid = du[algebraic_eqs] integrator.opts.internalnorm(resid,t) <= integrator.opts.abstol && return nlequation_oop = function (u) update_coefficients!(M,u,p,t) M * (u-u0)/dt - f(u,p,t) end nlequation! = (out,u) -> out .= nlequation_oop(u) integrator.u = nlsolve(nlequation!, u0).zero integrator.uprev = integrator.u if alg_extrapolates(integrator.alg) integrator.uprev2 = integrator.uprev end return end function _initialize_dae!(integrator, prob::DAEProblem, alg::ShampineCollocationInit, ::Val{true}) @unpack p, t, f = integrator u0 = integrator.u dtmax = integrator.opts.dtmax tmp = get_tmp_cache(integrator)[1] resid = get_tmp_cache(integrator)[2] dt = t != 0 ? min(t/1000,dtmax) : dtmax # Haven't implemented norm reduction nlequation! = function (out,u) #M * (u-u0)/dt - f(u,p,t) @. tmp = (u - u0)/dt f(out,tmp,u,p,t) nothing end nlequation!(tmp,u0) f(resid,integrator.du,u0,p,t) integrator.opts.internalnorm(resid,t) <= integrator.opts.abstol && return integrator.u .= nlsolve(nlequation!, u0).zero recursivecopy!(integrator.uprev,integrator.u) if alg_extrapolates(integrator.alg) recursivecopy!(integrator.uprev2,integrator.uprev) end return end function _initialize_dae!(integrator, prob::DAEProblem, alg::ShampineCollocationInit, ::Val{false}) @unpack p, t, f = integrator u0 = integrator.u dtmax = integrator.opts.dtmax dt = t != 0 ? min(t/1000,dtmax/10) : dtmax # Haven't implemented norm reduction nlequation_oop = function (u) f((u-u0)/dt,u,p,t) end nlequation! = (out,u) -> out .= nlequation_oop(u) resid = f(integrator.du,u0,p,t) integrator.opts.internalnorm(resid,t) <= integrator.opts.abstol && return integrator.u = nlsolve(nlequation!, u0).zero integrator.uprev = integrator.u if alg_extrapolates(integrator.alg) integrator.uprev2 = integrator.uprev end end ## BrownFullBasic #= The method: Keep differential variables constant Solve for the algebraic variables =# function _initialize_dae!(integrator, prob::ODEProblem, alg::BrownFullBasicInit, ::Val{true}) @unpack p, t, f = integrator u = integrator.u M = integrator.f.mass_matrix update_coefficients!(M,u,p,t) algebraic_vars = [all(iszero,x) for x in eachcol(M)] algebraic_eqs = [all(iszero,x) for x in eachrow(M)] (iszero(algebraic_vars) || iszero(algebraic_eqs)) && return tmp = get_tmp_cache(integrator)[1] f(tmp,u,p,t) tmp .= algebraic_eqs .* tmp integrator.opts.internalnorm(tmp,t) <= alg.abstol && return alg_u = @view u[algebraic_vars] nlequation = (out, x) -> begin alg_u .= x f(tmp, u, p, t) out .= @view tmp[algebraic_eqs] end r = nlsolve(nlequation, u[algebraic_vars]) alg_u .= r.zero recursivecopy!(integrator.uprev,integrator.u) if alg_extrapolates(integrator.alg) recursivecopy!(integrator.uprev2,integrator.uprev) end return end function _initialize_dae!(integrator, prob::ODEProblem, alg::BrownFullBasicInit, ::Val{false}) @unpack p, t, f = integrator u0 = integrator.u M = integrator.f.mass_matrix update_coefficients!(M,u0,p,t) algebraic_vars = [all(iszero,x) for x in eachcol(M)] algebraic_eqs = [all(iszero,x) for x in eachrow(M)] (iszero(algebraic_vars) || iszero(algebraic_eqs)) && return du = f(u0,p,t) resid = du[algebraic_eqs] integrator.opts.internalnorm(resid,t) <= alg.abstol && return if u0 isa Number # This doesn't fix static arrays! u = [u0] else u = u0 end alg_u = @view u[algebraic_vars] nlequation = (out,x) -> begin alg_u .= x du = f(u,p,t) out .= @view du[algebraic_eqs] end r = nlsolve(nlequation, u0[algebraic_vars]) alg_u .= r.zero if u0 isa Number # This doesn't fix static arrays! integrator.u = first(u) else integrator.u = u end integrator.uprev = integrator.u if alg_extrapolates(integrator.alg) integrator.uprev2 = integrator.uprev end return end function _initialize_dae!(integrator, prob::DAEProblem, alg::BrownFullBasicInit, ::Val{true}) @unpack p, t, f = integrator differential_vars = prob.differential_vars u = integrator.u du = integrator.du tmp = get_tmp_cache(integrator)[1] f(tmp, du, u, p, t) if integrator.opts.internalnorm(tmp,t) <= alg.abstol return elseif differential_vars === nothing error("differential_vars must be set for DAE initialization to occur. Either set consistent initial conditions, differential_vars, or use a different initialization algorithm.") end nlequation = (out, x) -> begin @. du = ifelse(differential_vars,x,du) @. u = ifelse(differential_vars,u,x) f(out, du, u, p, t) end r = nlsolve(nlequation, ifelse.(differential_vars,du,u)) @. du = ifelse(differential_vars,r.zero,du) @. u = ifelse(differential_vars,u,r.zero) recursivecopy!(integrator.uprev,integrator.u) if alg_extrapolates(integrator.alg) recursivecopy!(integrator.uprev2,integrator.uprev) end return end function _initialize_dae!(integrator, prob::DAEProblem, alg::BrownFullBasicInit, ::Val{false}) @unpack p, t, f = integrator differential_vars = prob.differential_vars if integrator.opts.internalnorm(f(integrator.du, integrator.u, p, t),t) <= alg.abstol return elseif differential_vars === nothing error("differential_vars must be set for DAE initialization to occur. Either set consistent initial conditions, differential_vars, or use a different initialization algorithm.") end if integrator.u isa Number && integrator.du isa Number # This doesn't fix static arrays! u = [integrator.u] du = [integrator.du] else u = integrator.u du = integrator.du end nlequation = (out,x) -> begin @. du = ifelse(differential_vars,x,du) @. u = ifelse(differential_vars,u,x) out .= f(du, u, p, t) end r = nlsolve(nlequation, ifelse.(differential_vars,du,u)) @. du = ifelse(differential_vars,r.zero,du) @. u = ifelse(differential_vars,u,r.zero) if integrator.u isa Number && integrator.du isa Number # This doesn't fix static arrays! integrator.u = first(u) integrator.du = first(du) else integrator.u = u integrator.du = du end integrator.uprev = integrator.u if alg_extrapolates(integrator.alg) integrator.uprev2 = integrator.uprev end return end
If two sets are equal and the functions defined on them are equal, then the functions are holomorphic on the sets if and only if the functions are holomorphic on the sets.