text
stringlengths 0
1.25M
| meta
stringlengths 47
1.89k
|
|---|---|
if haskey(ENV, "CI")
ENV["PLOTS_TEST"] = "true"
ENV["GKSwstype"] = "100" # gr segfault workaround
end
using FluxOptTools, Optim, Zygote, Flux, Plots, Test, Statistics, Random
##
@testset "FluxOptTools" begin
@info "Testing FluxOptTools"
@testset "copy" begin
@info "Testing copy"
m = Chain(Dense(1,5,tanh), Dense(5,5,tanh) , Dense(5,1))
x = collect(LinRange(-pi,pi,100)')
y = sin.(x)
sp = sortperm(x[:])
loss() = mean(abs2, m(x) .- y)
Zygote.refresh()
pars = Flux.params(m)
pars0 = deepcopy(pars)
npars = veclength(pars)
@test npars == 46
copy!(pars, zeros(pars))
@test all(all(iszero, p) for p in pars)
p = zeros(pars)
copy!(pars, 1:npars)
copy!(p, pars)
@test p == 1:npars
grads = Zygote.gradient(loss, pars)
grads0 = deepcopy(grads)
copy!(grads, zeros(grads))
@test all(all(iszero,grads[k]) for k in keys(grads.grads))
p = zeros(grads)
copy!(grads, 1:npars)
copy!(p, grads)
@test p == 1:npars
end
## Test optimization ============================================
end
# NOTE: tests below fail if they are in a testset, probably Zygote's fault
m = Chain(Dense(1,5,tanh), Dense(5,5,tanh) , Dense(5,1))
x = collect(LinRange(-pi,pi,100)')
y = sin.(x)
sp = sortperm(x[:])
loss() = mean(abs2, m(x) .- y)
@show loss()
Zygote.refresh()
pars = Flux.params(m)
opt = ADAM(0.01)
@show loss()
for i = 1:500
grads = Zygote.gradient(loss, pars)
Flux.Optimise.update!(opt, pars, grads)
end
@show loss()
@test loss() < 1e-1
plot(x[sp], [y[sp] m(x)[sp]]) |> display
plot(loss, pars, l=0.5, npoints=50, seriestype=:contour) |> display
lossfun, gradfun, fg!, p0 = optfuns(loss, pars)
res = Optim.optimize(Optim.only_fg!(fg!), p0, BFGS())
@test loss() < 1e-3
plot(loss, pars, l=0.1, npoints=50) |> display
plot(x[sp], [y[sp] m(x)[sp]]) |> display
## Benchmark Optim vs ADAM
losses_adam = map(1:10) do i
@show i
Random.seed!(i)
m = Chain(Dense(1,5,tanh), Dense(5,5,tanh) , Dense(5,1))
x = collect(LinRange(-pi,pi,100)')
y = sin.(x)
loss() = mean(abs2, m(x) .- y)
Zygote.refresh()
pars = Flux.params(m)
opt = Flux.ADAM(0.2)
trace = [loss()]
for i = 1:500
l,back = Zygote.pullback(loss, pars)
push!(trace, l)
grads = back(l)
Flux.Optimise.update!(opt, pars, grads)
end
trace
end
res_lbfgs = map(1:10) do i
@show i
Random.seed!(i)
m = Chain(Dense(1,5,tanh), Dense(5,5,tanh) , Dense(5,1))
x = LinRange(-pi,pi,100)'
y = sin.(x)
loss() = mean(abs2, m(x) .- y)
Zygote.refresh()
pars = Flux.params(m)
lossfun, gradfun, fg!, p0 = optfuns(loss, pars)
res = Optim.optimize(Optim.only_fg!(fg!), p0, BFGS(), Optim.Options(iterations=500, store_trace=true))
res
end
losses_SLBFGS = map(1:10) do i
@show i
Random.seed!(i)
m = Chain(Dense(1,5,tanh), Dense(5,5,tanh) , Dense(5,1))
x = LinRange(-pi,pi,100)'
y = sin.(x)
loss() = mean(abs2, m(x) .- y)
Zygote.refresh()
pars = Flux.params(m)
lossfun, gradfun, fg!, p0 = optfuns(loss, pars)
opt = SLBFGS(lossfun,p0; m=3, ᾱ=1., ρ=false, λ=.0001, κ=0.1)
function train(opt, p0, iters=20)
p = copy(p0)
g = zeros(veclength(pars))
trace = [loss()]
for i = 1:iters
g = gradfun(g,p)
p = apply(opt, g, p)
push!(trace, opt.fold)
end
trace
end
trace = train(opt,p0, 500)
end
##
valuetrace(r) = getfield.(r.trace, :value)
valuetraces = valuetrace.(res_lbfgs)
plot(valuetraces, yscale=:log10, xscale=:identity, lab="", c=:red)
plot!(losses_adam, lab="", c=:blue, xlabel="Epochs", ylabel="Loss")
plot!(losses_SLBFGS, lab="", c=:green)
|
{"hexsha": "40566017920fd0510147a4d55ea836c193e5472f", "size": 3637, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/runtests.jl", "max_stars_repo_name": "baggepinnen/FluxOptTools.jl", "max_stars_repo_head_hexsha": "fa0f140978295cc49f9a69eda7a442318883aed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2019-07-01T09:24:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T02:28:28.000Z", "max_issues_repo_path": "test/runtests.jl", "max_issues_repo_name": "baggepinnen/FluxOptTools.jl", "max_issues_repo_head_hexsha": "fa0f140978295cc49f9a69eda7a442318883aed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2019-09-17T04:43:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T19:22:51.000Z", "max_forks_repo_path": "test/runtests.jl", "max_forks_repo_name": "baggepinnen/FluxOptTools.jl", "max_forks_repo_head_hexsha": "fa0f140978295cc49f9a69eda7a442318883aed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-10-05T07:42:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T13:05:45.000Z", "avg_line_length": 24.4093959732, "max_line_length": 106, "alphanum_fraction": 0.5963706351, "num_tokens": 1304}
|
import tensorflow as tf
import numpy as np
import pandas as pd
import scipy.stats as st
from tensorflow.keras import layers
import sklearn.metrics
import sklearn
from tensorflow.keras.models import Model
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import *
from collections import defaultdict
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from sklearn.feature_extraction.text import CountVectorizer
# In[ ]:
#https://github.com/wwbp/empathic_reactions/blob/master/modeling/main/crossvalidation/experiment.py
def correlation(true, pred):
pred = np.array(pred).flatten()
result = st.pearsonr(np.array(true),pred)
return result[0]
def getMetrics(trueLabels, predictedLabels):
"""Takes as input true labels, predictions, and prediction confidence scores and computes all metrics"""
MSE = sklearn.metrics.mean_squared_error(trueLabels, predictedLabels, squared = True)
MAE = sklearn.metrics.mean_absolute_error(trueLabels, predictedLabels)
MAPE = sklearn.metrics.mean_absolute_percentage_error(trueLabels, predictedLabels)
RMSE = sklearn.metrics.mean_squared_error(trueLabels, predictedLabels, squared = False)
PearsonR = correlation(true = trueLabels,
pred = predictedLabels)
return MSE, MAE, MAPE, RMSE, PearsonR
# In[ ]:
def splitRowIntoWords(row, length):
"""Takes a variable length text input and convert it into a list of words with length equal to 'length' in the function parameter"""
words = tf.keras.preprocessing.text.text_to_word_sequence(row, filters=' !#$%&()*+,-./:;<=>?@[\\]^_{|}~\t\n"\'', lower=True, split=" ")
# If length is less than required length, add zeros
while len(words) < length:
words.append(0)
# If greater, remove stuff at the end
if len(words) >= length:
words = words[:length]
return words
# In[ ]:
def buildAndTrainModel(model, learningRate, batchSize, epochs, trainingData, validationData, testingData, trainingLabels, validationLabels, testingLabels, MODEL_NAME, isPrintModel=True):
"""Take the model and model parameters, build and train the model"""
# Build and compile model
# To use other optimizers, refer to: https://keras.io/optimizers/
# Please do not change the loss function
optimizer = tf.keras.optimizers.Adam(lr=learningRate)
model.compile(optimizer=optimizer,
loss=tf.keras.losses.MeanSquaredError())
if isPrintModel:
print(model.summary())
for epoch in range(0, epochs):
model.fit(trainingData, trainingLabels,
epochs=1,
verbose=0,
batch_size=batchSize,
shuffle=False)
# Evaluate model
valLoss = model.evaluate(validationData, validationLabels, verbose=False)
#model.save('Results/StructuredBinary/{}/epoch_{}'.format(filename,epoch))
## get metrics
predictions = model.predict(testingData)
MSE, MAE, MAPE, RMSE, PR = getMetrics(testingLabels,predictions)
MeanSquaredError.append(MSE)
RootMeanSquaredError.append(RMSE)
MeanAbsoluteError.append(MAE)
MeanAbsolutePercentageError.append(MAPE)
PearsonR.append(PR)
ValMSE.append(valLoss)
Epoch.append(epoch)
if valLoss <= min(ValMSE):
max_predictions = predictions
return MeanSquaredError, RootMeanSquaredError, MeanAbsoluteError, MeanAbsolutePercentageError, ValMSE, PearsonR, Epoch, max_predictions
# In[ ]:
def attachOutputLayerToModel(lastDenseLayer, modelInputs):
"""Take as input a dense layer and attach an output layer"""
output = layers.Dense(1, activation='sigmoid', kernel_regularizer=tf.keras.regularizers.l2(0.001))(lastDenseLayer)
model = Model(inputs=modelInputs, outputs=output)
return model
# In[ ]:
def createFeedForwardNeuralNetwork(trainFeatures, validationFeatures, testFeatures, numLayers, layerNodes):
"""Create a feed forward neural network"""
## create basic nn model
modelInput = layers.Input(shape=trainFeatures.shape[1:], dtype='float32')
neuralNetworkLayer = layers.Dense(layerNodes, activation='relu', input_shape=trainFeatures.shape[1:], kernel_regularizer=tf.keras.regularizers.l2(0.001))(modelInput)
neuralNetworkLayer = layers.Dropout(0.5)(neuralNetworkLayer)
for i in range(numLayers - 1):
neuralNetworkLayer = layers.Dense(layerNodes, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))(neuralNetworkLayer)
neuralNetworkLayer = layers.Dropout(0.5)(neuralNetworkLayer)
# You can change the number of nodes in the dense layer. Right now, it's set to 32.
denseLayer = layers.Dense(64, kernel_regularizer=tf.keras.regularizers.l2(0.001))(neuralNetworkLayer)
return denseLayer, modelInput
# In[ ]:
files = ['TrustPhys_','SubjectiveLit_','Anxiety_','Numeracy_']
cv = ['1','2','3','4','5']
# In[ ]:
for filename in files:
for i in cv:
MeanSquaredError = []
MeanAbsoluteError = []
MeanAbsolutePercentageError = []
RootMeanSquaredError = []
PearsonR = []
Epoch = []
ValMSE = []
string_train = 'ContinuousCV/{}/{}train.txt'.format(i, filename)
string_test = 'ContinuousCV/{}/{}test.txt'.format(i, filename)
string_val = 'ContinuousCV/{}/{}val.txt'.format(i, filename)
data_train = pd.read_csv(string_train, header = None, sep = '\t',encoding='ISO-8859-1').dropna()
data_test = pd.read_csv(string_test, header = None, sep = '\t',encoding='ISO-8859-1').dropna()
data_val = pd.read_csv(string_val, header = None, sep = '\t',encoding='ISO-8859-1').dropna()
vectorizer = CountVectorizer(ngram_range = (1,1), max_features = 50000, binary = True)
x_train = data_train[1]
xtrainfeatures = vectorizer.fit_transform(x_train).toarray()
ytrain = data_train[0]
x_test = data_test[1]
xtestfeatures = vectorizer.transform(x_test).toarray()
ytest = data_test[0]
x_val = data_val[1]
xvalfeatures = vectorizer.transform(x_val).toarray()
yval = data_val[0]
#Build StructuredNN
StructuredLayers = 3
StructuredUnits = 256
StructuredDenseLayer, StructuredInput = createFeedForwardNeuralNetwork(xtrainfeatures,xvalfeatures,xtestfeatures,StructuredLayers,StructuredUnits)
# Attach the output layer with the model
NNModel = attachOutputLayerToModel(StructuredDenseLayer, StructuredInput)
# Train model
LEARNING_RATE = 0.0001
BATCH_SIZE = 32
EPOCHS = 35
MeanSquaredError, RootMeanSquaredError, MeanAbsoluteError, MeanAbsolutePercentageError, ValMSE, PearsonR, Epochs, pred = buildAndTrainModel(NNModel, LEARNING_RATE,
BATCH_SIZE, EPOCHS,
xtrainfeatures,xvalfeatures,xtestfeatures, ytrain,yval,ytest,"NN")
results = {
'Epochs': Epochs,
'Mean_Squared_Error': MeanSquaredError,
'Root_Mean_Squared_Error': RootMeanSquaredError,
'Mean_Absolute_Error': MeanAbsoluteError,
'Mean_Absolute_Percentage_Error': MeanAbsolutePercentageError,
'PearsonR': PearsonR,
'Val_Mean_Squared_Error': ValMSE
}
predictions_dictionary = {
'sentence': np.array(x_test).flatten(),
'pred': np.array(pred).flatten()
}
#results_df = pd.DataFrame.from_dict(results)
#results_string = 'Results/StructuredContinue/{}_{}Conresults.csv'.format(i, filename)
#results_df.to_csv(results_string, index = False)
#predictions_df = pd.DataFrame.from_dict(predictions_dictionary)
#predictions_df.to_csv('Results/StructuredContinue/{}_{}_Conpredictions.csv'.format(i, filename), index=False)
|
{"hexsha": "b6ece16c236440f8b0e8ec291e455ed0dd260b99", "size": 8553, "ext": "py", "lang": "Python", "max_stars_repo_path": "Code/ContinuousFeedForward.py", "max_stars_repo_name": "nd-hal/fair-psych-nlp", "max_stars_repo_head_hexsha": "c0ba97fdcec6a2f58563de8dba3b9dde6f9b4b6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-17T11:50:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:50:26.000Z", "max_issues_repo_path": "Code/ContinuousFeedForward.py", "max_issues_repo_name": "nd-hal/fair-psych-nlp", "max_issues_repo_head_hexsha": "c0ba97fdcec6a2f58563de8dba3b9dde6f9b4b6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/ContinuousFeedForward.py", "max_forks_repo_name": "nd-hal/fair-psych-nlp", "max_forks_repo_head_hexsha": "c0ba97fdcec6a2f58563de8dba3b9dde6f9b4b6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8772727273, "max_line_length": 212, "alphanum_fraction": 0.6421138782, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1885}
|
import numpy as np
import random
class experienceBuffer():
#Initialize an empty buffer of buffer_size
def __init__(self, buffer_size = 2000):
self.buffer = []
self.buffer_size = buffer_size
#Add experience to the buffer, and clear old experiences of full
def add(self,experience):
if len(self.buffer) + len(experience) >= self.buffer_size:
self.buffer[0:(len(experience)+len(self.buffer))-self.buffer_size] = []
self.buffer.extend(experience)
#Take a random sample of the experiences to work with
def sample(self,size):
return np.reshape(np.array(random.sample(self.buffer,size)),[size,5])
|
{"hexsha": "1e4af3dfcf01d8d2327a3ffecf91a037dd61347c", "size": 684, "ext": "py", "lang": "Python", "max_stars_repo_path": "DQN-Breakout/experience_replay.py", "max_stars_repo_name": "TonyNgo1/RL-OpenAIGym", "max_stars_repo_head_hexsha": "9e079d7783f4d93e7e3478cfc511ff31fa4bfb7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DQN-Breakout/experience_replay.py", "max_issues_repo_name": "TonyNgo1/RL-OpenAIGym", "max_issues_repo_head_hexsha": "9e079d7783f4d93e7e3478cfc511ff31fa4bfb7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DQN-Breakout/experience_replay.py", "max_forks_repo_name": "TonyNgo1/RL-OpenAIGym", "max_forks_repo_head_hexsha": "9e079d7783f4d93e7e3478cfc511ff31fa4bfb7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0, "max_line_length": 83, "alphanum_fraction": 0.6666666667, "include": true, "reason": "import numpy", "num_tokens": 151}
|
from pathlib import Path
import numpy as np
from mdgraph.data.preprocess import aminoacid_int_encoding, aminoacid_int_to_onehot
TEST_DATA_PATH = Path(__file__).parent / "data/1FME-unfolded.pdb"
def test_residue_onehot_encoding():
residues, labels = aminoacid_int_encoding(str(TEST_DATA_PATH))
assert len(residues) == 28
assert all(isinstance(r, str) for r in residues)
num_unique_aa = len(np.unique(labels))
onehot = aminoacid_int_to_onehot(labels)
assert onehot.shape == (len(labels), num_unique_aa)
# np.save("onehot_bba_amino_acid_labels.npy", labels)
|
{"hexsha": "04f890c1f862e206b4912946fec8c5b03de4497e", "size": 587, "ext": "py", "lang": "Python", "max_stars_repo_path": "test/test_preprocess.py", "max_stars_repo_name": "hengma1001/pytorch-geometric-sandbox", "max_stars_repo_head_hexsha": "cd5b73663db9d9c27a957c56cab20e575fc6374d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-09T22:26:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-09T22:26:10.000Z", "max_issues_repo_path": "test/test_preprocess.py", "max_issues_repo_name": "hengma1001/pytorch-geometric-sandbox", "max_issues_repo_head_hexsha": "cd5b73663db9d9c27a957c56cab20e575fc6374d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-02-23T04:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-26T23:13:33.000Z", "max_forks_repo_path": "test/test_preprocess.py", "max_forks_repo_name": "hengma1001/pytorch-geometric-sandbox", "max_forks_repo_head_hexsha": "cd5b73663db9d9c27a957c56cab20e575fc6374d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-17T19:03:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T19:03:28.000Z", "avg_line_length": 34.5294117647, "max_line_length": 83, "alphanum_fraction": 0.7666098807, "include": true, "reason": "import numpy", "num_tokens": 151}
|
#include <type_traits>
#include <boost/preprocessor/stringize.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/print.hpp>
#include <boost/fusion/include/vector.hpp>
#include <desalt/parameter_pack.hpp>
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
namespace ppack = desalt::parameter_pack;
namespace mpl = boost::mpl;
namespace fu = boost::fusion;
using ppack::type_seq;
using a = type_seq<int, char, double>;
using m = mpl::vector<int, char, double>;
using v = fu::vector<int, char, double>;
#define STATIC_TEST(...) static_assert((__VA_ARGS__), __FILE__ "(" BOOST_PP_STRINGIZE(__LINE__) ")")
STATIC_TEST(std::is_same<ppack::head<a>::type, int>::value);
STATIC_TEST(std::is_same<ppack::tail<a>::type, type_seq<char, double>>::value);
STATIC_TEST(std::is_same<ppack::cons<float, a>::type, type_seq<float, int, char, double>>::value);
STATIC_TEST(ppack::size<a>::value == 3);
STATIC_TEST(std::is_same<ppack::reverse<a>::type, type_seq<double, char, int>>::value);
STATIC_TEST(std::is_same<ppack::append<a, type_seq<float, short>>::type, type_seq<int, char, double, float, short>>::value);
STATIC_TEST(std::is_same<ppack::from_mpl_seq<m>::type, a>::value);
STATIC_TEST(std::is_same<ppack::from_fusion_seq<v>::type, a>::value);
STATIC_TEST(std::is_same<ppack::enumerate_c<int, 0, 5>::type, type_seq<std::integral_constant<int, 0>,
std::integral_constant<int, 1>,
std::integral_constant<int, 2>,
std::integral_constant<int, 3>,
std::integral_constant<int, 4>>>::value);
STATIC_TEST(std::is_same<ppack::at_c<a, 0>::type, int>::value);
STATIC_TEST(std::is_same<ppack::at_c<a, 1>::type, char>::value);
STATIC_TEST(std::is_same<ppack::at_c<a, 2>::type, double>::value);
int main() {}
|
{"hexsha": "9cb733c555716d2dc00681f4e394cc605019e099", "size": 1988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/parameter_pack.cpp", "max_stars_repo_name": "dechimal/desalt", "max_stars_repo_head_hexsha": "29f2bbe9e41850ddd4ebff39958747e504e3a6a3", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T08:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-21T09:52:52.000Z", "max_issues_repo_path": "test/parameter_pack.cpp", "max_issues_repo_name": "dechimal/desalt", "max_issues_repo_head_hexsha": "29f2bbe9e41850ddd4ebff39958747e504e3a6a3", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/parameter_pack.cpp", "max_forks_repo_name": "dechimal/desalt", "max_forks_repo_head_hexsha": "29f2bbe9e41850ddd4ebff39958747e504e3a6a3", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.487804878, "max_line_length": 124, "alphanum_fraction": 0.6222334004, "num_tokens": 490}
|
# -*- coding: utf-8 -*-
"""Mask-RCNN.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1aHWlXGTEeAFxN3L4lkJdtkDQsYKtxlc8
"""
import torch
import torchvision
import torchvision.transforms as T
import PIL
from PIL import Image
import random
import matplotlib.pyplot as plt
import numpy as np
import cv2
model=torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
model.eval()
coco_instance_category_names=[ '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']
def random_color_masks(image):
colors = [[0, 255, 0],[0, 0, 255],[255, 0, 0],[0, 255, 255],[255, 255, 0],[255, 0, 255],[80, 70, 180],[250, 80, 190],[245, 145, 50],[70, 150, 250],[50, 190, 190]]
r=np.zeros_like(image).astype(np.uint8)
g=np.zeros_like(image).astype(np.uint8)
b=np.zeros_like(image).astype(np.uint8)
r[image==1],b[image==1],g[image==1]=colors[random.randrange(0,10)]
colored_mask=np.stack([r,g,b],axis=2)
return colored_mask
def get_prediction(threshold,image):
# print("prediction")
img=image.astype(np.uint8)
img=PIL.Image.fromarray(img)
transform=T.Compose([T.ToTensor()])
img=transform(img)
# model.cuda()
# img = img.cuda()
pred=model([img])
pred_score=list(pred[0]['scores'].detach().cpu().numpy())
pred_t=[pred_score.index(x) for x in pred_score if x>threshold][-1]
masks=(pred[0]['masks']>0.5).squeeze().detach().cpu().numpy()
pred_class=[coco_instance_category_names[i] for i in list(pred[0]['labels'])]
pred_boxes=[[(i[0],i[1]),(i[2],i[3])] for i in list(pred[0]['boxes'].detach().cpu().numpy())]
masks=masks[:pred_t+1]
pred_boxes=pred_boxes[:pred_t +1]
pred_class=pred_class[:pred_t +1]
return masks,pred_boxes,pred_class
def instance_segmentation_api(threshold,image1,rect_thickness=2,text_size=2,text_thickness=2):
# print("instance")
masks,boxes,predict_class= get_prediction(threshold,image=image1)
image=image1
image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
for i in range(len(masks)):
rgb_mask=random_color_masks(masks[i])
image=cv2.addWeighted(image,1,rgb_mask,0.5,0)
cv2.rectangle(image,boxes[i][0],boxes[i][1],color=(0,255,0),thickness=rect_thickness)
cv2.putText(image,predict_class[i],boxes[i][1],cv2.FONT_HERSHEY_SIMPLEX,text_size,(0,255,0),thickness=text_thickness)
return image
# plt.figure(figsize=(20,30))
# plt.imshow(image)
# plt.xticks([])
# plt.yticks([])
# plt.show()
cap=cv2.VideoCapture(0)
while True:
ret,frame=cap.read()
image=instance_segmentation_api(threshold=0.75,image1=frame)
cv2.imshow('image',image)
if cv2.waitKey(1)==ord('a'):
break
cap.release()
cv2.destroyAllWindows()
|
{"hexsha": "7c62c11224956a227599e50f0fac48418d5dd21a", "size": 3649, "ext": "py", "lang": "Python", "max_stars_repo_path": "mask_rcnn.py", "max_stars_repo_name": "aryachiranjeev/Mask-RCNN", "max_stars_repo_head_hexsha": "8d34d3879a4039dccc173bea699b24465aa33372", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mask_rcnn.py", "max_issues_repo_name": "aryachiranjeev/Mask-RCNN", "max_issues_repo_head_hexsha": "8d34d3879a4039dccc173bea699b24465aa33372", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mask_rcnn.py", "max_forks_repo_name": "aryachiranjeev/Mask-RCNN", "max_forks_repo_head_hexsha": "8d34d3879a4039dccc173bea699b24465aa33372", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2346938776, "max_line_length": 164, "alphanum_fraction": 0.6678542066, "include": true, "reason": "import numpy", "num_tokens": 1169}
|
# run from detectron2/detectron2 directory
#from detectron2.data.datasets.coco import convert_to_coco_json
import torch
assert torch.__version__.startswith("1.7")
import argparse
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
import numpy as np
import os, json, cv2, random
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog, DatasetCatalog
from detectron2.evaluation.coco_evaluation import COCOEvaluator
# GET FOLDER TO RUN DETECTRON ON WITHIN annotation_tools/image_datasets
parser = argparse.ArgumentParser()
parser.add_argument('image_folder', type=str, help="Path to Folder? Folder must be in image_datasets")
parser.add_argument('output_json', type=str, help="Path to json output file? File will be output in json_datasets")
parser.add_argument('model_yaml', type=str, help="Model Yaml from Model Zoo - https://detectron2.readthedocs.io/en/latest/_modules/detectron2/model_zoo/model_zoo.html")
args = parser.parse_args()
model_yaml = args.model_yaml
# keypoint model = "COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x.yaml"
# CONFIGURE MODEL
cfg = get_cfg()
# add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
cfg.merge_from_file(model_zoo.get_config_file(model_yaml))
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model
cfg.MODEL.DEVICE = "cpu"
# Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(model_yaml)
predictor = DefaultPredictor(cfg)
# DATASET FORMAT FOR VISIPEDIA
images = []
licenses = []
annotations = []
categories = [{"keypoints_style": ["#e6194b", "#3cb44b", "#ffe119", "#0082c8", "#f58231", "#911eb4", "#46f0f0", "#f032e6",
"#d2f53c", "#fabebe", "#008080", "#e6beff", "#aa6e28", "#fffac8", "#800000", "#aaffc3", "#808000"], "skeleton": [[16, 14],
[14, 12], [17, 15], [15, 13], [12, 13], [6, 12], [7, 13], [6, 7], [6, 8], [7, 9], [8, 10], [9, 11], [2, 3], [1, 2], [1, 3],
[2, 4], [3, 5], [4, 6], [5, 7]], "supercategory": "person", "keypoints": ["nose", "left_eye", "right_eye", "left_ear",
"right_ear", "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", "left_wrist", "right_wrist", "left_hip",
"right_hip", "left_knee", "right_knee", "left_ankle", "right_ankle"], "id": "1", "name": "person"}]
# INITIALIZE IMAGE AND ANNOTATION ID COUNTER
image_ctr = 0
annotation_ctr = 0
kp_indices = {"nose": 0, "left_eye": 1, "right_eye": 3, "left_ear": 4,
"right_ear": 5, "left_shoulder": 6, "right_shoulder": 7, "left_elbow": 8,
"right_elbow": 9, "left_wrist": 10, "right_wrist": 11, "left_hip": 12,
"right_hip": 13, "left_knee": 14, "right_knee": 15, "left_ankle": 16, "right_ankle": 17}
kp_threshes = [0.5, 0.4, 0.4, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1]
# LOOP THROUGH FOLDER, RUN DETECTRON
directory = args.image_folder #directory in ../../annotation_tools/
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
# INITIALIZE IMAGE COUNTER
image_ctr += 1
# READ IMAGE AND PREDICT
im = cv2.imread(os.path.join(directory, filename))
height, width, channels = im.shape
outputs = predictor(im)
print("Images complete: {}".format(image_ctr))
#ADD ANNOTATIONS TO ANNOTATIONS LIST
boxes_tensor = list(outputs["instances"].pred_boxes)
keypoints_tensor = list(outputs["instances"].get_fields()["pred_keypoints"])
for i, bbox in enumerate(boxes_tensor):
ann = {}
annotation_ctr += 1
ann["id"] = str(annotation_ctr)
ann["image_id"] = str(image_ctr)
ann["category_id"] = "1"
d2_bbox = boxes_tensor[i].tolist()
coco_bbox = [d2_bbox[0], d2_bbox[1], d2_bbox[2] - d2_bbox[0], d2_bbox[3] - d2_bbox[1]]
ann["bbox"] = coco_bbox
list_kp_list = keypoints_tensor[i].tolist()
for n, kp in enumerate(list_kp_list):
if kp[2] < kp_threshes[n]:
list_kp_list[n][0] = 0
list_kp_list[n][1] = 0
list_kp_list[n][2] = 0
else:
list_kp_list[n][2] = 2
list_kp_list = [item for sublist in list_kp_list for item in sublist]
ann["keypoints"] = list_kp_list
annotations.append(ann)
# print(keypoints_tensor)
# print(ann["keypoints"])
# APPEND IMAGES TO IMAGE DICT
image_dict = {}
image_dict["url"] = "http://localhost:6008/image_datasets/" + str(args.image_folder).split("/")[-1] + "/" + filename
image_dict["file_name"] = filename
image_dict["rights_holder"] = ""
image_dict["id"] = str(image_ctr)
image_dict["license"] = "1"
image_dict["width"] = width
image_dict["height"] = height
images.append(image_dict)
# # DISPLAY ANNOTATIONS ON IMAGE
# v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
# out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
# cv2.imshow("", out.get_image()[:, :, ::-1])
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# APPEND FIELDS TO DATASET DICT
silver_dataset = {}
silver_dataset["images"] = images
silver_dataset["licenses"] = licenses
silver_dataset["annotations"] = annotations
silver_dataset["categories"] = categories
# WRITE DATASET DICT TO JSON
silver_dataset_path = args.output_json
with open(silver_dataset_path, 'w') as f:
json.dump(silver_dataset, f, indent=4)
#convert_to_coco_json(cfg.DATASETS.TRAIN[0], 'test_d2_coco', allow_cached=False)
|
{"hexsha": "56c71b62ed2857062cd2c08a9b765e292c3bc632", "size": 5885, "ext": "py", "lang": "Python", "max_stars_repo_path": "detectron2/detect.py", "max_stars_repo_name": "av777x/detectron2", "max_stars_repo_head_hexsha": "c1794881d6d2fac6af0b3206937d32628677469c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "detectron2/detect.py", "max_issues_repo_name": "av777x/detectron2", "max_issues_repo_head_hexsha": "c1794881d6d2fac6af0b3206937d32628677469c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "detectron2/detect.py", "max_forks_repo_name": "av777x/detectron2", "max_forks_repo_head_hexsha": "c1794881d6d2fac6af0b3206937d32628677469c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3381294964, "max_line_length": 168, "alphanum_fraction": 0.6593033135, "include": true, "reason": "import numpy", "num_tokens": 1749}
|
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes._base import _AxesBase
from matplotlib.patches import Ellipse, Circle
def calc_point_on_circle(i: int, slice: float, radius: float, center: (float, float) = (0, 0)):
"""
Return coordinates of the i-th point on a circle.
:param i: i-th point
:param slice: width of the slices [degrees]
:param radius: radius of the circle
:param center: (x, y) coordinates of the circle center
:return:
"""
angle = slice * i
new_x = center[0] + radius * np.cos(angle)
new_y = center[1] + radius * np.sin(angle)
return new_x, new_y
calculate_angle = lambda i, n_slices: 360 / n_slices * i
autorotate_angle = lambda angle: angle - 180 if 90 < angle < 270 else angle
autoalign_text = lambda angle: 'right' if 90 < angle < 270 else 'left'
def validate_data(genome: str, data: dict) -> None:
for key in ['color', 'shell', 'unique']:
if key not in data:
raise KeyError(f'Genome {genome} is missing attribute {key}!')
def flower_plot(
genome_to_data: dict[str:dict],
n_core: int,
shell_color='lightgray',
core_color='darkgrey',
alpha: float = 0.3,
rotate_shell: bool = True,
rotate_unique: bool = True,
rotate_genome: bool = True,
default_fontsize: float = None,
core_fontsize: float = 12,
ax: _AxesBase = None
) -> _AxesBase:
"""
Create a flower plot. Returns matplotlib axis object.
:param genome_to_data: dictionary that maps genome names to associated data (color, number of unique and shell genes)
:param n_core: number of core genes
:param shell_color: color of the shell circle
:param core_color: color of the core circle
:param alpha: opacity of the ellipses
:param rotate_shell: whether to rotate the number of shell genes text
:param rotate_unique: whether to rotate the number of unique genes text
:param rotate_genome: whether to rotate the genome name
:param default_fontsize: font size for number of genes and genome name
:param core_fontsize: font size for number of core genes
:param ax: matplotlib axis
:return: matplotlib axis
"""
assert len(genome_to_data) > 0, f'No data was supplied. {len(genome_to_data)=}'
if ax is None:
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}, figsize=(6, 6), dpi=300)
n_genomes = len(genome_to_data)
# scale plot according to the number of genomes
factor = n_genomes / 16
factor = max([1, factor]) # ensure factor is never less than 1
# default text parameters
if default_fontsize is None:
default_fontsize = 3.5 / np.log10(factor + 1) # empirical
textparams = dict(va='center', fontsize=default_fontsize, bbox=dict(facecolor='white', alpha=1e-16))
# calculate width of the slices [degrees]
slice = 2 * np.pi / n_genomes
# shell circle
circle_shell = Circle(
xy=(0, 0), radius=3 * factor, color=shell_color
)
ax.add_artist(circle_shell)
for i, (genome, data) in enumerate(genome_to_data.items()):
validate_data(genome, data)
angle = calculate_angle(i, n_genomes)
rotated_angle = autorotate_angle(angle)
# unique genes: ellipses
ax.add_artist(Ellipse(
calc_point_on_circle(i, slice, 3 * factor),
width=4, height=1.5, angle=angle, alpha=alpha, color=data['color']
))
# unique genes: number
text_unique = ax.text(
*calc_point_on_circle(i, slice, 3 * factor + 1),
s=data['unique'], ha='center',
rotation=rotated_angle if rotate_unique else None,
**textparams
)
text_unique.set_gid(f'flower-unique-{genome}')
# shell genes: number
text_shell = ax.text(
*calc_point_on_circle(i, slice, 3 * factor - 1),
s=data['shell'], ha='center',
rotation=rotated_angle if rotate_shell else None,
**textparams
)
text_shell.set_gid(f'flower-shell-{genome}')
# genome name
text_genome = ax.text(
*calc_point_on_circle(i, slice, 3 * factor + 2.1),
s=genome, ha=autoalign_text(angle),
rotation=rotated_angle if rotate_genome else None, rotation_mode='anchor',
**textparams
)
text_genome.set_gid(f'flower-genome-{genome}')
# core circle
circle_core = Circle(
xy=(0, 0), radius=1 * factor, color=core_color
)
circle_core.set_gid('flower-core')
ax.add_artist(circle_core)
# core genes: number
text_core = ax.text(
0, 0, n_core,
ha='center', va='center',
fontsize=core_fontsize
)
text_core.set_gid('flower-core-text')
# scale plot
lim = 4 + 3 * factor
ax.set_xlim(-lim, lim)
ax.set_ylim(-lim, lim)
ax.set_gid(f'flower-plot')
# disable axis
ax.set_axis_off()
return ax
|
{"hexsha": "9cddaf72065f2d67db70b1ca95ed0ea18889480b", "size": 4992, "ext": "py", "lang": "Python", "max_stars_repo_path": "flower_plot/flower_plot.py", "max_stars_repo_name": "MrTomRod/flower-plot", "max_stars_repo_head_hexsha": "19d5cf4dd63aa1aed418b0b66684aea8c7676ec6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-12-09T08:14:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T13:27:53.000Z", "max_issues_repo_path": "flower_plot/flower_plot.py", "max_issues_repo_name": "MrTomRod/flower-plot", "max_issues_repo_head_hexsha": "19d5cf4dd63aa1aed418b0b66684aea8c7676ec6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flower_plot/flower_plot.py", "max_forks_repo_name": "MrTomRod/flower-plot", "max_forks_repo_head_hexsha": "19d5cf4dd63aa1aed418b0b66684aea8c7676ec6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8421052632, "max_line_length": 121, "alphanum_fraction": 0.6354166667, "include": true, "reason": "import numpy", "num_tokens": 1302}
|
/-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen
-/
import group_theory.submonoid.inverses
import ring_theory.finiteness
import ring_theory.localization.basic
import tactic.ring_exp
/-!
# Submonoid of inverses
## Main definitions
* `is_localization.inv_submonoid M S` is the submonoid of `S = M⁻¹R` consisting of inverses of
each element `x ∈ M`
## Implementation notes
See `src/ring_theory/localization/basic.lean` for a design overview.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S]
variables [algebra R S] {P : Type*} [comm_ring P]
open function
open_locale big_operators
namespace is_localization
section inv_submonoid
variables (M S)
/-- The submonoid of `S = M⁻¹R` consisting of `{ 1 / x | x ∈ M }`. -/
def inv_submonoid : submonoid S := (M.map (algebra_map R S : R →* S)).left_inv
variable [is_localization M S]
lemma submonoid_map_le_is_unit : M.map (algebra_map R S : R →* S) ≤ is_unit.submonoid S :=
by { rintros _ ⟨a, ha, rfl⟩, exact is_localization.map_units S ⟨_, ha⟩ }
/-- There is an equivalence of monoids between the image of `M` and `inv_submonoid`. -/
noncomputable
abbreviation equiv_inv_submonoid : M.map (algebra_map R S : R →* S) ≃* inv_submonoid M S :=
((M.map (algebra_map R S : R →* S)).left_inv_equiv (submonoid_map_le_is_unit M S)).symm
/-- There is a canonical map from `M` to `inv_submonoid` sending `x` to `1 / x`. -/
noncomputable
def to_inv_submonoid : M →* inv_submonoid M S :=
(equiv_inv_submonoid M S).to_monoid_hom.comp ((algebra_map R S : R →* S).submonoid_map M)
lemma to_inv_submonoid_surjective : function.surjective (to_inv_submonoid M S) :=
function.surjective.comp (equiv.surjective _) (monoid_hom.submonoid_map_surjective _ _)
@[simp]
lemma to_inv_submonoid_mul (m : M) : (to_inv_submonoid M S m : S) * (algebra_map R S m) = 1 :=
submonoid.left_inv_equiv_symm_mul _ _ _
@[simp]
lemma mul_to_inv_submonoid (m : M) : (algebra_map R S m) * (to_inv_submonoid M S m : S) = 1 :=
submonoid.mul_left_inv_equiv_symm _ _ ⟨_, _⟩
@[simp]
lemma smul_to_inv_submonoid (m : M) : m • (to_inv_submonoid M S m : S) = 1 :=
by { convert mul_to_inv_submonoid M S m, rw ← algebra.smul_def, refl }
variables {S}
lemma surj' (z : S) : ∃ (r : R) (m : M), z = r • to_inv_submonoid M S m :=
begin
rcases is_localization.surj M z with ⟨⟨r, m⟩, e : z * _ = algebra_map R S r⟩,
refine ⟨r, m, _⟩,
rw [algebra.smul_def, ← e, mul_assoc],
simp,
end
lemma to_inv_submonoid_eq_mk' (x : M) :
(to_inv_submonoid M S x : S) = mk' S 1 x :=
by { rw ← (is_localization.map_units S x).mul_left_inj, simp }
lemma mem_inv_submonoid_iff_exists_mk' (x : S) :
x ∈ inv_submonoid M S ↔ ∃ m : M, mk' S 1 m = x :=
begin
simp_rw ← to_inv_submonoid_eq_mk',
exact ⟨λ h, ⟨_, congr_arg subtype.val (to_inv_submonoid_surjective M S ⟨x, h⟩).some_spec⟩,
λ h, h.some_spec ▸ (to_inv_submonoid M S h.some).prop⟩
end
variables (S)
lemma span_inv_submonoid : submodule.span R (inv_submonoid M S : set S) = ⊤ :=
begin
rw eq_top_iff,
rintros x -,
rcases is_localization.surj' M x with ⟨r, m, rfl⟩,
exact submodule.smul_mem _ _ (submodule.subset_span (to_inv_submonoid M S m).prop),
end
lemma finite_type_of_monoid_fg [monoid.fg M] : algebra.finite_type R S :=
begin
have := monoid.fg_of_surjective _ (to_inv_submonoid_surjective M S),
rw monoid.fg_iff_submonoid_fg at this,
rcases this with ⟨s, hs⟩,
refine ⟨⟨s, _⟩⟩,
rw eq_top_iff,
rintro x -,
change x ∈ ((algebra.adjoin R _ : subalgebra R S).to_submodule : set S),
rw [algebra.adjoin_eq_span, hs, span_inv_submonoid],
trivial
end
end inv_submonoid
end is_localization
|
{"author": "saisurbehera", "repo": "mathProof", "sha": "57c6bfe75652e9d3312d8904441a32aff7d6a75e", "save_path": "github-repos/lean/saisurbehera-mathProof", "path": "github-repos/lean/saisurbehera-mathProof/mathProof-57c6bfe75652e9d3312d8904441a32aff7d6a75e/src/tertiary_packages/mathlib/src/ring_theory/localization/inv_submonoid.lean"}
|
'''
Created on Apr 6, 2016
@author: jesus
Contains all methods and classes to perform the corpus division for cross validation
'''
import cPickle
import numpy as np
import copy,random
'''
Since we don't have enough sentences, we have no validation set, then,
each fold consists of a valtest set and a training set
'''
class Fold(object):
def __init__(self, train=[],valtest=[]):
self.trainSet=train
self.valtestSet=valtest
def saveToPickle(self,filePath):
outFile=file(filePath,'wb')
cPickle.dump([self.trainSet,self.valtestSet],outFile,protocol=cPickle.HIGHEST_PROTOCOL)
outFile.close()
def loadFromPickle(self,filePath):
inputFile=file(filePath,'rb')
[self.trainSet,self.valtestSet]=cPickle.load(inputFile)
inputFile.close()
'''
Receives a fold of situations divided into 10-90 test/train and creates properly the division between conditions
according to the conditions defined in Calvillo et al (2016)
'''
def getFoldTrainingTestSets(rawFoldFileNameActPas,rawFoldFileNameAct,condSize,outFileName):
foldActPas=Fold()
foldActPas.loadFromPickle(rawFoldFileNameActPas)
foldAct=Fold()
foldAct.loadFromPickle(rawFoldFileNameAct)
cond1=foldActPas.valtestSet[:condSize]
cond2=foldActPas.valtestSet[condSize:condSize*2]
cond3=foldActPas.valtestSet[condSize*2:]
cond4=foldAct.valtestSet[:condSize]
cond5=foldAct.valtestSet[condSize:]
trainingSet=[]
trainTestSet=[]
#cond1 actives are known, passives are asked
condt1p=[]
for sit in cond1:
condt1p.append(sit.passives[0])
trainingSet.extend(sit.actives)
trainTestSet.append(sit.actives[0])
#cond2 passives are known, actives are asked
condt2a=[]
for sit in cond2:
condt2a.append(sit.actives[0])
trainingSet.extend(sit.passives)
trainTestSet.append(sit.passives[0])
#cond3 dss is completely unknown
condt3a=[]
condt3p=[]
for sit in cond3:
condt3a.append(sit.actives[0])
condt3p.append(sit.passives[0])
#cond4 actives are known, passives are asked (but non-existent)
condt4p=[]
for sit in cond4:
exa=sit.actives[0]
passiveTrainElem=copy.deepcopy(exa)
passiveTrainElem.active=False
passiveTrainElem.DSSValue=np.append(sit.value,0.0)
passiveTrainElem.dss150[150]=0.0#This line is for a corpus with 150dss included
condt4p.append(passiveTrainElem)
trainingSet.extend(sit.actives)
trainTestSet.append(sit.actives[0])
#cond5 completely new DSS, actives are asked, passives are asked (but non-existent)
condt5a=[]
condt5p=[]
for sit in cond5:
condt5a.append(sit.actives[0])
exa=sit.actives[0]
passiveTrainElem=copy.deepcopy(exa)
passiveTrainElem.active=False
passiveTrainElem.DSSValue=np.append(sit.value,0.0)
passiveTrainElem.dss150[150]=0.0
condt5p.append(passiveTrainElem)
#ORIGINAL TRAINING SETS
trainActPas=foldActPas.trainSet
for sit in trainActPas:
trainingSet.extend(sit.passives)
trainTestSet.append(sit.passives[0])
trainingSet.extend(sit.actives)
trainTestSet.append(sit.actives[0])
trainAct=foldAct.trainSet
for sit in trainAct:
trainingSet.extend(sit.actives)
trainTestSet.append(sit.actives[0])
trainList=[trainingSet,trainTestSet]
testLists=[condt1p,condt2a,condt3a,condt3p,condt4p,condt5a,condt5p]
newFold=Fold(trainList,testLists)
#===========================================================================
# for lista in testLists:
# print
# for te in lista:
# print te.testItem
#===========================================================================
newFold.saveToPickle(outFileName)
return newFold
'''
Receives a list of elements elemList and creates k files with valtest/train divisions.
Not really used because SetA and SetAP have different sizes
'''
def getKFolds(k,elemList,seed):
kFloat=k*1.0
fullSize=len(elemList)
valtestSize=int(round(fullSize/kFloat)) #size is proportional to the number of folds
initial=0
folds=[]
random.seed(seed)
random.shuffle(elemList)
for i in xrange(k):
valtest=elemList[initial:initial+valtestSize]
training=elemList[:initial]+elemList[initial+valtestSize:]
fold=Fold(training,valtest)
fold.saveToPickle("fold_"+str(i)+".pick")
folds.append(fold)
initial+=valtestSize
return folds
'''
Receives a list of elements elemList and creates k files with valtest/train divisions.
The size of the valtest set is fixed beforehand
'''
def getKFoldsFixSize(k,valtestSize,elemList,seed,tag):
initial=0
folds=[]
random.seed(seed)
random.shuffle(elemList)
for i in xrange(k):
valtest=elemList[initial:initial+valtestSize]
training=elemList[:initial]+elemList[initial+valtestSize:]
fold=Fold(training,valtest)
fold.saveToPickle("fold_"+str(i)+"_"+tag+".pick")
folds.append(fold)
initial+=valtestSize
return folds
'''
We know that valtestsize is different for the corpus with only actives(28) from the one with passives(42)
So the size is not given as parameter
it is 28 and 42 because each condition contains 14 situations and
the act set contains 2 conditions, while the actpas contains 3
'''
def getKFoldsFixSizeAPCorpus(k,corpusAP,seed,tag):
listAct=corpusAP.act
listActPas=corpusAP.actpas
getKFoldsFixSize(k,28,listAct,seed,"sitfoldAct_"+tag)
getKFoldsFixSize(k,42,listActPas,seed,"sitfoldActPas_"+tag)
'''
Loads a pair of folds (actpasFoldx, actFoldx) and merges them creating the training and testing sets
including the testing conditions
For this case we know that condSize is 14
'''
def getKFoldTrainingTestSets(k,tag,condSize,outFileNamePrefix):
for x in xrange(k):
actpasFileName="fold_"+str(x)+"_sitfoldActPas_"+tag+".pick"
actFileName="fold_"+str(x)+"_sitfoldAct_"+tag+".pick"
outputFileName=outFileNamePrefix+"_"+str(x)+".pick"
getFoldTrainingTestSets(actpasFileName,actFileName,condSize,outputFileName)
'''
Takes a CorpusAP object and divides it into K-Folds
'''
def getKFinalTrainTestCondFolds(k,corpusAPFinal,tag,condSize,outTag):
getKFoldsFixSizeAPCorpus(k, corpusAPFinal, 127, tag)#127 is the seed for random
print "CORPUS DIVIDED INTO K FOLDS"
getKFoldTrainingTestSets(k, tag, condSize,outTag)
print "EACH FOLD DIVIDED INTO CONDITIONS"
if __name__ == '__main__':
from data.containers import CorpusAP
corpusAPFinal=CorpusAP()
corpusAPFinal.loadFromPickle("dataFiles/files-thesis/corpusAPFinal_thesis.pick")
getKFinalTrainTestCondFolds(10,corpusAPFinal,"thesis",14,"trainTest_Cond-thesis")
|
{"hexsha": "81f8902e95aaa6f0f2b1db55a99d5ac8d08b649a", "size": 7103, "ext": "py", "lang": "Python", "max_stars_repo_path": "data/crossValidation.py", "max_stars_repo_name": "iesus/thesis-production-models", "max_stars_repo_head_hexsha": "38bf703db513ffeed5a533590fbae747235a60ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/crossValidation.py", "max_issues_repo_name": "iesus/thesis-production-models", "max_issues_repo_head_hexsha": "38bf703db513ffeed5a533590fbae747235a60ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/crossValidation.py", "max_forks_repo_name": "iesus/thesis-production-models", "max_forks_repo_head_hexsha": "38bf703db513ffeed5a533590fbae747235a60ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5688888889, "max_line_length": 112, "alphanum_fraction": 0.6722511615, "include": true, "reason": "import numpy", "num_tokens": 1880}
|
# from __future__ import absolute_import
# from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
import glob
import numpy as np
from PIL import Image
def main():
data = '/data/zming/GH/manji/2000_labeled_sample_head'
folders = os.listdir(data)
folders.sort()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
with open(os.path.join(data, 'bad_images.txt'), 'w') as f_badimg:
image_num = 0
for fold in folders:
if not os.path.isdir(os.path.join(data, fold)):
continue
images_path = glob.glob(os.path.join(data, fold, '*.png'))
images_path.sort()
for image_path in images_path:
image_num += 1
#print ('\r','%s'%image_path, end = '')
print(image_path)
filename_queue = tf.train.string_input_producer([image_path]) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.
init_op = tf.global_variables_initializer()
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
try:
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
# print(image.shape)
# Image.fromarray(np.asarray(image)).show()
except:
print('!!!!!!!!!!!!! %s'%image_path)
f_badimg.write(image_path)
continue
f_badimg.close()
coord.request_stop()
coord.join(threads)
if __name__ == '__main__':
main()
|
{"hexsha": "929ddb0a7e540d04b9f5ed46356ad9247fca749d", "size": 2241, "ext": "py", "lang": "Python", "max_stars_repo_path": "handrecog/src/util/check_bad_tf_decodepng.py", "max_stars_repo_name": "hengxyz/hand_detection_recognition", "max_stars_repo_head_hexsha": "317545056886d7b85947f9258c4cc02e98cfd2fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "handrecog/src/util/check_bad_tf_decodepng.py", "max_issues_repo_name": "hengxyz/hand_detection_recognition", "max_issues_repo_head_hexsha": "317545056886d7b85947f9258c4cc02e98cfd2fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "handrecog/src/util/check_bad_tf_decodepng.py", "max_forks_repo_name": "hengxyz/hand_detection_recognition", "max_forks_repo_head_hexsha": "317545056886d7b85947f9258c4cc02e98cfd2fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1451612903, "max_line_length": 106, "alphanum_fraction": 0.5443998215, "include": true, "reason": "import numpy", "num_tokens": 439}
|
from nets.yolo3 import yolo_body
from keras.layers import Input
from yolo import YOLO
from PIL import Image
import numpy as np
from datetime import datetime
if __name__ == '__main__':
yolo = YOLO()
# x = 10
# photo = []
# with open('2007_test.txt') as f:
# file = f.readlines()
# # print(file[0])
# for line in file:
# photo.append(line.split()[0])
# np.random.seed(int(datetime.timestamp(datetime.now())))
# np.random.shuffle(photo)
# np.random.seed(None)
# for i in range(x):
if True:
# img = input('Input image filename:')
img ='E:/CMPE_master_project/photo/v1780.jpg'
# print(photo[i])
try:
image = Image.open(img)
except:
print('Open Error! Try again!')
# continue
else:
# [[type,[top,left,bottom,right],score]
boxes = yolo.detect_image_boxes(image)
print(boxes)
r_image = yolo.detect_image(image)
r_image.show()
yolo.close_session()
|
{"hexsha": "25914e8e27f1597990d5b1b8de3e77bd6d8ef312", "size": 1054, "ext": "py", "lang": "Python", "max_stars_repo_path": "predict.py", "max_stars_repo_name": "robert4213/Plant_detection_Application", "max_stars_repo_head_hexsha": "807267adefcec37f02d1480a9ddbb49169fdbd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predict.py", "max_issues_repo_name": "robert4213/Plant_detection_Application", "max_issues_repo_head_hexsha": "807267adefcec37f02d1480a9ddbb49169fdbd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predict.py", "max_forks_repo_name": "robert4213/Plant_detection_Application", "max_forks_repo_head_hexsha": "807267adefcec37f02d1480a9ddbb49169fdbd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0256410256, "max_line_length": 61, "alphanum_fraction": 0.5702087287, "include": true, "reason": "import numpy", "num_tokens": 260}
|
[STATEMENT]
lemma hoare_cnvalid:
assumes hoare: "\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F\<^esub> P c Q,A"
shows "\<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
using hoare
[PROOF STATE]
proof (prove)
using this:
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c Q,A
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
proof (induct)
[PROOF STATE]
proof (state)
goal (15 subgoals):
1. \<And>\<Theta> F Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> Q Skip Q,A
2. \<And>\<Theta> F f Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> Q} Basic f Q,A
3. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
4. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
5. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
6. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
7. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
8. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
9. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
10. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
A total of 15 subgoals...
[PROOF STEP]
case (Skip \<Theta> F P A)
[PROOF STATE]
proof (state)
this:
goal (15 subgoals):
1. \<And>\<Theta> F Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> Q Skip Q,A
2. \<And>\<Theta> F f Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> Q} Basic f Q,A
3. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
4. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
5. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
6. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
7. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
8. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
9. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
10. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
A total of 15 subgoals...
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P Skip P,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Skip P,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Skip,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Skip,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
assume "\<Gamma>\<turnstile>\<langle>Skip,Normal s\<rangle> =n\<Rightarrow> t" "s \<in> P"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Skip,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Skip,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
thus "t \<in> Normal ` P \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Skip,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
goal (1 subgoal):
1. t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` P \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Skip P,A
goal (14 subgoals):
1. \<And>\<Theta> F f Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> Q} Basic f Q,A
2. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
3. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
4. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
5. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
6. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
7. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
8. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
10. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
A total of 14 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (14 subgoals):
1. \<And>\<Theta> F f Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> Q} Basic f Q,A
2. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
3. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
4. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
5. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
6. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
7. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
8. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
10. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
A total of 14 subgoals...
[PROOF STEP]
case (Basic \<Theta> F f P A)
[PROOF STATE]
proof (state)
this:
goal (14 subgoals):
1. \<And>\<Theta> F f Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> Q} Basic f Q,A
2. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
3. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
4. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
5. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
6. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
7. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
8. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
10. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
A total of 14 subgoals...
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> P} (Basic f) P,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> P} Basic f P,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> t; s \<in> {s. f s \<in> P}; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> t; s \<in> {s. f s \<in> P}; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
assume "\<Gamma>\<turnstile>\<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> t" "s \<in> {s. f s \<in> P}"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> t
s \<in> {s. f s \<in> P}
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> t; s \<in> {s. f s \<in> P}; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
thus "t \<in> Normal ` P \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Basic f,Normal s\<rangle> =n\<Rightarrow> t
s \<in> {s. f s \<in> P}
goal (1 subgoal):
1. t \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` P \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. f s \<in> P} Basic f P,A
goal (13 subgoals):
1. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
2. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
4. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
5. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
6. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
7. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
9. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
10. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
A total of 13 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (13 subgoals):
1. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
2. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
4. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
5. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
6. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
7. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
9. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
10. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
A total of 13 subgoals...
[PROOF STEP]
case (Spec \<Theta> F r Q A)
[PROOF STATE]
proof (state)
this:
goal (13 subgoals):
1. \<And>\<Theta> F r Q A n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
2. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
4. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
5. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
6. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
7. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
9. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
10. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
A total of 13 subgoals...
[PROOF STEP]
show "\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t; s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t; s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t; s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P: "s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}"
[PROOF STATE]
proof (state)
this:
s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t; s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec P
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t
s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Spec r,Normal s\<rangle> =n\<Rightarrow> t
s \<in> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)}
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> {s. (\<forall>t. (s, t) \<in> r \<longrightarrow> t \<in> Q) \<and> (\<exists>t. (s, t) \<in> r)} Spec r Q,A
goal (12 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
4. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
5. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
6. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
8. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
9. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
10. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
A total of 12 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (12 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
4. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
5. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
6. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
8. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
9. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
10. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
A total of 12 subgoals...
[PROOF STEP]
case (Seq \<Theta> F P c1 R A c2 Q)
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c1 R,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> P c1 R,A
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c2 Q,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> R c2 Q,A
goal (12 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
4. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
5. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
6. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
8. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
9. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
10. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
A total of 12 subgoals...
[PROOF STEP]
have valid_c1: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P c1 R,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c1 R,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> P c1 R,A
goal (12 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
4. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
5. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
6. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
8. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
9. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
10. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
A total of 12 subgoals...
[PROOF STEP]
have valid_c2: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> R c2 Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c2 Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> R c2 Q,A
goal (12 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 R A c\<^sub>2 Q n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 R,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 R,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
3. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
4. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
5. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
6. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
8. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
9. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
10. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
A total of 12 subgoals...
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P Seq c1 c2 Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c1 c2 Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P: "s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec P
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
[PROOF STEP]
obtain r where
exec_c1: "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> r" and exec_c2: "\<Gamma>\<turnstile>\<langle>c2,r\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
goal (1 subgoal):
1. (\<And>r. \<lbrakk>\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> r; \<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with t_notin_F
[PROOF STATE]
proof (chain)
picking this:
t \<notin> Fault ` F
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t
[PROOF STEP]
have "r \<notin> Fault ` F"
[PROOF STATE]
proof (prove)
using this:
t \<notin> Fault ` F
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. r \<notin> Fault ` F
[PROOF STEP]
by (auto dest: execn_Fault_end)
[PROOF STATE]
proof (state)
this:
r \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with valid_c1 ctxt exec_c1 P
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> P c1 R,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> r
s \<in> P
r \<notin> Fault ` F
[PROOF STEP]
have r: "r\<in>Normal ` R \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> P c1 R,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> r
s \<in> P
r \<notin> Fault ` F
goal (1 subgoal):
1. r \<in> Normal ` R \<union> Abrupt ` A
[PROOF STEP]
by (rule cnvalidD)
[PROOF STATE]
proof (state)
this:
r \<in> Normal ` R \<union> Abrupt ` A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Seq c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
show "t\<in>Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
proof (cases r)
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. \<And>x1. r = Normal x1 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>x2. r = Abrupt x2 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
3. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
4. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
case (Normal r')
[PROOF STATE]
proof (state)
this:
r = Normal r'
goal (4 subgoals):
1. \<And>x1. r = Normal x1 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>x2. r = Abrupt x2 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
3. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
4. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with exec_c2 r
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t
r \<in> Normal ` R \<union> Abrupt ` A
r = Normal r'
[PROOF STEP]
show "t\<in>Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t
r \<in> Normal ` R \<union> Abrupt ` A
r = Normal r'
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
apply -
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t; r \<in> Normal ` R \<union> Abrupt ` A; r = Normal r'\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
apply (rule cnvalidD [OF valid_c2 ctxt _ _ t_notin_F])
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t; r \<in> Normal ` R \<union> Abrupt ` A; r = Normal r'\<rbrakk> \<Longrightarrow> \<Gamma>\<turnstile> \<langle>c2,Normal ?s3\<rangle> =n\<Rightarrow> t
2. \<lbrakk>\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t; r \<in> Normal ` R \<union> Abrupt ` A; r = Normal r'\<rbrakk> \<Longrightarrow> ?s3 \<in> R
[PROOF STEP]
apply auto
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal (3 subgoals):
1. \<And>x2. r = Abrupt x2 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
3. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. \<And>x2. r = Abrupt x2 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
3. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
case (Abrupt r')
[PROOF STATE]
proof (state)
this:
r = Abrupt r'
goal (3 subgoals):
1. \<And>x2. r = Abrupt x2 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
3. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with exec_c2
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t
r = Abrupt r'
[PROOF STEP]
have "t=Abrupt r'"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>c2,r\<rangle> =n\<Rightarrow> t
r = Abrupt r'
goal (1 subgoal):
1. t = Abrupt r'
[PROOF STEP]
by (auto elim: execn_elim_cases)
[PROOF STATE]
proof (state)
this:
t = Abrupt r'
goal (3 subgoals):
1. \<And>x2. r = Abrupt x2 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
3. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with Abrupt r
[PROOF STATE]
proof (chain)
picking this:
r = Abrupt r'
r \<in> Normal ` R \<union> Abrupt ` A
t = Abrupt r'
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
r = Abrupt r'
r \<in> Normal ` R \<union> Abrupt ` A
t = Abrupt r'
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal (2 subgoals):
1. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
case Fault
[PROOF STATE]
proof (state)
this:
r = Fault x3_
goal (2 subgoals):
1. \<And>x3. r = Fault x3 \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with r
[PROOF STATE]
proof (chain)
picking this:
r \<in> Normal ` R \<union> Abrupt ` A
r = Fault x3_
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
r \<in> Normal ` R \<union> Abrupt ` A
r = Fault x3_
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal (1 subgoal):
1. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
case Stuck
[PROOF STATE]
proof (state)
this:
r = Stuck
goal (1 subgoal):
1. r = Stuck \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with r
[PROOF STATE]
proof (chain)
picking this:
r \<in> Normal ` R \<union> Abrupt ` A
r = Stuck
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
r \<in> Normal ` R \<union> Abrupt ` A
r = Stuck
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Seq c1 c2 Q,A
goal (11 subgoals):
1. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
3. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
4. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
5. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
7. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
8. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
10. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
A total of 11 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (11 subgoals):
1. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
3. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
4. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
5. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
7. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
8. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
10. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
A total of 11 subgoals...
[PROOF STEP]
case (Cond \<Theta> F P b c1 Q A c2)
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c1 Q,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c1 Q,A
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c2 Q,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> - b) c2 Q,A
goal (11 subgoals):
1. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
3. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
4. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
5. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
7. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
8. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
10. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
A total of 11 subgoals...
[PROOF STEP]
have valid_c1: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c1 Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c1 Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c1 Q,A
goal (11 subgoals):
1. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
3. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
4. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
5. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
7. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
8. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
10. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
A total of 11 subgoals...
[PROOF STEP]
have valid_c2: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c2 Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c2 Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> - b) c2 Q,A
goal (11 subgoals):
1. \<And>\<Theta> F P b c\<^sub>1 Q A c\<^sub>2 n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c\<^sub>1 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c\<^sub>1 Q,A; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> - b) c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> - b) c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c\<^sub>1 c\<^sub>2 Q,A
2. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
3. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
4. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
5. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
7. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
8. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
9. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
10. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
A total of 11 subgoals...
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c1 c2 Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c1 c2 Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P: "s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
proof (cases "s\<in>b")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
s \<in> b
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with exec
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t
s \<in> b
[PROOF STEP]
have "\<Gamma>\<turnstile>\<langle>c1,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t
s \<in> b
goal (1 subgoal):
1. \<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> t
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with P True
[PROOF STATE]
proof (chain)
picking this:
s \<in> P
s \<in> b
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
s \<in> P
s \<in> b
\<Gamma>\<turnstile> \<langle>c1,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by - (rule cnvalidD [OF valid_c1 ctxt _ _ t_notin_F],auto)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
s \<notin> b
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with exec P
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
s \<notin> b
[PROOF STEP]
have "\<Gamma>\<turnstile>\<langle>c2,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Cond b c1 c2,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
s \<notin> b
goal (1 subgoal):
1. \<Gamma>\<turnstile> \<langle>c2,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c2,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with P False
[PROOF STATE]
proof (chain)
picking this:
s \<in> P
s \<notin> b
\<Gamma>\<turnstile> \<langle>c2,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
s \<in> P
s \<notin> b
\<Gamma>\<turnstile> \<langle>c2,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by - (rule cnvalidD [OF valid_c2 ctxt _ _ t_notin_F],auto)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Cond b c1 c2 Q,A
goal (10 subgoals):
1. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
2. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
3. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
4. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
6. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
7. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
8. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
9. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
10. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (10 subgoals):
1. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
2. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
3. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
4. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
6. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
7. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
8. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
9. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
10. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (While \<Theta> F P b c A n)
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A
goal (10 subgoals):
1. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
2. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
3. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
4. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
6. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
7. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
8. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
9. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
10. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have valid_c: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A
goal (10 subgoals):
1. \<And>\<Theta> F P b c A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(P \<inter> b) c P,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
2. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
3. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
4. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
6. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
7. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
8. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
9. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
10. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
assume P: "s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
show "t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
proof (cases "s \<in> b")
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
case True
[PROOF STATE]
proof (state)
this:
s \<in> b
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
{
[PROOF STATE]
proof (state)
this:
s \<in> b
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
fix d::"('b,'a,'c) com"
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. s__ \<in> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s__ \<notin> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>d,s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>d,s\<rangle> =n\<Rightarrow> t
goal (2 subgoals):
1. s__ \<in> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s__ \<notin> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
assume d: "d=While b c"
[PROOF STATE]
proof (state)
this:
d = While b c
goal (2 subgoals):
1. s__ \<in> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s__ \<notin> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (2 subgoals):
1. s__ \<in> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s__ \<notin> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
from exec d ctxt
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>d,s\<rangle> =n\<Rightarrow> t
d = While b c
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
have "\<lbrakk>s \<in> Normal ` P; t \<notin> Fault ` F\<rbrakk>
\<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt`A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>d,s\<rangle> =n\<Rightarrow> t
d = While b c
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<lbrakk>s \<in> Normal ` P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
proof (induct)
[PROOF STATE]
proof (state)
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
case (WhileTrue s b' c' n r t)
[PROOF STATE]
proof (state)
this:
s \<in> b'
\<Gamma>\<turnstile> \<langle>c',Normal s\<rangle> =n\<Rightarrow> r
\<lbrakk>Normal s \<in> Normal ` P; r \<notin> Fault ` F; c' = While b c; \<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c\<rbrakk> \<Longrightarrow> r \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
\<Gamma>\<turnstile> \<langle>While b' c',r\<rangle> =n\<Rightarrow> t
\<lbrakk>r \<in> Normal ` P; t \<notin> Fault ` F; While b' c' = While b c; \<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
Normal s \<in> Normal ` P
t \<notin> Fault ` F
While b' c' = While b c
\<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
have t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. t \<notin> Fault ` F
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
have eqs: "While b' c' = While b c"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. While b' c' = While b c
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
While b' c' = While b c
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
note valid_c
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
have ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
from WhileTrue
[PROOF STATE]
proof (chain)
picking this:
s \<in> b'
\<Gamma>\<turnstile> \<langle>c',Normal s\<rangle> =n\<Rightarrow> r
\<lbrakk>Normal s \<in> Normal ` P; r \<notin> Fault ` F; c' = While b c; \<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c\<rbrakk> \<Longrightarrow> r \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
\<Gamma>\<turnstile> \<langle>While b' c',r\<rangle> =n\<Rightarrow> t
\<lbrakk>r \<in> Normal ` P; t \<notin> Fault ` F; While b' c' = While b c; \<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
Normal s \<in> Normal ` P
t \<notin> Fault ` F
While b' c' = While b c
\<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c
[PROOF STEP]
obtain "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> r" and
"\<Gamma>\<turnstile>\<langle>While b c,r\<rangle> =n\<Rightarrow> t" and
"Normal s \<in> Normal `(P \<inter> b)"
[PROOF STATE]
proof (prove)
using this:
s \<in> b'
\<Gamma>\<turnstile> \<langle>c',Normal s\<rangle> =n\<Rightarrow> r
\<lbrakk>Normal s \<in> Normal ` P; r \<notin> Fault ` F; c' = While b c; \<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c\<rbrakk> \<Longrightarrow> r \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
\<Gamma>\<turnstile> \<langle>While b' c',r\<rangle> =n\<Rightarrow> t
\<lbrakk>r \<in> Normal ` P; t \<notin> Fault ` F; While b' c' = While b c; \<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
Normal s \<in> Normal ` P
t \<notin> Fault ` F
While b' c' = While b c
\<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p a,c
goal (1 subgoal):
1. (\<lbrakk>\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> r; \<Gamma>\<turnstile> \<langle>While b c,r\<rangle> =n\<Rightarrow> t; Normal s \<in> Normal ` (P \<inter> b)\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>While b c,r\<rangle> =n\<Rightarrow> t
Normal s \<in> Normal ` (P \<inter> b)
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>While b c,r\<rangle> =n\<Rightarrow> t
Normal s \<in> Normal ` (P \<inter> b)
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
with t_notin_F
[PROOF STATE]
proof (chain)
picking this:
t \<notin> Fault ` F
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>While b c,r\<rangle> =n\<Rightarrow> t
Normal s \<in> Normal ` (P \<inter> b)
[PROOF STEP]
have "r \<notin> Fault ` F"
[PROOF STATE]
proof (prove)
using this:
t \<notin> Fault ` F
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>While b c,r\<rangle> =n\<Rightarrow> t
Normal s \<in> Normal ` (P \<inter> b)
goal (1 subgoal):
1. r \<notin> Fault ` F
[PROOF STEP]
by (auto dest: execn_Fault_end)
[PROOF STATE]
proof (state)
this:
r \<notin> Fault ` F
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>While b c,r\<rangle> =n\<Rightarrow> t
Normal s \<in> Normal ` (P \<inter> b)
r \<notin> Fault ` F
[PROOF STEP]
have r: "r \<in> Normal ` P \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (P \<inter> b) c P,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> r
\<Gamma>\<turnstile> \<langle>While b c,r\<rangle> =n\<Rightarrow> t
Normal s \<in> Normal ` (P \<inter> b)
r \<notin> Fault ` F
goal (1 subgoal):
1. r \<in> Normal ` P \<union> Abrupt ` A
[PROOF STEP]
by - (rule cnvalidD,auto)
[PROOF STATE]
proof (state)
this:
r \<in> Normal ` P \<union> Abrupt ` A
goal (20 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 20 subgoals...
[PROOF STEP]
from this _ ctxt
[PROOF STATE]
proof (chain)
picking this:
r \<in> Normal ` P \<union> Abrupt ` A
PROP ?psi \<Longrightarrow> PROP ?psi
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
show "t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A "
[PROOF STATE]
proof (prove)
using this:
r \<in> Normal ` P \<union> Abrupt ` A
PROP ?psi \<Longrightarrow> PROP ?psi
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
proof (cases r)
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. \<And>x1. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Normal x1\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>x2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Abrupt x2\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
case (Normal r')
[PROOF STATE]
proof (state)
this:
r = Normal r'
goal (4 subgoals):
1. \<And>x1. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Normal x1\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>x2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Abrupt x2\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with r ctxt eqs t_notin_F
[PROOF STATE]
proof (chain)
picking this:
r \<in> Normal ` P \<union> Abrupt ` A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
While b' c' = While b c
t \<notin> Fault ` F
r = Normal r'
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
r \<in> Normal ` P \<union> Abrupt ` A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
While b' c' = While b c
t \<notin> Fault ` F
r = Normal r'
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
by - (rule WhileTrue.hyps,auto)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (3 subgoals):
1. \<And>x2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Abrupt x2\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. \<And>x2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Abrupt x2\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
case (Abrupt r')
[PROOF STATE]
proof (state)
this:
r = Abrupt r'
goal (3 subgoals):
1. \<And>x2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Abrupt x2\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
have "\<Gamma>\<turnstile>\<langle>While b' c',r\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>\<turnstile> \<langle>While b' c',r\<rangle> =n\<Rightarrow> t
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>While b' c',r\<rangle> =n\<Rightarrow> t
goal (3 subgoals):
1. \<And>x2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Abrupt x2\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with Abrupt
[PROOF STATE]
proof (chain)
picking this:
r = Abrupt r'
\<Gamma>\<turnstile> \<langle>While b' c',r\<rangle> =n\<Rightarrow> t
[PROOF STEP]
have "t=r"
[PROOF STATE]
proof (prove)
using this:
r = Abrupt r'
\<Gamma>\<turnstile> \<langle>While b' c',r\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. t = r
[PROOF STEP]
by (auto dest: execn_Abrupt_end)
[PROOF STATE]
proof (state)
this:
t = r
goal (3 subgoals):
1. \<And>x2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Abrupt x2\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with r Abrupt
[PROOF STATE]
proof (chain)
picking this:
r \<in> Normal ` P \<union> Abrupt ` A
r = Abrupt r'
t = r
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
r \<in> Normal ` P \<union> Abrupt ` A
r = Abrupt r'
t = r
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (2 subgoals):
1. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
case Fault
[PROOF STATE]
proof (state)
this:
r = Fault x3_
goal (2 subgoals):
1. \<And>x3. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Fault x3\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with r
[PROOF STATE]
proof (chain)
picking this:
r \<in> Normal ` P \<union> Abrupt ` A
r = Fault x3_
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
r \<in> Normal ` P \<union> Abrupt ` A
r = Fault x3_
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (1 subgoal):
1. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
case Stuck
[PROOF STATE]
proof (state)
this:
r = Stuck
goal (1 subgoal):
1. \<lbrakk>r \<in> Normal ` P \<union> Abrupt ` A; \<And>psi. PROP psi \<Longrightarrow> PROP psi; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; r = Stuck\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with r
[PROOF STATE]
proof (chain)
picking this:
r \<in> Normal ` P \<union> Abrupt ` A
r = Stuck
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
r \<in> Normal ` P \<union> Abrupt ` A
r = Stuck
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (19 subgoals):
1. \<And>s n. \<lbrakk>Normal s \<in> Normal ` P; Normal s \<notin> Fault ` F; Skip = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal s \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. \<And>s g c n t f. \<lbrakk>s \<in> g; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
3. \<And>s g f c n. \<lbrakk>s \<notin> g; Normal s \<in> Normal ` P; Fault f \<notin> Fault ` F; Guard f g c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
4. \<And>c f n. \<lbrakk>Fault f \<in> Normal ` P; Fault f \<notin> Fault ` F; c = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Fault f \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
5. \<And>f s n. \<lbrakk>Normal s \<in> Normal ` P; Normal (f s) \<notin> Fault ` F; Basic f = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal (f s) \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
6. \<And>s t r n. \<lbrakk>(s, t) \<in> r; Normal s \<in> Normal ` P; Normal t \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Normal t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
7. \<And>s r n. \<lbrakk>\<forall>t. (s, t) \<notin> r; Normal s \<in> Normal ` P; Stuck \<notin> Fault ` F; Spec r = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> Stuck \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
8. \<And>c\<^sub>1 s n s' c\<^sub>2 t. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> s'; \<lbrakk>Normal s \<in> Normal ` P; s' \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> s' \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; \<Gamma>\<turnstile> \<langle>c\<^sub>2,s'\<rangle> =n\<Rightarrow> t; \<lbrakk>s' \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Seq c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
9. \<And>s ba c\<^sub>1 n t c\<^sub>2. \<lbrakk>s \<in> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>1 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
10. \<And>s ba c\<^sub>2 n t c\<^sub>1. \<lbrakk>s \<notin> ba; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; \<lbrakk>Normal s \<in> Normal ` P; t \<notin> Fault ` F; c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A; Normal s \<in> Normal ` P; t \<notin> Fault ` F; Cond ba c\<^sub>1 c\<^sub>2 = While b c; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
A total of 19 subgoals...
[PROOF STEP]
qed auto
[PROOF STATE]
proof (state)
this:
\<lbrakk>s \<in> Normal ` P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (2 subgoals):
1. s__ \<in> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s__ \<notin> b \<Longrightarrow> t__ \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<Gamma>\<turnstile> \<langle>?d2,?sa2\<rangle> =n\<Rightarrow> ?ta2; ?d2 = While b c; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; ?sa2 \<in> Normal ` P; ?ta2 \<notin> Fault ` F\<rbrakk> \<Longrightarrow> ?ta2 \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (2 subgoals):
1. s \<in> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
2. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with exec ctxt P t_notin_F
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
s \<in> P
t \<notin> Fault ` F
\<lbrakk>\<Gamma>\<turnstile> \<langle>?d2,?sa2\<rangle> =n\<Rightarrow> ?ta2; ?d2 = While b c; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; ?sa2 \<in> Normal ` P; ?ta2 \<notin> Fault ` F\<rbrakk> \<Longrightarrow> ?ta2 \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
s \<in> P
t \<notin> Fault ` F
\<lbrakk>\<Gamma>\<turnstile> \<langle>?d2,?sa2\<rangle> =n\<Rightarrow> ?ta2; ?d2 = While b c; \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; ?sa2 \<in> Normal ` P; ?ta2 \<notin> Fault ` F\<rbrakk> \<Longrightarrow> ?ta2 \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
case False
[PROOF STATE]
proof (state)
this:
s \<notin> b
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with exec P
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
s \<notin> b
[PROOF STEP]
have "t=Normal s"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>While b c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
s \<notin> b
goal (1 subgoal):
1. t = Normal s
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
t = Normal s
goal (1 subgoal):
1. s \<notin> b \<Longrightarrow> t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
with P False
[PROOF STATE]
proof (chain)
picking this:
s \<in> P
s \<notin> b
t = Normal s
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
s \<in> P
s \<notin> b
t = Normal s
goal (1 subgoal):
1. t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` (P \<inter> - b) \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P While b c (P \<inter> - b),A
goal (9 subgoals):
1. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
2. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
3. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
5. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
6. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
8. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
9. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (9 subgoals):
1. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
2. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
3. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
5. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
6. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
8. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
9. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (Guard \<Theta> F g P c Q A f)
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
goal (9 subgoals):
1. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
2. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
3. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
5. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
6. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
8. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
9. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have valid_c: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
goal (9 subgoals):
1. \<And>\<Theta> F g P c Q A f n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
2. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
3. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
5. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
6. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
7. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
8. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
9. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> g \<inter> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> g \<inter> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> g \<inter> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> g \<inter> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> g \<inter> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P:"s \<in> (g \<inter> P)"
[PROOF STATE]
proof (state)
this:
s \<in> g \<inter> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> g \<inter> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec P
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> g \<inter> P
[PROOF STEP]
have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> g \<inter> P
goal (1 subgoal):
1. \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> g \<inter> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from valid_c ctxt this P t_notin_F
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> g \<inter> P
t \<notin> Fault ` F
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> g \<inter> P
t \<notin> Fault ` F
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by (rule cnvalidD)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) Guard f g c Q,A
goal (8 subgoals):
1. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
2. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
4. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
5. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
7. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (8 subgoals):
1. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
2. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
4. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
5. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
7. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (Guarantee f F \<Theta> g P c Q A)
[PROOF STATE]
proof (state)
this:
f \<in> F
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
goal (8 subgoals):
1. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
2. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
4. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
5. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
7. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have valid_c: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
goal (8 subgoals):
1. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
2. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
4. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
5. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
7. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have f_F: "f \<in> F"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. f \<in> F
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
f \<in> F
goal (8 subgoals):
1. \<And>f F \<Theta> g P c Q A n. \<lbrakk>f \<in> F; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>(g \<inter> P) c Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
2. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
4. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
5. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
6. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
7. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
8. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P:"s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec f_F t_notin_F
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
f \<in> F
t \<notin> Fault ` F
[PROOF STEP]
have g: "s \<in> g"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
f \<in> F
t \<notin> Fault ` F
goal (1 subgoal):
1. s \<in> g
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
s \<in> g
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with P
[PROOF STATE]
proof (chain)
picking this:
s \<in> P
s \<in> g
[PROOF STEP]
have P': "s \<in> g \<inter> P"
[PROOF STATE]
proof (prove)
using this:
s \<in> P
s \<in> g
goal (1 subgoal):
1. s \<in> g \<inter> P
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
s \<in> g \<inter> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec P g
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
s \<in> g
[PROOF STEP]
have "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P
s \<in> g
goal (1 subgoal):
1. \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
by cases auto
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Guard f g c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from valid_c ctxt this P' t_notin_F
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> g \<inter> P
t \<notin> Fault ` F
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> (g \<inter> P) c Q,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> g \<inter> P
t \<notin> Fault ` F
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by (rule cnvalidD)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Guard f g c Q,A
goal (7 subgoals):
1. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
3. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
4. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
6. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (7 subgoals):
1. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
3. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
4. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
6. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (CallRec P p Q A Specs \<Theta> F)
[PROOF STATE]
proof (state)
this:
(P, p, Q, A) \<in> Specs
\<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
goal (7 subgoals):
1. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
3. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
4. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
6. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have p: "(P,p,Q,A) \<in> Specs"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (P, p, Q, A) \<in> Specs
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
(P, p, Q, A) \<in> Specs
goal (7 subgoals):
1. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
3. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
4. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
6. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have valid_body:
"\<forall>(P,p,Q,A) \<in> Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs \<Turnstile>n:\<^bsub>/F\<^esub> P (the (\<Gamma> p)) Q,A)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>n:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
[PROOF STEP]
using CallRec.hyps
[PROOF STATE]
proof (prove)
using this:
(P, p, Q, A) \<in> Specs
\<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>n:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>n:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
goal (7 subgoals):
1. \<And>P p Q A Specs \<Theta> F n. \<lbrakk>(P, p, Q, A) \<in> Specs; \<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> \<Gamma>,\<Theta> \<union> Specs\<turnstile>\<^bsub>/F \<^esub>P the (\<Gamma> p) Q,A \<and> (\<forall>x. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>x:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
3. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
4. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
5. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
6. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
7. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
{
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
fix n
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n__:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
have "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A
\<Longrightarrow> \<forall>(P,p,Q,A) \<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A \<Longrightarrow> \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
proof (induct n)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P Call p x,y
2. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
case 0
[PROOF STATE]
proof (state)
this:
\<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P Call p a,c
goal (2 subgoals):
1. \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P Call p x,y
2. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
show "\<forall>(P,p,Q,A) \<in>Specs. \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by (fastforce elim!: execn_elim_cases simp add: nvalid_def)
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>0:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
case (Suc m)
[PROOF STATE]
proof (state)
this:
\<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p a,c \<Longrightarrow> \<forall>a\<in>Specs. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p a,c
\<forall>a\<in>\<Theta>. case a of (P, p, a, c) \<Rightarrow> \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p a,c
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
have hyp: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>m:\<^bsub>/F\<^esub> P (Call p) Q,A
\<Longrightarrow> \<forall>(P,p,Q,A) \<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A \<Longrightarrow> \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A \<Longrightarrow> \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
have "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>Suc m:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
hence ctxt_m: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>m:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
using this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by (fastforce simp add: nvalid_def intro: execn_Suc)
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
hence valid_Proc:
"\<forall>(P,p,Q,A) \<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
using this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by (rule hyp)
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
let ?\<Theta>'= "\<Theta> \<union> Specs"
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
from valid_Proc ctxt_m
[PROOF STATE]
proof (chain)
picking this:
\<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
have "\<forall>(P, p, Q, A)\<in>?\<Theta>'. \<Gamma> \<Turnstile>m:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
using this:
\<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>\<Theta> \<union> Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta> \<union> Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
with valid_body
[PROOF STATE]
proof (chain)
picking this:
\<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>n:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
\<forall>(P, p, Q, A)\<in>\<Theta> \<union> Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
have valid_body_m:
"\<forall>(P,p,Q,A) \<in>Specs. \<forall>n. \<Gamma> \<Turnstile>m:\<^bsub>/F\<^esub> P (the (\<Gamma> p)) Q,A"
[PROOF STATE]
proof (prove)
using this:
\<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>n:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
\<forall>(P, p, Q, A)\<in>\<Theta> \<union> Specs. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>Specs. \<forall>n. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A
[PROOF STEP]
by (fastforce simp add: cnvalid_def)
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>Specs. \<forall>n. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A
goal (1 subgoal):
1. \<And>n. \<lbrakk>\<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p x,y; \<forall>(P, p, x, y)\<in>\<Theta>. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y\<rbrakk> \<Longrightarrow> \<forall>(P, p, x, y)\<in>Specs. \<Gamma>\<Turnstile>Suc n:\<^bsub>/F\<^esub> P Call p x,y
[PROOF STEP]
show "\<forall>(P,p,Q,A) \<in>Specs. \<Gamma> \<Turnstile>Suc m:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
proof (clarify)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>a aa ab b. (a, aa, ab, b) \<in> Specs \<Longrightarrow> \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> a Call aa ab,b
[PROOF STEP]
fix P p Q A
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>a aa ab b. (a, aa, ab, b) \<in> Specs \<Longrightarrow> \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> a Call aa ab,b
[PROOF STEP]
assume p: "(P,p,Q,A) \<in> Specs"
[PROOF STATE]
proof (state)
this:
(P, p, Q, A) \<in> Specs
goal (1 subgoal):
1. \<And>a aa ab b. (a, aa, ab, b) \<in> Specs \<Longrightarrow> \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> a Call aa ab,b
[PROOF STEP]
show "\<Gamma> \<Turnstile>Suc m:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
proof (rule nvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec_call:
"\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume Pre: "s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec_call
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =Suc m\<Rightarrow> t
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
proof (cases)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>bdy n. \<lbrakk>Suc m = Suc n; \<Gamma> p = Some bdy; \<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix bdy m'
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>bdy n. \<lbrakk>Suc m = Suc n; \<Gamma> p = Some bdy; \<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume m: "Suc m = Suc m'"
[PROOF STATE]
proof (state)
this:
Suc m = Suc m'
goal (2 subgoals):
1. \<And>bdy n. \<lbrakk>Suc m = Suc n; \<Gamma> p = Some bdy; \<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume bdy: "\<Gamma> p = Some bdy"
[PROOF STATE]
proof (state)
this:
\<Gamma> p = Some bdy
goal (2 subgoals):
1. \<And>bdy n. \<lbrakk>Suc m = Suc n; \<Gamma> p = Some bdy; \<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec_body: "\<Gamma>\<turnstile>\<langle>bdy,Normal s\<rangle> =m'\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =m'\<Rightarrow> t
goal (2 subgoals):
1. \<And>bdy n. \<lbrakk>Suc m = Suc n; \<Gamma> p = Some bdy; \<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from Pre valid_body_m exec_body bdy m p t_notin_F
[PROOF STATE]
proof (chain)
picking this:
s \<in> P
\<forall>(P, p, Q, A)\<in>Specs. \<forall>n. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A
\<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =m'\<Rightarrow> t
\<Gamma> p = Some bdy
Suc m = Suc m'
(P, p, Q, A) \<in> Specs
t \<notin> Fault ` F
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
s \<in> P
\<forall>(P, p, Q, A)\<in>Specs. \<forall>n. \<Gamma>\<Turnstile>m:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A
\<Gamma>\<turnstile> \<langle>bdy,Normal s\<rangle> =m'\<Rightarrow> t
\<Gamma> p = Some bdy
Suc m = Suc m'
(P, p, Q, A) \<in> Specs
t \<notin> Fault ` F
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by (fastforce simp add: nvalid_def)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal (1 subgoal):
1. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume "\<Gamma> p = None"
[PROOF STATE]
proof (state)
this:
\<Gamma> p = None
goal (1 subgoal):
1. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with valid_body p
[PROOF STATE]
proof (chain)
picking this:
\<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>n:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
(P, p, Q, A) \<in> Specs
\<Gamma> p = None
[PROOF STEP]
have False
[PROOF STATE]
proof (prove)
using this:
\<forall>(P, p, Q, A)\<in>Specs. p \<in> dom \<Gamma> \<and> (\<forall>n. \<Gamma>,\<Theta> \<union> Specs\<Turnstile>n:\<^bsub>/F\<^esub> P the (\<Gamma> p) Q,A)
(P, p, Q, A) \<in> Specs
\<Gamma> p = None
goal (1 subgoal):
1. False
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
False
goal (1 subgoal):
1. \<And>n. \<lbrakk>Suc m = Suc n; t = Stuck; \<Gamma> p = None\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
thus ?thesis
[PROOF STATE]
proof (prove)
using this:
False
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
..
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p Q,A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>Suc m:\<^bsub>/F\<^esub> P Call p Q,A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A \<Longrightarrow> \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n__:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
}
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>?na2:\<^bsub>/F\<^esub> P Call p Q,A \<Longrightarrow> \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>?na2:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
with p
[PROOF STATE]
proof (chain)
picking this:
(P, p, Q, A) \<in> Specs
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>?na2:\<^bsub>/F\<^esub> P Call p Q,A \<Longrightarrow> \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>?na2:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
(P, p, Q, A) \<in> Specs
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>?na2:\<^bsub>/F\<^esub> P Call p Q,A \<Longrightarrow> \<forall>(P, p, Q, A)\<in>Specs. \<Gamma>\<Turnstile>?na2:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by (fastforce simp add: cnvalid_def)
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (6 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
2. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
3. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
5. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (6 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
2. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
3. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
5. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (DynCom P \<Theta> F c Q A)
[PROOF STATE]
proof (state)
this:
\<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A)
goal (6 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
2. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
3. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
5. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
hence valid_c: "\<forall>s\<in>P. (\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P (c s) Q,A)"
[PROOF STATE]
proof (prove)
using this:
\<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A)
goal (1 subgoal):
1. \<forall>s\<in>P. \<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c s Q,A
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<forall>s\<in>P. \<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c s Q,A
goal (6 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c s Q,A \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P c s Q,A) \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
2. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
3. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
4. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
5. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
6. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P: "s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_Fault: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>DynCom c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
proof (cases)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<Gamma>\<turnstile> \<langle>c s,Normal s\<rangle> =n\<Rightarrow> t \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume "\<Gamma>\<turnstile>\<langle>c s,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c s,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<Gamma>\<turnstile> \<langle>c s,Normal s\<rangle> =n\<Rightarrow> t \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from cnvalidD [OF valid_c [rule_format, OF P] ctxt this P t_notin_Fault]
[PROOF STATE]
proof (chain)
picking this:
t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P DynCom c Q,A
goal (5 subgoals):
1. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
2. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
4. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
5. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (5 subgoals):
1. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
2. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
4. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
5. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (Throw \<Theta> F A Q)
[PROOF STATE]
proof (state)
this:
goal (5 subgoals):
1. \<And>\<Theta> F A Q n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
2. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
3. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
4. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
5. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t; s \<in> A; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t; s \<in> A; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume "\<Gamma>\<turnstile>\<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t" "s \<in> A"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t
s \<in> A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t; s \<in> A; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t
s \<in> A
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Throw,Normal s\<rangle> =n\<Rightarrow> t
s \<in> A
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by cases simp
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> A Throw Q,A
goal (4 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
3. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (4 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
3. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (Catch \<Theta> F P c\<^sub>1 Q R c\<^sub>2 A)
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R
\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A
goal (4 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
3. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have valid_c1: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R
goal (4 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
3. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have valid_c2: "\<And>n. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>?n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A
goal (4 subgoals):
1. \<And>\<Theta> F P c\<^sub>1 Q R c\<^sub>2 A n. \<lbrakk>\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P c\<^sub>1 Q,R; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c\<^sub>1 Q,R; \<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>R c\<^sub>2 Q,A; \<And>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> R c\<^sub>2 Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
2. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
3. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
4. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P: "s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_Fault: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from exec
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> \<langle>Catch c\<^sub>1 c\<^sub>2,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
proof (cases)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>s'. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s'
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>s'. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec_c1: "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'
goal (2 subgoals):
1. \<And>s'. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec_c2: "\<Gamma>\<turnstile>\<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t
goal (2 subgoals):
1. \<And>s'. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from cnvalidD [OF valid_c1 ctxt exec_c1 P ]
[PROOF STATE]
proof (chain)
picking this:
Abrupt s' \<notin> Fault ` F \<Longrightarrow> Abrupt s' \<in> Normal ` Q \<union> Abrupt ` R
[PROOF STEP]
have "Abrupt s' \<in> Abrupt ` R"
[PROOF STATE]
proof (prove)
using this:
Abrupt s' \<notin> Fault ` F \<Longrightarrow> Abrupt s' \<in> Normal ` Q \<union> Abrupt ` R
goal (1 subgoal):
1. Abrupt s' \<in> Abrupt ` R
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
Abrupt s' \<in> Abrupt ` R
goal (2 subgoals):
1. \<And>s'. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> Abrupt s'; \<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
2. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with cnvalidD [OF valid_c2 ctxt _ _ t_notin_Fault] exec_c2
[PROOF STATE]
proof (chain)
picking this:
\<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal ?s\<rangle> =n\<Rightarrow> t; ?s \<in> R\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
\<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t
Abrupt s' \<in> Abrupt ` R
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal ?s\<rangle> =n\<Rightarrow> t; ?s \<in> R\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
\<Gamma>\<turnstile> \<langle>c\<^sub>2,Normal s'\<rangle> =n\<Rightarrow> t
Abrupt s' \<in> Abrupt ` R
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by fastforce
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal (1 subgoal):
1. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec_c1: "\<Gamma>\<turnstile>\<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume notAbr: "\<not> isAbr t"
[PROOF STATE]
proof (state)
this:
\<not> isAbr t
goal (1 subgoal):
1. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from cnvalidD [OF valid_c1 ctxt exec_c1 P t_notin_Fault]
[PROOF STATE]
proof (chain)
picking this:
t \<in> Normal ` Q \<union> Abrupt ` R
[PROOF STEP]
have "t \<in> Normal ` Q \<union> Abrupt ` R"
[PROOF STATE]
proof (prove)
using this:
t \<in> Normal ` Q \<union> Abrupt ` R
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` R
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` R
goal (1 subgoal):
1. \<lbrakk>\<Gamma>\<turnstile> \<langle>c\<^sub>1,Normal s\<rangle> =n\<Rightarrow> t; \<not> isAbr t\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with notAbr
[PROOF STATE]
proof (chain)
picking this:
\<not> isAbr t
t \<in> Normal ` Q \<union> Abrupt ` R
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<not> isAbr t
t \<in> Normal ` Q \<union> Abrupt ` R
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Catch c\<^sub>1 c\<^sub>2 Q,A
goal (3 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
2. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (3 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
2. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (Conseq P \<Theta> F c Q A)
[PROOF STATE]
proof (state)
this:
\<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A
goal (3 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
2. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
hence adapt: "\<forall>s \<in> P. (\<exists>P' Q' A'. \<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A' \<and>
s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A)"
[PROOF STATE]
proof (prove)
using this:
\<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A
goal (1 subgoal):
1. \<forall>s\<in>P. \<exists>P' Q' A'. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A' \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
\<forall>s\<in>P. \<exists>P' Q' A'. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A' \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A
goal (3 subgoals):
1. \<And>P \<Theta> F c Q A n. \<forall>s\<in>P. \<exists>P' Q' A'. (\<Gamma>,\<Theta>\<turnstile>\<^bsub>/F \<^esub>P' c Q',A' \<and> (\<forall>x. \<Gamma>,\<Theta>\<Turnstile>x:\<^bsub>/F\<^esub> P' c Q',A')) \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
2. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
3. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt:"\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>c,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume P: "s \<in> P"
[PROOF STATE]
proof (state)
this:
s \<in> P
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume t_notin_F: "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from P adapt
[PROOF STATE]
proof (chain)
picking this:
s \<in> P
\<forall>s\<in>P. \<exists>P' Q' A'. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A' \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A
[PROOF STEP]
obtain P' Q' A' Z where
spec: "\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A'" and
P': "s \<in> P'" and strengthen: "Q' \<subseteq> Q \<and> A' \<subseteq> A"
[PROOF STATE]
proof (prove)
using this:
s \<in> P
\<forall>s\<in>P. \<exists>P' Q' A'. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A' \<and> s \<in> P' \<and> Q' \<subseteq> Q \<and> A' \<subseteq> A
goal (1 subgoal):
1. (\<And>P' Q' A'. \<lbrakk>\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A'; s \<in> P'; Q' \<subseteq> Q \<and> A' \<subseteq> A\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A'
s \<in> P'
Q' \<subseteq> Q \<and> A' \<subseteq> A
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from spec [rule_format] ctxt exec P' t_notin_F
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A'
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P'
t \<notin> Fault ` F
[PROOF STEP]
have "t \<in> Normal ` Q' \<union> Abrupt ` A'"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P' c Q',A'
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
\<Gamma>\<turnstile> \<langle>c,Normal s\<rangle> =n\<Rightarrow> t
s \<in> P'
t \<notin> Fault ` F
goal (1 subgoal):
1. t \<in> Normal ` Q' \<union> Abrupt ` A'
[PROOF STEP]
by (rule cnvalidD)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q' \<union> Abrupt ` A'
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
with strengthen
[PROOF STATE]
proof (chain)
picking this:
Q' \<subseteq> Q \<and> A' \<subseteq> A
t \<in> Normal ` Q' \<union> Abrupt ` A'
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
Q' \<subseteq> Q \<and> A' \<subseteq> A
t \<in> Normal ` Q' \<union> Abrupt ` A'
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
goal (2 subgoals):
1. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case (Asm P p Q A \<Theta> F)
[PROOF STATE]
proof (state)
this:
(P, p, Q, A) \<in> \<Theta>
goal (2 subgoals):
1. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
have asm: "(P, p, Q, A) \<in> \<Theta>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (P, p, Q, A) \<in> \<Theta>
[PROOF STEP]
by fact
[PROOF STATE]
proof (state)
this:
(P, p, Q, A) \<in> \<Theta>
goal (2 subgoals):
1. \<And>P p Q A \<Theta> F n. (P, p, Q, A) \<in> \<Theta> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
2. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
show "\<Gamma>,\<Theta> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
proof (rule cnvalidI)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
fix s t
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume ctxt: "\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P (Call p) Q,A"
[PROOF STATE]
proof (state)
this:
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume exec: "\<Gamma>\<turnstile>\<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t"
[PROOF STATE]
proof (state)
this:
\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
from asm ctxt
[PROOF STATE]
proof (chain)
picking this:
(P, p, Q, A) \<in> \<Theta>
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
have "\<Gamma> \<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A"
[PROOF STATE]
proof (prove)
using this:
(P, p, Q, A) \<in> \<Theta>
\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
moreover
[PROOF STATE]
proof (state)
this:
\<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
assume "s \<in> P" "t \<notin> Fault ` F"
[PROOF STATE]
proof (state)
this:
s \<in> P
t \<notin> Fault ` F
goal (1 subgoal):
1. \<And>s t. \<lbrakk>\<forall>(P, p, Q, A)\<in>\<Theta>. \<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A; \<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t; s \<in> P; t \<notin> Fault ` F\<rbrakk> \<Longrightarrow> t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
ultimately
[PROOF STATE]
proof (chain)
picking this:
\<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
s \<in> P
t \<notin> Fault ` F
[PROOF STEP]
show "t \<in> Normal ` Q \<union> Abrupt ` A"
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
s \<in> P
t \<notin> Fault ` F
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
using exec
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
s \<in> P
t \<notin> Fault ` F
\<Gamma>\<turnstile> \<langle>Call p,Normal s\<rangle> =n\<Rightarrow> t
goal (1 subgoal):
1. t \<in> Normal ` Q \<union> Abrupt ` A
[PROOF STEP]
by (auto simp add: nvalid_def)
[PROOF STATE]
proof (state)
this:
t \<in> Normal ` Q \<union> Abrupt ` A
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P Call p Q,A
goal (1 subgoal):
1. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
case ExFalso
[PROOF STATE]
proof (state)
this:
\<forall>n. \<Gamma>,\<Theta>_\<Turnstile>n:\<^bsub>/F_\<^esub> P_ c_ Q_,A_
\<not> \<Gamma>\<Turnstile>\<^bsub>/F_\<^esub> P_ c_ Q_,A_
goal (1 subgoal):
1. \<And>\<Theta> F P c Q A n. \<lbrakk>\<forall>n. \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A; \<not> \<Gamma>\<Turnstile>\<^bsub>/F\<^esub> P c Q,A\<rbrakk> \<Longrightarrow> \<Gamma>,\<Theta>\<Turnstile>n:\<^bsub>/F\<^esub> P c Q,A
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
\<forall>n. \<Gamma>,\<Theta>_\<Turnstile>n:\<^bsub>/F_\<^esub> P_ c_ Q_,A_
\<not> \<Gamma>\<Turnstile>\<^bsub>/F_\<^esub> P_ c_ Q_,A_
goal (1 subgoal):
1. \<Gamma>,\<Theta>_\<Turnstile>n:\<^bsub>/F_\<^esub> P_ c_ Q_,A_
[PROOF STEP]
by iprover
[PROOF STATE]
proof (state)
this:
\<Gamma>,\<Theta>_\<Turnstile>n:\<^bsub>/F_\<^esub> P_ c_ Q_,A_
goal:
No subgoals!
[PROOF STEP]
qed
|
{"llama_tokens": 137187, "file": "Simpl_HoarePartialProps", "length": 426}
|
#include <boost/intrusive/Segment_tree/segment_tree_algorithms.hpp>
#include <boost/intrusive/Segment_tree/segment_tree_hook.hpp>
#include "boost/intrusive/Segment_tree/merging_function.hpp"
#include <boost/intrusive/Segment_tree/segment_tree_iterator.hpp>
#include<boost/intrusive/any_hook.hpp>
#include <boost/intrusive/detail/get_value_traits.hpp>
#include "boost/intrusive/options.hpp"
#include <boost/intrusive/detail/is_stateful_value_traits.hpp>
#include <boost/intrusive/detail/default_header_holder.hpp>
#include "boost/intrusive/detail/size_holder.hpp"
#include<iostream>
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/assert.hpp>
#include <boost/intrusive/pointer_traits.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/link_mode.hpp>
#include <boost/intrusive/detail/reverse_iterator.hpp>
#include <boost/intrusive/detail/uncast.hpp>
#include <boost/intrusive/detail/array_initializer.hpp>
#include <boost/intrusive/detail/exception_disposer.hpp>
#include <boost/intrusive/detail/equal_to_value.hpp>
#include <boost/intrusive/detail/key_nodeptr_comp.hpp>
#include <boost/intrusive/detail/simple_disposers.hpp>
#include <boost/intrusive/detail/algorithm.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/static_assert.hpp>
#include <boost/intrusive/detail/minimal_less_equal_header.hpp>//std::less
#include <cstddef> //std::size_t, etc.
namespace boost {
namespace intrusive {
struct default_segtree_hook_applier
{
template <class T>
struct apply
{
typedef typename T::default_segtree_hook type;
};
};
template<>
struct is_default_hook_tag<default_segtree_hook_applier>
{ static const bool value = true; };
struct segtree_defaults
{
typedef default_segtree_hook_applier proto_value_traits;
static const bool constant_time_size = true;
typedef std::size_t size_type;
typedef void header_holder_type;
};
/**
<ul>
<li> This class is main class where all the functions are defined</li>
<li> This class is derived in the "segment_tree" class </li>
*/
template<typename ValueTraits, class SizeType, bool ConstantTimeSize, typename HeaderHolder>
class segment_tree_impl
{
public:
typedef ValueTraits value_traits;
typedef typename value_traits::node_traits node_traits;
typedef typename node_traits::node node;
typedef typename node::node_ptr node_ptr;
typedef typename value_traits::pointer pointer;
typedef typename pointer_traits<pointer>::element_type value_type;
typedef typename pointer_traits<pointer>::reference reference;
typedef segment_tree_algorithms<node_traits> algo;
typedef typename value_type::data_type data_type;
typedef segtree_iterator<value_traits, false> iterator;
typedef segtree_iterator<value_traits, true> const_iterator;
typedef typename node_traits::const_node_ptr const_node_ptr;
typedef SizeType size_type;
///@cond
static const bool constant_time_size = ConstantTimeSize;
static const bool stateful_value_traits = detail::is_stateful_value_traits<value_traits>::value;
///@endcond
private:
struct data_t : public ValueTraits
{
typedef typename segment_tree_impl::value_traits value_traits;
explicit data_t(const value_traits &val_traits)
: value_traits(val_traits)
{}
size_type total_nodes=0,internal_nodes=0,nodecnt_run=1;
node_ptr root;
value_type *ptr;
} data_;
const value_traits &priv_value_traits() const
{
return data_;
}
value_traits &priv_value_traits()
{
return data_;
}
typedef typename boost::intrusive::value_traits_pointers
<ValueTraits>::const_value_traits_ptr const_value_traits_ptr;
const_value_traits_ptr priv_value_traits_ptr() const
{ return pointer_traits<const_value_traits_ptr>::pointer_to(this->priv_value_traits()); }
value_type *input;
int start,end;
public:
/*!
<ul>
<li> This function initialises all the variables and constructs segment tree for given inputs </li>
</ul>
\param input input array
\param start starting index of input
\param end last index of input
<p></p>
<b>Complexity : </b> O(N) */
segment_tree_impl(value_type input[],int start,int end)
:data_(value_traits())
{
this->input=input;
this->start=start;
this->end=end;
nodes_count(start,end);
data_.ptr=(value_type*)malloc((data_.internal_nodes)*sizeof(value_type));
initialisation(input,start,end,0);
data_.root=value_traits::to_node_ptr(data_.ptr[0]);
}
private:
void initialisation(value_type input[],int start,int end,int parent_pos)
{
if(start!=end)
{
int mid=(start+end)/2,left,right;
node_ptr parent=value_traits::to_node_ptr(data_.ptr[parent_pos]),left_child,right_child;
if(start==mid)
{
left_child=value_traits::to_node_ptr(input[start]);
}
else
{
left_child=value_traits::to_node_ptr(data_.ptr[data_.nodecnt_run]);
left=data_.nodecnt_run;
data_.nodecnt_run++;
}
if(mid+1==end)
{
right_child=value_traits::to_node_ptr(input[end]);
}
else
{
right_child=value_traits::to_node_ptr(data_.ptr[data_.nodecnt_run]);
right=data_.nodecnt_run;
data_.nodecnt_run++;
}
parent->left_child=left_child;
parent->right_child=right_child;
if(start!=mid)
initialisation(input,start,mid,left);
if(mid+1!=end)
initialisation(input,mid+1,end,right);
}
}
private:
void nodes_count(int start,int end)
{
data_.total_nodes++;
if(start==end)
{
return ;
}
data_.internal_nodes++;
int mid=(start+end)/2;
nodes_count(start,mid);
nodes_count(mid+1,end);
}
public:
/*!
<ul>
<li> This function builds the segment tree from the given inputs </li>
</ul>
\param func merging function
\return Nothing
<p> </p>
<b> Complexity </b> O(NLog(N)) where N is length of input array
*/
void build(auto func)
{
build_computation(input,start,end,func,data_.root);
}
private:
data_type build_computation(value_type *input,int start,int end,auto func,node_ptr &curr_node)
{
value_type* p=value_traits::to_value_ptr(curr_node);
if(start==end)
{
return p->value;
}
int mid=(start+end)/2;
node_ptr left_ptr=node_traits::get_left_child(curr_node);
node_ptr right_ptr=node_traits::get_right_child(curr_node);
data_type left_value=build_computation(input,start,mid,func,left_ptr);
data_type right_value=build_computation(input,mid+1,end,func,right_ptr);
p->value=func(left_value,right_value);
return p->value;
}
public:
/*!
<ul>
<li> This updates the segment tree according to given inputs </li>
<li> This supports only single update i.e only single element from input array needs to be updated </li>
</ul>
\param func merging function
\param index updated index
\return Nothing
<p> </p>
<b> Complexity: </b> O(Log(N)) where N is length of input array
*/
void update(auto func,int index)
{
update_computation(input,start,end,func,index,data_.root);
}
private:
data_type update_computation(value_type input[],int start,int end,auto func,int index,node_ptr &curr_node)
{
pointer p=value_traits::to_value_ptr(curr_node);
if(start==end && start==index)
{
return p->value;
}
if(index>end || index<start)
{
return p->value;
}
int mid=(start+end)/2;
node_ptr left_ptr=node_traits::get_left_child(curr_node);
node_ptr right_ptr=node_traits::get_right_child(curr_node);
p->value=func(update_computation(input,start,mid,func,index,left_ptr),update_computation(input,mid+1,end,func,index,right_ptr));
return p->value;
}
private:
int range_nodes=0;
public:
/*!
<ul>
<li> This function queries the segment tree according to given inputs </li>
<li> This is very useful operation as it has many applications. </li>
</ul>
\param func merging function
\param index updated index
\return Nothing
<p> </p>
<b> Complexity: </b> O(Log(N)) where N is length of input array
*/
data_type query(auto func,int query_start,int query_end)
{
data_type *required_values;
required_values=(data_type*)malloc(data_.total_nodes*sizeof(data_type));
query_computation(input,start,end,func,query_start,query_end,required_values,data_.root);
data_type final_value;
final_value=required_values[0];
for(int each=1;each<range_nodes;each++)
{
final_value=func(final_value,required_values[each]);
}
range_nodes=0;
return final_value;
}
private:
void query_computation(value_type input[],int start,int end,auto func,int query_start,int query_end,data_type *required_values,node_ptr &curr_node)
{
pointer p=value_traits::to_value_ptr(curr_node);
if(query_start<=start && end<=query_end)
{
required_values[range_nodes]=p->value;
range_nodes++;
return ;
}
if(query_start>end || start>query_end)
{
return ;
}
int mid=(start+end)/2;
node_ptr left_ptr=node_traits::get_left_child(curr_node);
node_ptr right_ptr=node_traits::get_right_child(curr_node);
query_computation(input,start,mid,func,query_start,query_end,required_values,left_ptr);
query_computation(input,mid+1,end,func,query_start,query_end,required_values,right_ptr);
}
public:
/*!
This returns an iterator to the root node or source node of fenwick tree.
*/
iterator get_root()
{
return iterator(data_.root, this->priv_value_traits_ptr());
}
/*!
This returns a const iterator to the root node or source node of fenwick tree.
*/
const_iterator const_get_root() const
{
return const_iterator(data_.root, this->priv_value_traits_ptr());
}
};
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void, class O3 = void, class O4 = void>
#endif
struct make_segment_tree
{
public:
typedef typename pack_options
< segtree_defaults,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4
#else
Options...
#endif
>::type packed_options;
typedef typename detail::get_value_traits
<T, typename packed_options::proto_value_traits>::type value_traits;
/*!
<ul>
<li>This is the main class which contains all the methods supported by segment tree.</li>
<li>This class is derived into "segment_tree" class by giving appropriate inputs.</li>
</ul>
*/
typedef segment_tree_impl
<value_traits,
typename packed_options::size_type,
packed_options::constant_time_size,
typename packed_options::header_holder_type
> implementation_defined;
typedef implementation_defined type;
};
#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4>
#else
template<class T, class ...Options>
#endif
class segment_tree
: public make_segment_tree<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4
#else
Options...
#endif
>::type
{
public:
typedef typename make_segment_tree
<T,
#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4
#else
Options...
#endif
>::type Base;
public:
typedef typename Base::value_traits value_traits;
typedef typename Base::iterator iterator;
public:
/*!
<ul>
<li> This is the first and main function used while working with any data structure.</li>
<li>This calls the "segment_tree_impl" function which does initialisation and declaration of variables.</li>
</ul>
*/
segment_tree(T input[],int start,int end)
: Base(input,start,end)
{
};
};
}
}
#endif
|
{"hexsha": "0f971c9cc04fee109ee5183c465bbcf3abfa9e45", "size": 12967, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/intrusive/Segment_tree/segment_tree.hpp", "max_stars_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_stars_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T18:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-22T17:12:44.000Z", "max_issues_repo_path": "include/boost/intrusive/Segment_tree/segment_tree.hpp", "max_issues_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_issues_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-05-31T10:01:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-26T15:14:26.000Z", "max_forks_repo_path": "include/boost/intrusive/Segment_tree/segment_tree.hpp", "max_forks_repo_name": "BoostGSoC18/Advanced-Intrusive", "max_forks_repo_head_hexsha": "30c465125c460e4bc2a9583ce00f0f706ed23e5a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6624685139, "max_line_length": 151, "alphanum_fraction": 0.6602143904, "num_tokens": 2994}
|
pushfirst!(LOAD_PATH, joinpath(@__DIR__, "..", "packages"))
import VSCodeLiveUnitTesting
popfirst!(LOAD_PATH)
VSCodeLiveUnitTesting.live_unit_test(ARGS[1], ARGS[2])
|
{"hexsha": "c289605357104b258ed9685c819c71e1e5f13c7c", "size": 166, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "scripts/tasks/task_liveunittesting.jl", "max_stars_repo_name": "novitk/julia-vscode", "max_stars_repo_head_hexsha": "a3ec5649a734b5c1dc09b0f40aa7a7aa6caac5d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 812, "max_stars_repo_stars_event_min_datetime": "2019-06-13T22:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:43:32.000Z", "max_issues_repo_path": "scripts/tasks/task_liveunittesting.jl", "max_issues_repo_name": "novitk/julia-vscode", "max_issues_repo_head_hexsha": "a3ec5649a734b5c1dc09b0f40aa7a7aa6caac5d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1765, "max_issues_repo_issues_event_min_datetime": "2019-06-12T16:28:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:05:12.000Z", "max_forks_repo_path": "scripts/tasks/task_liveunittesting.jl", "max_forks_repo_name": "novitk/julia-vscode", "max_forks_repo_head_hexsha": "a3ec5649a734b5c1dc09b0f40aa7a7aa6caac5d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 131, "max_forks_repo_forks_event_min_datetime": "2019-06-16T21:23:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T08:36:52.000Z", "avg_line_length": 27.6666666667, "max_line_length": 59, "alphanum_fraction": 0.7831325301, "num_tokens": 47}
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""Test code for softmax"""
import numpy as np
import pytest
import sys
import tvm
from tvm import topi
from tvm import te
import tvm.topi.testing
from tvm.topi.utils import get_const_tuple
from ..conftest import requires_hexagon_toolchain
dtype = tvm.testing.parameter(
"float16",
"float32",
)
# TODO(mehrdadh): add log_softmax to config
configs = {
"softmax": {
"topi": topi.nn.softmax,
"ref": tvm.topi.testing.softmax_python,
"dimensions": [2, 4],
},
}
# TODO(mehrdadh): larger size like (1, 16, 256, 256) would fail due to TVM_HEXAGON_RPC_BUFF_SIZE_BYTES
shapes = [(32, 10), (3, 4), (1, 16, 32, 32)]
softmax_operation, shape = tvm.testing.parameters(
*[
(name, shape)
for name, config in configs.items()
for shape in shapes
if len(shape) in config["dimensions"]
]
)
@requires_hexagon_toolchain
def test_softmax(hexagon_session, shape, dtype, softmax_operation):
if dtype == "float16":
pytest.xfail("float16 is not supported.")
A = te.placeholder(shape, dtype=dtype, name="A")
topi_op = configs[softmax_operation]["topi"]
B = topi_op(A, axis=1)
def get_ref_data(shape):
ref_func = tvm.topi.testing.softmax_python
a_np = np.random.uniform(size=shape).astype(dtype)
if len(shape) == 2:
b_np = ref_func(a_np)
elif len(shape) == 4:
_, c, h, w = a_np.shape
a_np_2d = a_np.transpose(0, 2, 3, 1).reshape(h * w, c)
b_np_2d = tvm.topi.testing.softmax_python(a_np_2d)
b_np = b_np_2d.reshape(1, h, w, c).transpose(0, 3, 1, 2)
return a_np, b_np
# get the test data
a_np, b_np = get_ref_data(shape)
target_hexagon = tvm.target.hexagon("v68")
with tvm.target.Target(target_hexagon):
fschedule = topi.hexagon.schedule_softmax
s = fschedule(B)
func = tvm.build(
s, [A, B], tvm.target.Target(target_hexagon, host=target_hexagon), name="softmax"
)
mod = hexagon_session.load_module(func)
dev = hexagon_session.device
a = tvm.nd.array(a_np, dev)
b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), dev)
mod["softmax"](a, b)
tvm.testing.assert_allclose(b.numpy(), b_np, rtol=1e-5)
if __name__ == "__main__":
sys.exit(pytest.main(sys.argv))
|
{"hexsha": "4825d1e52442f9cf1ef1bcb6697bf2c3143bc602", "size": 3126, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/python/contrib/test_hexagon/topi/test_softmax.py", "max_stars_repo_name": "pfk-beta/tvm", "max_stars_repo_head_hexsha": "5ecb8c384a66933fec8c7f033cba03337eb1a726", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 90, "max_stars_repo_stars_event_min_datetime": "2021-11-30T11:58:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:24:04.000Z", "max_issues_repo_path": "tests/python/contrib/test_hexagon/topi/test_softmax.py", "max_issues_repo_name": "pfk-beta/tvm", "max_issues_repo_head_hexsha": "5ecb8c384a66933fec8c7f033cba03337eb1a726", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 64, "max_issues_repo_issues_event_min_datetime": "2021-11-22T23:58:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T03:19:22.000Z", "max_forks_repo_path": "tests/python/contrib/test_hexagon/topi/test_softmax.py", "max_forks_repo_name": "pfk-beta/tvm", "max_forks_repo_head_hexsha": "5ecb8c384a66933fec8c7f033cba03337eb1a726", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27, "max_forks_repo_forks_event_min_datetime": "2021-12-09T22:39:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T23:21:48.000Z", "avg_line_length": 30.6470588235, "max_line_length": 102, "alphanum_fraction": 0.6730646193, "include": true, "reason": "import numpy", "num_tokens": 854}
|
section \<open>Translating Multitape TMs to Singletape TMs\<close>
text \<open>In this section we define the mapping from a multitape Turing machine to a singletape
Turing machine. We further define soundness of the translation via several relations
which establish a connection between configurations of both kinds of Turing machines.
The translation works both for deterministic and non-deterministic TMs. Moreover,
we verify a quadratic overhead in runtime.
\<close>
(* potential extension: add right-end marker, so that final phase can write original symbols of first tape onto tape, i.e.
replace tuple-symbols by original symbols; this could be useful if TMs with output are considered, i.e.,
where functions need to be computed *)
theory Multi_Single_TM_Translation
imports
Multitape_TM
Singletape_TM
STM_Renaming
begin
subsection \<open>Definition of the Translation\<close>
datatype 'a tuple_symbol = NO_HAT "'a" | HAT "'a"
datatype ('a, 'k) st_tape_symbol = ST_LE ("\<turnstile>") | TUPLE "'k \<Rightarrow> 'a tuple_symbol" | INP "'a"
datatype 'a sym_or_bullet = SYM "'a" | BULLET ("\<bullet>")
datatype ('a,'q,'k) st_states =
R\<^sub>1 "'a sym_or_bullet" |
R\<^sub>2 |
S\<^sub>0 'q |
S "'q" "'k \<Rightarrow> 'a sym_or_bullet" |
S\<^sub>1 "'q" "'k \<Rightarrow> 'a" |
E\<^sub>0 "'q" "'k \<Rightarrow> 'a" "'k \<Rightarrow> dir" |
E "'q" "'k \<Rightarrow> 'a sym_or_bullet" "'k \<Rightarrow> dir" |
Er "'q" "'k \<Rightarrow> 'a sym_or_bullet" "'k \<Rightarrow> dir" "'k set" |
El "'q" "'k \<Rightarrow> 'a sym_or_bullet" "'k \<Rightarrow> dir" "'k set" |
Em "'q" "'k \<Rightarrow> 'a sym_or_bullet" "'k \<Rightarrow> dir" "'k set"
type_synonym ('a,'q,'k)mt_rule = "'q \<times> ('k \<Rightarrow> 'a) \<times> 'q \<times> ('k \<Rightarrow> 'a) \<times> ('k \<Rightarrow> dir)"
context multitape_tm
begin
definition R1_Set where "R1_Set = SYM ` \<Sigma> \<union> {\<bullet>}"
definition gamma_set :: "('k \<Rightarrow> 'a tuple_symbol) set" where
"gamma_set = (UNIV :: 'k set) \<rightarrow> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>"
definition \<Gamma>' :: "('a, 'k) st_tape_symbol set" where
"\<Gamma>' = TUPLE ` gamma_set \<union> INP ` \<Sigma> \<union> {\<turnstile>}"
definition "func_set = (UNIV :: 'k set) \<rightarrow> SYM ` \<Gamma> \<union> {\<bullet>}"
definition blank' :: "('a, 'k) st_tape_symbol" where "blank' = TUPLE (\<lambda> _. NO_HAT blank)"
definition hatLE' :: "('a, 'k) st_tape_symbol" where "hatLE' = TUPLE (\<lambda> _. HAT LE)"
definition encSym :: "'a \<Rightarrow> ('a, 'k) st_tape_symbol" where "encSym a = (TUPLE (\<lambda> i. if i = 0 then NO_HAT a else NO_HAT blank))"
definition add_inp :: "('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> 'a sym_or_bullet) \<Rightarrow> ('k \<Rightarrow> 'a sym_or_bullet)" where
"add_inp inp inp2 = (\<lambda> k. case inp k of HAT s \<Rightarrow> SYM s | _ \<Rightarrow> inp2 k)"
definition project_inp :: "('k \<Rightarrow> 'a sym_or_bullet) \<Rightarrow> ('k \<Rightarrow> 'a)" where
"project_inp inp = (\<lambda> k. case inp k of SYM s \<Rightarrow> s)"
definition compute_idx_set :: "('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> 'a sym_or_bullet) \<Rightarrow> 'k set" where
"compute_idx_set tup ys = {i . tup i \<in> HAT ` \<Gamma> \<and> ys i \<in> SYM ` \<Gamma>}"
definition update_ys :: "('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> 'a sym_or_bullet) \<Rightarrow> ('k \<Rightarrow> 'a sym_or_bullet)" where
"update_ys tup ys = (\<lambda> k. if k \<in> (compute_idx_set tup ys) then \<bullet> else ys k)"
definition replace_sym :: "('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> 'a sym_or_bullet) \<Rightarrow> ('k \<Rightarrow> 'a tuple_symbol)" where
"replace_sym tup ys = (\<lambda> k. if k \<in> (compute_idx_set tup ys)
then (case ys k of SYM a \<Rightarrow> NO_HAT a)
else tup k)"
definition place_hats_to_dir :: "dir \<Rightarrow> ('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> dir) \<Rightarrow>'k set \<Rightarrow> ('k \<Rightarrow> 'a tuple_symbol)" where
"place_hats_to_dir dir tup ds I = (\<lambda> k. (case tup k of
NO_HAT a \<Rightarrow> if k \<in> I \<and> ds k = dir
then HAT a
else NO_HAT a
| HAT a \<Rightarrow> HAT a )) "
definition place_hats_R :: "('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> dir) \<Rightarrow>'k set \<Rightarrow> ('k \<Rightarrow> 'a tuple_symbol)" where
"place_hats_R = place_hats_to_dir dir.R"
definition place_hats_M :: "('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> dir) \<Rightarrow>'k set \<Rightarrow> ('k \<Rightarrow> 'a tuple_symbol)" where
"place_hats_M = place_hats_to_dir dir.N"
definition place_hats_L :: "('k \<Rightarrow> 'a tuple_symbol) \<Rightarrow> ('k \<Rightarrow> dir) \<Rightarrow>'k set \<Rightarrow> ('k \<Rightarrow> 'a tuple_symbol)" where
"place_hats_L = place_hats_to_dir dir.L"
definition \<delta>' ::
"(('a, 'q, 'k) st_states \<times> ('a, 'k) st_tape_symbol \<times> ('a, 'q, 'k) st_states \<times> ('a, 'k) st_tape_symbol \<times> dir)set"
where
"\<delta>' = ({(R\<^sub>1 \<bullet>, \<turnstile>, R\<^sub>1 \<bullet>, \<turnstile>, dir.R)})
\<union> (\<lambda> x. (R\<^sub>1 \<bullet>, INP x, R\<^sub>1 (SYM x), hatLE', dir.R)) ` \<Sigma>
\<union> (\<lambda> (a,x). (R\<^sub>1 (SYM a), INP x, R\<^sub>1 (SYM x), encSym a, dir.R)) ` (\<Sigma> \<times> \<Sigma>)
\<union> {(R\<^sub>1 \<bullet>, blank', R\<^sub>2, hatLE', dir.L)}
\<union> (\<lambda> a. (R\<^sub>1 (SYM a), blank', R\<^sub>2, encSym a, dir.L)) ` \<Sigma>
\<union> (\<lambda> x. (R\<^sub>2, x, R\<^sub>2, x, dir.L)) ` (\<Gamma>' - { \<turnstile> })
\<union> {(R\<^sub>2, \<turnstile>, S\<^sub>0 s, \<turnstile>, dir.N)}
\<union> (\<lambda> q. (S\<^sub>0 q, \<turnstile>, S q (\<lambda> _. \<bullet>), \<turnstile>, dir.R)) ` (Q - {t,r})
\<union> (\<lambda> (q,inp,t). (S q inp, TUPLE t, S q (add_inp t inp), TUPLE t, dir.R)) ` (Q \<times> (func_set - (UNIV \<rightarrow> SYM ` \<Gamma>)) \<times> gamma_set)
\<union> (\<lambda> (q,inp,a). (S q inp, a, S\<^sub>1 q (project_inp inp), a, dir.L)) ` (Q \<times> (UNIV \<rightarrow> SYM ` \<Gamma>) \<times> (\<Gamma>' - { \<turnstile> }))
\<union> (\<lambda> ((q,a,q',b,d),t). (S\<^sub>1 q a, t, E\<^sub>0 q' b d, t, dir.N)) ` (\<delta> \<times> \<Gamma>')
\<union> (\<lambda> ((q,a,d),t). (E\<^sub>0 q a d, t, E q (SYM o a) d, t, dir.N)) ` ((Q \<times> (UNIV \<rightarrow> \<Gamma>) \<times> UNIV) \<times> \<Gamma>')
\<union> (\<lambda> (q,d). (E q (\<lambda> _. \<bullet>) d, \<turnstile>, S\<^sub>0 q, \<turnstile>, dir.N)) ` (Q \<times> UNIV)
\<union> (\<lambda> (q,ys,ds,t). (E q ys ds, TUPLE t, Er q (update_ys t ys) ds (compute_idx_set t ys), TUPLE(replace_sym t ys), dir.R)) ` (Q \<times> func_set \<times> UNIV \<times> gamma_set)
\<union> (\<lambda> (q,ys,ds,I,t). (Er q ys ds I, TUPLE t, Em q ys ds I, TUPLE (place_hats_R t ds I), dir.L)) ` (Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set)
\<union> (\<lambda> (q,ys,ds,I,t). (Em q ys ds I, TUPLE t, El q ys ds I, TUPLE (place_hats_M t ds I), dir.L)) ` (Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set)
\<union> (\<lambda> (q,ys,ds,I,t). (El q ys ds I, TUPLE t, E q ys ds, TUPLE (place_hats_L t ds I), dir.N)) ` (Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set)
\<union> (\<lambda> (q,ys,ds,I). (El q ys ds I, \<turnstile>, E q ys ds, \<turnstile>, dir.N)) ` (Q \<times> func_set \<times> UNIV \<times> Pow(UNIV)) \<comment> \<open> first switch into E state, so E phase is always finished in E state\<close>
"
definition "Q' =
R\<^sub>1 ` R1_Set \<union> {R\<^sub>2} \<union>
S\<^sub>0 ` Q \<union> (\<lambda> (q,inp). S q inp) ` (Q \<times> func_set) \<union> (\<lambda> (q,a). S\<^sub>1 q a) ` (Q \<times> (UNIV \<rightarrow> \<Gamma>)) \<union>
(\<lambda> (q,a,d). E\<^sub>0 q a d) ` (Q \<times> (UNIV \<rightarrow> \<Gamma>) \<times> UNIV) \<union>
(\<lambda> (q,a,d). E q a d) ` (Q \<times> func_set \<times> UNIV) \<union>
(\<lambda> (q,a,d,I). Er q a d I) ` (Q \<times> func_set \<times> UNIV \<times> UNIV) \<union>
(\<lambda> (q,a,d,I). Em q a d I) ` (Q \<times> func_set \<times> UNIV \<times> UNIV) \<union>
(\<lambda> (q,a,d,I). El q a d I) ` (Q \<times> func_set \<times> UNIV \<times> UNIV)"
lemma compute_idx_range[simp,intro]:
assumes "tup \<in> gamma_set"
assumes "ys \<in> func_set"
shows "compute_idx_set tup ys \<in> UNIV"
by auto
lemma update_ys_range[simp,intro]:
assumes "tup \<in> gamma_set"
assumes "ys \<in> func_set"
shows "update_ys tup ys \<in> func_set"
by (insert assms, fastforce simp: update_ys_def func_set_def)
lemma replace_sym_range[simp,intro]:
assumes "tup \<in> gamma_set"
assumes "ys \<in> func_set"
shows "replace_sym tup ys \<in> gamma_set"
proof -
have "\<forall> k. (if k \<in> compute_idx_set tup ys then case ys k of SYM x \<Rightarrow> NO_HAT x else tup k) \<in> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>"
by(intro allI, insert assms, cases "k \<in> compute_idx_set tup ys", auto simp: func_set_def compute_idx_set_def gamma_set_def replace_sym_def)
then show ?thesis
using assms unfolding replace_sym_def gamma_set_def by blast
qed
lemma tup_hat_content:
assumes "tup \<in> gamma_set"
assumes "tup x = HAT a"
shows "a \<in> \<Gamma>"
proof -
have "range tup \<subseteq> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>"
using assms gamma_set_def by auto
then show ?thesis
using assms(2)
by (metis UNIV_I Un_iff image_iff image_subset_iff tuple_symbol.distinct(1) tuple_symbol.inject(2))
qed
lemma tup_no_hat_content:
assumes "tup \<in> gamma_set"
assumes "tup x = NO_HAT a"
shows "a \<in> \<Gamma>"
proof -
have "range tup \<subseteq> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>"
using assms gamma_set_def by auto
then show ?thesis
using assms(2)
by (metis UNIV_I Un_iff image_iff image_subset_iff tuple_symbol.inject(1) tuple_symbol.simps(4))
qed
lemma place_hats_to_dir_range[simp, intro]:
assumes "tup \<in> gamma_set"
shows "place_hats_to_dir d tup ds I \<in> gamma_set"
proof -
have "\<forall> k. (case tup k of NO_HAT a \<Rightarrow> if k \<in> I \<and> ds k = d then HAT a else NO_HAT a | HAT x \<Rightarrow> HAT x)
\<in> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>"
proof
fix k
show "(case tup k of NO_HAT a \<Rightarrow> if k \<in> I \<and> ds k = d then HAT a else NO_HAT a | HAT x \<Rightarrow> HAT x)
\<in> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>"
by(cases "tup k", insert tup_hat_content[OF assms(1)] tup_no_hat_content[OF assms(1)], auto simp: gamma_set_def)
qed
then show ?thesis
using assms
unfolding place_hats_to_dir_def gamma_set_def
by auto
qed
lemma place_hats_range[simp,intro]:
assumes "tup \<in> gamma_set"
shows "place_hats_R tup ds I \<in> gamma_set" and
"place_hats_L tup ds I \<in> gamma_set" and
"place_hats_M tup ds I \<in> gamma_set"
by(insert assms, auto simp: place_hats_R_def place_hats_L_def place_hats_M_def)
lemma fin_R1_Set[intro,simp]: "finite R1_Set"
unfolding R1_Set_def using fin_\<Sigma> by auto
lemma fin_gamma_set[intro,simp]: "finite gamma_set"
unfolding gamma_set_def using fin_\<Gamma>
by (intro fin_funcsetI, auto)
lemma fin_\<Gamma>'[intro,simp]: "finite \<Gamma>'"
unfolding \<Gamma>'_def using fin_\<Sigma> by auto
lemma fin_func_set[simp,intro]: "finite func_set"
unfolding func_set_def using fin_\<Gamma> by auto
lemma memberships[simp,intro]: "\<turnstile> \<in> \<Gamma>'"
"\<bullet> \<in> R1_Set"
"x \<in> \<Sigma> \<Longrightarrow> SYM x \<in> R1_Set"
"x \<in> \<Sigma> \<Longrightarrow> encSym x \<in> \<Gamma>'"
"blank' \<in> \<Gamma>'"
"hatLE' \<in> \<Gamma>'"
"x \<in> \<Sigma> \<Longrightarrow> INP x \<in> \<Gamma>'"
"y \<in> gamma_set \<Longrightarrow> TUPLE y \<in> \<Gamma>'"
"(\<lambda>_. \<bullet>) \<in> func_set"
"f \<in> UNIV \<rightarrow> SYM ` \<Gamma> \<Longrightarrow> f \<in> func_set"
"g \<in> UNIV \<rightarrow> \<Gamma> \<Longrightarrow> SYM \<circ> g \<in> func_set"
"f \<in> UNIV \<rightarrow> SYM ` \<Gamma> \<Longrightarrow> project_inp f k \<in> \<Gamma>"
unfolding R1_Set_def \<Gamma>'_def blank'_def hatLE'_def gamma_set_def encSym_def func_set_def project_inp_def
using LE blank tm funcset_mem[of f UNIV "SYM ` \<Gamma>" k] by (auto split: sym_or_bullet.splits)
lemma add_inp_func_set[simp,intro]: "b \<in> gamma_set \<Longrightarrow> a \<in> func_set \<Longrightarrow> add_inp b a \<in> func_set"
unfolding func_set_def gamma_set_def
proof
fix x
assume a: "a \<in> UNIV \<rightarrow> SYM ` \<Gamma> \<union> {\<bullet>}" and b: "b \<in> UNIV \<rightarrow> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>"
from a have a: "a x \<in> SYM ` \<Gamma> \<union> {\<bullet>}" by auto
from b have b: "b x \<in> NO_HAT ` \<Gamma> \<union> HAT ` \<Gamma>" by auto
show "add_inp b a x \<in> SYM ` \<Gamma> \<union> {\<bullet>}" using a b
unfolding add_inp_def by (cases "b x", auto simp: gamma_set_def)
qed
lemma automation[simp]: "\<And> a b A B. (S a b \<in> (\<lambda>x. case x of (x1, x2) \<Rightarrow> S x1 x2) ` (A \<times> B)) \<longleftrightarrow> (a \<in> A \<and> b \<in> B)"
"\<And> a b A B. (S\<^sub>1 a b \<in> (\<lambda>x. case x of (x1, x2) \<Rightarrow> S\<^sub>1 x1 x2) ` (A \<times> B)) \<longleftrightarrow> (a \<in> A \<and> b \<in> B)"
"\<And> a b c A B C. (E\<^sub>0 a b c \<in> (\<lambda>x. case x of (x1, x2, x3) \<Rightarrow> E\<^sub>0 x1 x2 x3) ` (A \<times> B \<times> C)) \<longleftrightarrow> (a \<in> A \<and> b \<in> B \<and> c \<in> C)"
"\<And> a b c A B C. (E a b c \<in> (\<lambda>x. case x of (x1, x2, x3) \<Rightarrow> E x1 x2 x3) ` (A \<times> B \<times> C)) \<longleftrightarrow> (a \<in> A \<and> b \<in> B \<and> c \<in> C)"
"\<And> a b c d A B C. (Er a b c d \<in> (\<lambda>x. case x of (x1, x2, x3, x4) \<Rightarrow> Er x1 x2 x3 x4) ` (A \<times> B \<times> C)) \<longleftrightarrow> (a \<in> A \<and> b \<in> B \<and> (c,d) \<in> C)"
"\<And> a b c d A B C. (Em a b c d \<in> (\<lambda>x. case x of (x1, x2, x3, x4) \<Rightarrow> Em x1 x2 x3 x4) ` (A \<times> B \<times> C)) \<longleftrightarrow> (a \<in> A \<and> b \<in> B \<and> (c,d) \<in> C)"
"\<And> a b c d A B C. (El a b c d \<in> (\<lambda>x. case x of (x1, x2, x3, x4) \<Rightarrow> El x1 x2 x3 x4) ` (A \<times> B \<times> C)) \<longleftrightarrow> (a \<in> A \<and> b \<in> B \<and> (c,d) \<in> C)"
"blank' \<noteq> \<turnstile>"
"\<turnstile> \<noteq> blank'"
"blank' \<noteq> INP x"
"INP x \<noteq> blank'"
by (force simp: blank'_def)+
interpretation st: singletape_tm Q' "(INP ` \<Sigma>)" \<Gamma>' blank' \<turnstile> \<delta>' "R\<^sub>1 \<bullet>" "S\<^sub>0 t" "S\<^sub>0 r"
proof
show "finite Q'"
unfolding Q'_def using fin_Q fin_\<Gamma>
by (intro finite_UnI finite_imageI finite_cartesian_product, auto)
show "finite \<Gamma>'" by (rule fin_\<Gamma>')
show "S\<^sub>0 t \<in> Q'" unfolding Q'_def using tQ by auto
show "S\<^sub>0 r \<in> Q'" unfolding Q'_def using rQ by auto
show "S\<^sub>0 t \<noteq> S\<^sub>0 r" using tr by auto
show "blank' \<notin> INP ` \<Sigma>" unfolding blank'_def by auto
show "R\<^sub>1 \<bullet> \<in> Q'" unfolding Q'_def by auto
show "\<delta>' \<subseteq> (Q' - {S\<^sub>0 t, S\<^sub>0 r}) \<times> \<Gamma>' \<times> Q' \<times> \<Gamma>' \<times> UNIV"
unfolding \<delta>'_def Q'_def using tm
by (auto dest: \<delta>)
show "(q, \<turnstile>, q', a', d) \<in> \<delta>' \<Longrightarrow> a' = \<turnstile> \<and> d \<in> {dir.N, dir.R}" for q q' a' d
unfolding \<delta>'_def by (auto simp: hatLE'_def blank'_def)
qed auto
lemma valid_st: "singletape_tm Q' (INP ` \<Sigma>) \<Gamma>' blank' \<turnstile> \<delta>' (R\<^sub>1 \<bullet>) (S\<^sub>0 t) (S\<^sub>0 r)" ..
text \<open>Determinism is preserved.\<close>
lemma det_preservation: "deterministic \<Longrightarrow> st.deterministic"
unfolding deterministic_def st.deterministic_def unfolding \<delta>'_def
by auto
subsection \<open>Soundness of the Translation\<close>
lemma range_mt_pos:
"\<exists> i. Max (range (mt_pos cm)) = mt_pos cm i"
"finite (range (mt_pos (cm :: ('a, 'q, 'k) mt_config)))"
"range (mt_pos cm) \<noteq> {}"
proof -
show "finite (range (mt_pos cm))" by auto
moreover show "range (mt_pos cm) \<noteq> {}" by auto
ultimately show "\<exists> i. Max (range (mt_pos cm)) = mt_pos cm i"
by (meson Max_in imageE)
qed
lemma max_mt_pos_step: assumes "(cm,cm') \<in> step"
shows "Max (range (mt_pos cm')) \<le> Suc (Max (range (mt_pos cm)))"
proof -
from range_mt_pos(1)[of cm'] obtain i'
where max1: "Max (range (mt_pos cm')) = mt_pos cm' i'" by auto
hence "Max (range (mt_pos cm')) \<le> mt_pos cm' i'" by auto
also have "\<dots> \<le> Suc (mt_pos cm i')" using assms
proof (cases)
case (step q ts n q' a dir)
then show ?thesis by (cases "dir i'", auto)
qed
also have "\<dots> \<le> Suc (Max (range (mt_pos cm)))" using range_mt_pos[of cm] by simp
finally show ?thesis .
qed
lemma max_mt_pos_init: "Max (range (mt_pos (init_config w))) = 0"
unfolding init_config_def by auto
lemma INP_D: assumes "set x \<subseteq> INP ` \<Sigma>"
shows "\<exists> w. x = map INP w \<and> set w \<subseteq> \<Sigma>"
using assms
proof (induct x)
case (Cons x xs)
then obtain w where "xs = map INP w \<and> set w \<subseteq> \<Sigma>" by auto
moreover from Cons(2) obtain a where "x = INP a" and "a \<in> \<Sigma>" by auto
ultimately show ?case by (intro exI[of _ "a # w"], auto)
qed auto
subsubsection \<open>R-Phase\<close>
fun enc :: "('a, 'q, 'k) mt_config \<Rightarrow> nat \<Rightarrow> ('a, 'k) st_tape_symbol"
where "enc (Config\<^sub>M q tc p) n = TUPLE (\<lambda> k. if p k = n then HAT (tc k n) else NO_HAT (tc k n))"
inductive rel_R\<^sub>1 :: "(('a, 'k) st_tape_symbol,('a, 'q, 'k) st_states)st_config \<Rightarrow> 'a list \<Rightarrow> nat \<Rightarrow> bool" where
"n = length w \<Longrightarrow>
tc' 0 = \<turnstile> \<Longrightarrow>
p' \<le> n \<Longrightarrow>
(\<And> i. i < p' \<Longrightarrow> enc (init_config w) i = tc' (Suc i)) \<Longrightarrow>
(\<And> i. i \<ge> p' \<Longrightarrow> tc' (Suc i) = (if i < n then INP (w ! i) else blank')) \<Longrightarrow>
(p' = 0 \<Longrightarrow> q' = \<bullet>) \<Longrightarrow>
(\<And> p. p' = Suc p \<Longrightarrow> q' = SYM (w ! p)) \<Longrightarrow>
rel_R\<^sub>1 (Config\<^sub>S (R\<^sub>1 q') tc' (Suc p')) w p'"
lemma rel_R\<^sub>1_init: shows "\<exists> cs1. (st.init_config (map INP w), cs1) \<in> st.dstep \<and> rel_R\<^sub>1 cs1 w 0"
proof -
let ?INP = "INP :: 'a \<Rightarrow> ('a, 'k) st_tape_symbol"
have mem: "(R\<^sub>1 \<bullet>, \<turnstile>, R\<^sub>1 \<bullet>, \<turnstile>, dir.R) \<in> \<delta>'" unfolding \<delta>'_def by auto
let ?cs1 = "Config\<^sub>S (R\<^sub>1 \<bullet>) (\<lambda>n. if n = 0 then \<turnstile> else if n \<le> length (map ?INP w) then map ?INP w ! (n - 1) else blank') (Suc 0)"
have "(st.init_config (map INP w), ?cs1) \<in> st.dstep"
unfolding st.init_config_def by (rule st.dstepI[OF mem], auto simp: \<delta>'_def blank'_def)
moreover have "rel_R\<^sub>1 ?cs1 w 0"
by (intro rel_R\<^sub>1.intros[OF refl], auto)
ultimately show ?thesis by blast
qed
lemma rel_R\<^sub>1_R\<^sub>1: assumes "rel_R\<^sub>1 cs0 w j"
and "j < length w"
and "set w \<subseteq> \<Sigma>"
shows "\<exists> cs1. (cs0, cs1) \<in> st.dstep \<and> rel_R\<^sub>1 cs1 w (Suc j)"
using assms(1)
proof (cases rule: rel_R\<^sub>1.cases)
case (1 n tc' q')
note cs0 = 1(1)
from assms have wj: "w ! j \<in> \<Sigma>" by auto
show ?thesis
proof (cases j)
case 0
with 1 have q': "q' = \<bullet>" by auto
from 1(6)[of 0] 0 assms 1 have tc'1: "tc' (Suc 0) = INP (w ! 0)" by auto
have mem: "(R\<^sub>1 \<bullet>, INP (w ! 0), R\<^sub>1 (SYM (w ! 0)), hatLE', dir.R) \<in> \<delta>'" unfolding \<delta>'_def
using wj 0 by auto
let ?cs1 = "Config\<^sub>S (R\<^sub>1 (SYM (w ! 0))) (tc'(Suc 0 := hatLE')) (Suc (Suc 0))"
have enc: "enc (init_config w) 0 = hatLE'" unfolding init_config_def hatLE'_def by auto
have "(cs0, ?cs1) \<in> st.dstep" unfolding cs0 0
by (intro st.dstepI[OF mem], auto simp: q' tc'1 \<delta>'_def blank'_def)
moreover have "rel_R\<^sub>1 ?cs1 w (Suc 0)"
by (intro rel_R\<^sub>1.intros, rule 1(2), insert 1 0 assms(2), auto simp: enc) (cases w, auto)
ultimately show ?thesis unfolding 0 by blast
next
case (Suc p)
from 1(8)[OF Suc] have q': "q' = SYM (w ! p)" by auto
from Suc assms(2) have "p < length w" by auto
with assms(3) have "w ! p \<in> \<Sigma>" by auto
with wj have "(w ! p, w ! j) \<in> \<Sigma> \<times> \<Sigma>" by auto
hence mem: "(R\<^sub>1 (SYM (w ! p)), INP (w ! j), R\<^sub>1 (SYM (w ! j)), encSym (w ! p), dir.R) \<in> \<delta>'" unfolding \<delta>'_def by auto
have enc: "enc (init_config w) j = encSym (w ! p)" unfolding Suc using \<open>p < length w\<close>
by (auto simp: init_config_def encSym_def)
from 1(6)[of j] assms 1 have tc': "tc' (Suc j) = INP (w ! j)" by auto
let ?cs1 = "Config\<^sub>S (R\<^sub>1 (SYM (w ! j))) (tc'(Suc j := encSym (w ! p))) (Suc (Suc j))"
have "(cs0, ?cs1) \<in> st.dstep" unfolding cs0
by (rule st.dstepI[OF mem], insert q' tc', auto simp: \<delta>'_def blank'_def)
moreover have "rel_R\<^sub>1 ?cs1 w (Suc j)"
by (intro rel_R\<^sub>1.intros, insert 1 assms enc, auto)
ultimately show ?thesis by blast
qed
qed
inductive rel_R\<^sub>2 :: "(('a, 'k) st_tape_symbol,('a, 'q, 'k) st_states)st_config \<Rightarrow> 'a list \<Rightarrow> nat \<Rightarrow> bool" where
"tc' 0 = \<turnstile> \<Longrightarrow>
(\<And> i. enc (init_config w) i = tc' (Suc i)) \<Longrightarrow>
p \<le> length w \<Longrightarrow>
rel_R\<^sub>2 (Config\<^sub>S R\<^sub>2 tc' p) w p"
lemma rel_R\<^sub>1_R\<^sub>2: assumes "rel_R\<^sub>1 cs0 w (length w)"
and "set w \<subseteq> \<Sigma>"
shows "\<exists> cs1. (cs0, cs1) \<in> st.dstep \<and> rel_R\<^sub>2 cs1 w (length w)"
using assms
proof (cases rule: rel_R\<^sub>1.cases)
case (1 n tc' q')
note cs0 = 1(1)
have enc: "enc (init_config w) i = tc' (Suc i)" if "i \<noteq> length w" for i
proof (cases "i < length w")
case True
thus ?thesis using 1(5)[of i] by auto
next
case False
with that have i: "i > length w" by auto
with 1(6)[of i] 1 have "tc' (Suc i) = blank'" by auto
also have "\<dots> = enc (init_config w) i" using i unfolding init_config_def by (auto simp: blank'_def)
finally show ?thesis by simp
qed
show ?thesis
proof (cases "length w")
case 0
with 1 have q': "q' = \<bullet>" by auto
from 1(6)[of 0] 0 1 have tc'1: "tc' (Suc 0) = blank'" by auto
have mem: "(R\<^sub>1 \<bullet>, blank', R\<^sub>2, hatLE', dir.L) \<in> \<delta>'" unfolding \<delta>'_def
by auto
let ?tc = "tc'(Suc 0 := hatLE')"
let ?cs1 = "Config\<^sub>S R\<^sub>2 ?tc 0"
have enc0: "enc (init_config w) 0 = hatLE'" unfolding init_config_def hatLE'_def by auto
have enc: "enc (init_config w) i = ?tc (Suc i)" for i using enc[of i] enc0 using 0
by (cases i, auto)
have "(cs0, ?cs1) \<in> st.dstep" unfolding cs0 0
by (intro st.dstepI[OF mem], auto simp: q' tc'1 \<delta>'_def blank'_def)
moreover have "rel_R\<^sub>2 ?cs1 w (length w)" unfolding 0
by (intro rel_R\<^sub>2.intros enc, insert 1 0, auto)
ultimately show ?thesis unfolding 0 by blast
next
case (Suc p)
from 1(8)[OF Suc] have q': "q' = SYM (w ! p)" by auto
from Suc have "p < length w" by auto
with assms(2) have "w ! p \<in> \<Sigma>" by auto
hence mem: "(R\<^sub>1 (SYM (w ! p)), blank', R\<^sub>2, encSym (w ! p), dir.L) \<in> \<delta>'" unfolding \<delta>'_def by auto
let ?tc = "tc'(Suc (length w) := encSym (w ! p))"
have encW: "enc (init_config w) (length w) = encSym (w ! p)" unfolding Suc using \<open>p < length w\<close>
by (auto simp: init_config_def encSym_def)
from 1(6)[of "length w"] assms 1 have tc': "tc' (Suc (length w)) = blank'" by auto
let ?cs1 = "Config\<^sub>S R\<^sub>2 ?tc (length w)"
have enc: "enc (init_config w) i = ?tc (Suc i)" for i using enc[of i] encW by auto
have "(cs0, ?cs1) \<in> st.dstep" unfolding cs0 q'
by (intro st.dstepI[OF mem] tc', auto simp: \<delta>'_def blank'_def)
moreover have "rel_R\<^sub>2 ?cs1 w (length w)"
by (intro rel_R\<^sub>2.intros, insert 1 assms enc, auto)
ultimately show ?thesis by blast
qed
qed
lemma rel_R\<^sub>2_R\<^sub>2: assumes "rel_R\<^sub>2 cs0 w (Suc j)"
and "set w \<subseteq> \<Sigma>"
shows "\<exists> cs1. (cs0, cs1) \<in> st.dstep \<and> rel_R\<^sub>2 cs1 w j"
using assms
proof (cases rule: rel_R\<^sub>2.cases)
case (1 tc')
note cs0 = 1(1)
from 1 have j: "j < length w" by auto
have tc: "tc' (Suc j) \<in> \<Gamma>' - { \<turnstile> }" unfolding 1(3)[symmetric] using j assms(2)[unfolded set_conv_nth] unfolding init_config_def
by (force simp: \<Gamma>'_def gamma_set_def intro!: imageI LE blank set_mp[OF \<Sigma>_sub_\<Gamma>, of "w ! (j - Suc 0)"])
hence mem: "(R\<^sub>2, tc' (Suc j), R\<^sub>2, tc' (Suc j), dir.L) \<in> \<delta>'" unfolding \<delta>'_def by auto
let ?cs1 = "Config\<^sub>S R\<^sub>2 tc' j"
have "(cs0, ?cs1) \<in> st.dstep" unfolding cs0 using tc
by (intro st.dstepI[OF mem], auto simp: \<delta>'_def blank'_def)
moreover have "rel_R\<^sub>2 ?cs1 w j"
by (intro rel_R\<^sub>2.intros, insert 1, auto)
ultimately show ?thesis by blast
qed
inductive rel_S\<^sub>0 :: "(('a, 'k) st_tape_symbol,('a, 'q, 'k) st_states)st_config \<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> bool" where
"tc' 0 = \<turnstile> \<Longrightarrow>
(\<And> i. tc' (Suc i) = enc (Config\<^sub>M q tc p) i) \<Longrightarrow>
valid_config (Config\<^sub>M q tc p) \<Longrightarrow>
rel_S\<^sub>0 (Config\<^sub>S (S\<^sub>0 q) tc' 0) (Config\<^sub>M q tc p)"
lemma rel_R\<^sub>2_S\<^sub>0: assumes "rel_R\<^sub>2 cs0 w 0"
and "set w \<subseteq> \<Sigma>"
shows "\<exists> cs1. (cs0, cs1) \<in> st.dstep \<and> rel_S\<^sub>0 cs1 (init_config w)"
using assms
proof (cases rule: rel_R\<^sub>2.cases)
case (1 tc')
note cs0 = 1(1)
hence mem: "(R\<^sub>2, \<turnstile>, S\<^sub>0 s, \<turnstile>, dir.N) \<in> \<delta>'" unfolding \<delta>'_def by auto
let ?cs1 = "Config\<^sub>S (S\<^sub>0 s) tc' 0"
have "(cs0, ?cs1) \<in> st.dstep" unfolding cs0
by (intro st.dstepI[OF mem], insert 1, auto simp: \<delta>'_def blank'_def)
moreover have "rel_S\<^sub>0 ?cs1 (init_config w)" using valid_init_config[OF assms(2)] unfolding init_config_def
by (intro rel_S\<^sub>0.intros, insert 1(1,2,4-), auto simp: 1(3)[symmetric] init_config_def)
ultimately show ?thesis by blast
qed
text \<open>If we start with a proper word \<open>w\<close> as input on the singletape TM,
then via the R-phase one can switch to the beginning of
the S-phase (@{const rel_S\<^sub>0}) for the initial configuration.\<close>
lemma R_phase: assumes "set w \<subseteq> \<Sigma>"
shows "\<exists> cs. (st.init_config (map INP w), cs) \<in> st.dstep^^(3 + 2 * length w) \<and> rel_S\<^sub>0 cs (init_config w)"
proof -
from rel_R\<^sub>1_init[of w] obtain cs1 n where
step1: "(st.init_config (map INP w), cs1) \<in> st.dstep" and
relR1: "rel_R\<^sub>1 cs1 w n" and
n0: "n = 0"
by auto
from relR1
have "n + k \<le> length w \<Longrightarrow> \<exists> cs2. (cs1, cs2) \<in> st.dstep^^k \<and> rel_R\<^sub>1 cs2 w (n + k)" for k
proof (induction k arbitrary: cs1 n)
case (Suc k cs1 n)
hence "n < length w" by auto
from rel_R\<^sub>1_R\<^sub>1[OF Suc(3) this assms] obtain cs3 where
step: "(cs1, cs3) \<in> st.dstep" and rel: "rel_R\<^sub>1 cs3 w (Suc n)" by auto
from Suc.IH[OF _ rel] Suc(2) obtain cs2 where
steps: "(cs3, cs2) \<in> st.dstep ^^ k" and rel: "rel_R\<^sub>1 cs2 w (Suc n + k)"
by auto
from relpow_Suc_I2[OF step steps] rel
show ?case by auto
qed auto
from this[of "length w", unfolded n0]
obtain cs2 where steps2: "(cs1, cs2) \<in> st.dstep ^^ length w" and rel: "rel_R\<^sub>1 cs2 w (length w)" by auto
from rel_R\<^sub>1_R\<^sub>2[OF rel assms] obtain cs3 n where step3: "(cs2, cs3) \<in> st.dstep"
and rel: "rel_R\<^sub>2 cs3 w n" and n: "n = length w"
by auto
from rel have "\<exists> cs. (cs3, cs) \<in> st.dstep^^n \<and> rel_R\<^sub>2 cs w 0"
proof (induction n arbitrary: cs3 rule: nat_induct)
case (Suc n cs3)
from rel_R\<^sub>2_R\<^sub>2[OF Suc(2) assms] obtain cs1 where
step: "(cs3, cs1) \<in> st.dstep" and rel: "rel_R\<^sub>2 cs1 w n" by auto
from Suc.IH[OF rel] obtain cs where steps: "(cs1, cs) \<in> st.dstep ^^ n" and rel: "rel_R\<^sub>2 cs w 0" by auto
from relpow_Suc_I2[OF step steps] rel show ?case by auto
qed auto
then obtain cs4 where steps4: "(cs3, cs4) \<in> st.dstep^^(length w)" and rel: "rel_R\<^sub>2 cs4 w 0" by (auto simp: n)
from rel_R\<^sub>2_S\<^sub>0[OF rel assms] obtain cs where step5: "(cs4, cs) \<in> st.dstep" and
rel: "rel_S\<^sub>0 cs (init_config w)" by auto
from relpow_Suc_I2[OF step1 relpow_transI[OF steps2 relpow_Suc_I2[OF step3 relpow_Suc_I[OF steps4 step5]]]]
have "(st.init_config (map INP w), cs) \<in> st.dstep ^^ Suc (length w + Suc (Suc (length w)))" .
also have "Suc (length w + Suc (Suc (length w))) = 3 + 2 * length w" by simp
finally show ?thesis using rel by auto
qed
subsubsection \<open>S-Phase\<close>
inductive rel_S :: "(('a, 'k) st_tape_symbol,('a, 'q, 'k) st_states)st_config \<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> nat \<Rightarrow> bool" where
"tc' 0 = \<turnstile> \<Longrightarrow>
(\<And> i. tc' (Suc i) = enc (Config\<^sub>M q tc p) i) \<Longrightarrow>
valid_config (Config\<^sub>M q tc p) \<Longrightarrow>
(\<And> i. inp i = (if p i < p' then SYM (tc i (p i)) else \<bullet>)) \<Longrightarrow>
rel_S (Config\<^sub>S (S q inp) tc' (Suc p')) (Config\<^sub>M q tc p) p'"
lemma rel_S\<^sub>0_S: assumes "rel_S\<^sub>0 cs0 cm"
and "mt_state cm \<notin> {t,r}"
shows "\<exists> cs1. (cs0, cs1) \<in> st.dstep \<and> rel_S cs1 cm 0"
using assms(1)
proof (cases rule: rel_S\<^sub>0.cases)
case (1 tc' q tc p)
note cs0 = 1(1)
note cm = 1(2)
from assms(2) cm 1(5) have qtr: "q \<in> Q - {t,r}" by auto
hence mem: "(S\<^sub>0 q, \<turnstile>, S q (\<lambda>_. \<bullet>), \<turnstile>, dir.R) \<in> \<delta>'" unfolding \<delta>'_def by auto
let ?cs1 = "Config\<^sub>S (S q (\<lambda>_. \<bullet>)) tc' (Suc 0)"
have "(cs0, ?cs1) \<in> st.dstep" unfolding cs0
by (rule st.dstepI[OF mem], insert 1, auto simp: \<delta>'_def blank'_def)
moreover have "rel_S ?cs1 cm 0" unfolding cm
by (intro rel_S.intros 1, auto)
ultimately show ?thesis by blast
qed
lemma rel_S_mem: assumes "rel_S (Config\<^sub>S (S q inp) tc' p') cm j"
shows "inp \<in> func_set \<and> q \<in> Q \<and> (\<exists> t. tc' (Suc i) = TUPLE t \<and> t \<in> gamma_set)"
using assms(1)
proof (cases rule: rel_S.cases)
case (1 tc p)
from 1 have q: "q \<in> Q" by auto
have inp: "inp \<in> func_set" unfolding func_set_def 1(6) using 1(5)
by force
have "\<exists> t. tc' (Suc i) = TUPLE t \<and> t \<in> gamma_set" using 1(5)
unfolding 1(4) by (force simp: gamma_set_def)
with q inp show ?thesis by auto
qed
lemma rel_S_S: assumes "rel_S cs0 cm p'"
"p' \<le> Max (range (mt_pos cm))"
shows "\<exists> cs1. (cs0, cs1) \<in> st.dstep \<and> rel_S cs1 cm (Suc p')"
using assms(1)
proof (cases rule: rel_S.cases)
case (1 tc' q tc p inp)
note cs0 = 1(1)
note cm = 1(2)
let ?Set = "Q \<times> (func_set - (UNIV \<rightarrow> SYM ` \<Gamma>)) \<times> gamma_set"
let ?f = "\<lambda>(q, inp, t). (S q inp, TUPLE t, S q (add_inp t inp), TUPLE t, dir.R)"
obtain i where "mt_pos cm i = Max (range (mt_pos cm))" using range_mt_pos(1)[of cm] by auto
with assms 1 have "p' \<le> p i" by auto
with 1(6)[of i] have "inp i = \<bullet>" by auto
hence inp: "inp \<notin> (UNIV \<rightarrow> SYM ` \<Gamma>)"
by (metis PiE UNIV_I image_iff sym_or_bullet.distinct(1))
with rel_S_mem[OF assms(1)[unfolded cs0], of p'] obtain t where
"(q,inp,t) \<in> ?Set" and tc': "tc' (Suc p') = TUPLE t" by auto
hence "?f (q,inp,t) \<in> \<delta>'" unfolding \<delta>'_def by blast
hence mem: "(S q inp, TUPLE t, S q (add_inp t inp), TUPLE t, dir.R) \<in> \<delta>'" by simp
let ?cs1 = "Config\<^sub>S (S q (add_inp t inp)) tc' (Suc (Suc p'))"
have "(cs0,?cs1) \<in> st.dstep" unfolding cs0 using inp
by (intro st.dstepI[OF mem], auto simp: tc' \<delta>'_def blank'_def)
moreover have "rel_S ?cs1 cm (Suc p')" unfolding cm
proof (intro rel_S.intros 1)
from 1(4)[of p', unfolded tc']
have t: "t = (\<lambda>k. if p k = p' then HAT (tc k p') else NO_HAT (tc k p'))" by auto
show "\<And> k. add_inp t inp k = (if p k < Suc p' then SYM (tc k (p k)) else \<bullet>)"
unfolding add_inp_def 1 t by auto
qed
ultimately show ?thesis by blast
qed
inductive rel_S\<^sub>1 :: "(('a, 'k) st_tape_symbol,('a, 'q, 'k) st_states)st_config \<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> bool" where
"tc' 0 = \<turnstile> \<Longrightarrow>
(\<And> i. tc' (Suc i) = enc (Config\<^sub>M q tc p) i) \<Longrightarrow>
valid_config (Config\<^sub>M q tc p) \<Longrightarrow>
(\<And> i. inp i = tc i (p i)) \<Longrightarrow>
(\<And> i. p i < p') \<Longrightarrow>
p' = Suc (Max (range p)) \<Longrightarrow>
rel_S\<^sub>1 (Config\<^sub>S (S\<^sub>1 q inp) tc' p') (Config\<^sub>M q tc p)"
lemma rel_S_S\<^sub>1: assumes "rel_S cs0 cm p'"
"p' = Suc (Max (range (mt_pos cm)))"
shows "\<exists> cs1. (cs0, cs1) \<in> st.dstep \<and> rel_S\<^sub>1 cs1 cm"
using assms(1)
proof (cases rule: rel_S.cases)
case (1 tc' q tc p inp)
from assms have p'Max: "p' > Max (range (mt_pos cm))" by auto
note cs0 = 1(1)
note cm = 1(2)
from p'Max range_mt_pos(2-)[of cm] have pip: "p i < p'" for i unfolding cm by auto
let ?SET = "Q \<times> func_set \<times> gamma_set"
let ?Set = "Q \<times> (UNIV \<rightarrow> SYM ` \<Gamma>) \<times> (\<Gamma>' - { \<turnstile> })"
from rel_S_mem[OF assms(1)[unfolded cs0], of p'] obtain t where
mem: "(q,inp,t) \<in> ?SET" and tc': "tc' (Suc p') = TUPLE t" by auto
hence "inp \<in> func_set" by auto
with pip have inp: "inp \<in> UNIV \<rightarrow> SYM ` \<Gamma>" unfolding func_set_def using 1(6) by auto
with mem have "(q,inp,TUPLE t) \<in> ?Set" by auto
hence "(\<lambda> (q,inp,a). (S q inp, a, S\<^sub>1 q (project_inp inp), a, dir.L)) (q,inp,TUPLE t) \<in> \<delta>'" unfolding \<delta>'_def by blast
hence mem: "(S q inp, TUPLE t, S\<^sub>1 q (project_inp inp), TUPLE t, dir.L) \<in> \<delta>'" by simp
let ?cs1 = "Config\<^sub>S (S\<^sub>1 q (project_inp inp)) tc' p'"
have "(cs0,?cs1) \<in> st.dstep" unfolding cs0 using inp
by (intro st.dstepI[OF mem], auto simp: tc' \<delta>'_def blank'_def)
moreover have "rel_S\<^sub>1 ?cs1 cm" unfolding cm
proof (intro rel_S\<^sub>1.intros 1 pip)
fix i
from inp have "inp i \<in> SYM ` \<Gamma>" by auto
then obtain g where "inp i = SYM g" and "g \<in> \<Gamma>" by auto
thus "project_inp inp i = tc i (p i)" using 1(6)[of i] by (auto simp: project_inp_def split: if_splits)
show "p' = Suc (Max (range p))" unfolding assms(2) unfolding cm by simp
qed
ultimately show ?thesis by auto
qed
text \<open>If we start the S-phase (in @{const rel_S\<^sub>0}), and the multitape-TM is not in a final state,
then we can move to the end of the S-phase (in @{const rel_S\<^sub>1}).\<close>
lemma S_phase: assumes "rel_S\<^sub>0 cs cm"
and "mt_state cm \<notin> {t, r}"
shows "\<exists> cs'. (cs, cs') \<in> st.dstep^^(3 + Max (range (mt_pos cm))) \<and> rel_S\<^sub>1 cs' cm"
proof -
let ?N = "Max (range (mt_pos cm))"
from rel_S\<^sub>0_S[OF assms] obtain cs1 n where
step1: "(cs, cs1) \<in> st.dstep" and rel: "rel_S cs1 cm n" and n: "n = 0"
by auto
from rel have "n + k \<le> Suc ?N \<Longrightarrow> \<exists> cs2. (cs1, cs2) \<in> st.dstep ^^ k \<and> rel_S cs2 cm (n + k)" for k
proof (induction k arbitrary: cs1 n)
case (Suc k cs n)
hence "n \<le> ?N" by auto
from rel_S_S[OF Suc(3) this] obtain cs1 where step: "(cs, cs1) \<in> st.dstep" and rel: "rel_S cs1 cm (Suc n)" by auto
from Suc have "Suc n + k \<le> Suc ?N" by auto
from Suc.IH[OF this rel] obtain cs2 where steps: "(cs1, cs2) \<in> st.dstep ^^ k" and rel: "rel_S cs2 cm (n + Suc k)" by auto
from relpow_Suc_I2[OF step steps] rel
show ?case by auto
qed auto
from this[of "Suc ?N", unfolded n] obtain cs2 where
steps2: "(cs1, cs2) \<in> st.dstep ^^ (Suc ?N)" and rel: "rel_S cs2 cm (Suc ?N)" by auto
from rel_S_S\<^sub>1[OF rel] obtain cs3 where step3: "(cs2,cs3) \<in> st.dstep" and rel: "rel_S\<^sub>1 cs3 cm" by auto
from relpow_Suc_I2[OF step1 relpow_Suc_I[OF steps2 step3]]
have "(cs, cs3) \<in> st.dstep ^^ Suc (Suc (Suc ?N))" by simp
also have "Suc (Suc (Suc ?N)) = 3 + ?N" by simp
finally show ?thesis using rel by blast
qed
subsubsection \<open>E-Phase\<close>
context
fixes rule :: "('a,'q,'k)mt_rule"
begin
inductive_set \<delta>step :: "('a, 'q, 'k) mt_config rel" where
\<delta>step: "rule = (q, a, q1, b, dir) \<Longrightarrow>
rule \<in> \<delta> \<Longrightarrow>
(\<And> k. ts k (n k) = a k) \<Longrightarrow>
(\<And> k. ts' k = (ts k)(n k := b k)) \<Longrightarrow>
(\<And> k. n' k = go_dir (dir k) (n k)) \<Longrightarrow>
(Config\<^sub>M q ts n, Config\<^sub>M q1 ts' n') \<in> \<delta>step"
end
lemma step_to_\<delta>step: "(c1,c2) \<in> step \<Longrightarrow> \<exists> rule. (c1,c2) \<in> \<delta>step rule"
proof (induct rule: step.induct)
case (step q ts n q' a dir)
show ?case
by (rule exI, rule \<delta>step.intros[OF refl step], auto)
qed
lemma \<delta>step_to_step: "(c1,c2) \<in> \<delta>step rule \<Longrightarrow> (c1,c2) \<in> step"
proof (induct rule: \<delta>step.induct)
case *: (\<delta>step q a q' b dir ts n ts' n')
from * have a: "a = (\<lambda> k. ts k (n k))" by auto
from * have ts': "ts' = (\<lambda> k. (ts k)(n k := b k))" by auto
from * have n': "n' = (\<lambda> k. go_dir (dir k) (n k))" by auto
from * show ?case using step.intros[of q ts n q' b dir] unfolding a ts' n' by auto
qed
inductive rel_E\<^sub>0 :: "(('a, 'k) st_tape_symbol,('a, 'q, 'k) st_states)st_config
\<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> ('a,'q,'k)mt_rule \<Rightarrow> bool" where
"tc' 0 = \<turnstile> \<Longrightarrow>
(\<And> i. tc' (Suc i) = enc (Config\<^sub>M q tc p) i) \<Longrightarrow>
valid_config (Config\<^sub>M q tc p) \<Longrightarrow>
rule = (q,a,q1,b,d) \<Longrightarrow>
(Config\<^sub>M q tc p, Config\<^sub>M q1 tc1 p1) \<in> \<delta>step rule \<Longrightarrow>
(\<And> i. p i < p') \<Longrightarrow>
p' = Suc (Max (range p)) \<Longrightarrow>
rel_E\<^sub>0 (Config\<^sub>S (E\<^sub>0 q1 b d) tc' p') (Config\<^sub>M q tc p) (Config\<^sub>M q1 tc1 p1) rule"
text \<open>For the transition between S and E phase we do not have deterministic steps.
Therefore we add two lemmas: the former one is for showing that multitape can be simulated
by singletape, and the latter one is for the inverse direction.\<close>
lemma rel_S\<^sub>1_E\<^sub>0_step: assumes "rel_S\<^sub>1 cs cm"
and "(cm,cm1) \<in> step"
shows "\<exists> rule cs1. (cs, cs1) \<in> st.step \<and> rel_E\<^sub>0 cs1 cm cm1 rule"
proof -
from step_to_\<delta>step[OF assms(2)] obtain rule where rstep: "(cm, cm1) \<in> \<delta>step rule" by auto
show ?thesis using assms(1)
proof (cases rule: rel_S\<^sub>1.cases)
case (1 tc' q tc p inp p')
note cs = 1(1)
note cm = 1(2)
have tc': "tc' p' \<in> \<Gamma>'" unfolding 1(8,4) enc.simps \<Gamma>'_def gamma_set_def using 1(5)
by (force intro!: imageI)
show ?thesis using rstep[unfolded cm]
proof (cases rule: \<delta>step.cases)
case 2: (\<delta>step a q1 b dir ts' n')
note rule = 2(2)
note cm1 = 2(1)
have "(\<lambda>((q, a, q', b, d), t). (S\<^sub>1 q a, t, E\<^sub>0 q' b d, t, dir.N)) (rule,tc' p') \<in> \<delta>'"
unfolding \<delta>'_def using tc' 2(3) by blast
hence mem: "(S\<^sub>1 q a, tc' p', E\<^sub>0 q1 b dir, tc' p', dir.N) \<in> \<delta>'" by (auto simp: rule)
have inp_a: "inp = a" using 2(4)[folded 1(6)] by auto
let ?cs1 = "Config\<^sub>S (E\<^sub>0 q1 b dir) tc' p'"
have step: "(cs, ?cs1) \<in> st.step" unfolding cs
by (intro st.stepI[OF mem], insert inp_a, auto)
moreover have "rel_E\<^sub>0 ?cs1 cm cm1 rule" unfolding cm cm1
by (intro rel_E\<^sub>0.intros[OF _ _ _ rule], insert 1 2 assms rstep, auto)
ultimately show ?thesis by blast
qed
qed
qed
lemma rel_S\<^sub>1_E\<^sub>0_st_step: assumes "rel_S\<^sub>1 cs cm"
and "(cs,cs1) \<in> st.step"
shows "\<exists> cm1 rule. (cm, cm1) \<in> step \<and> rel_E\<^sub>0 cs1 cm cm1 rule"
using assms(1)
proof (cases rule: rel_S\<^sub>1.cases)
case (1 tc' q tc p inp p')
note cs = 1(1)
note cm = 1(2)
have tc': "tc' p' \<in> \<Gamma>'" unfolding 1(8,4) enc.simps \<Gamma>'_def gamma_set_def using 1(5)
by (force intro!: imageI)
show ?thesis using assms(2)[unfolded cs]
proof (cases rule: st.step.cases)
case 2: (step qq bb ddir)
from 2(2)[unfolded \<delta>'_def]
have "(S\<^sub>1 q inp, tc' p', qq, bb, ddir) \<in> (\<lambda>((q, a, q', b, d), t). (S\<^sub>1 q a, t, E\<^sub>0 q' b d, t, dir.N)) ` (\<delta> \<times> \<Gamma>')" by auto
then obtain q' b dir where mem: "(q,inp,q',b,dir) \<in> \<delta>" and qq: "qq = E\<^sub>0 q' b dir" and ddir: "ddir = dir.N"
and bb: "bb = tc' p'" by auto
hence cs1: "cs1 = Config\<^sub>S (E\<^sub>0 q' b dir) tc' p'" unfolding 2 qq ddir bb by auto
let ?rule = "(q,inp,q',b,dir)"
let ?cm1 = "Config\<^sub>M q' (\<lambda> k. (tc k)(p k := b k)) (\<lambda> k. go_dir (dir k) (p k))"
have \<delta>step: "(cm, ?cm1) \<in> \<delta>step ?rule" unfolding cm
by (intro \<delta>step.intros[OF refl mem], auto simp: 1(6))
from \<delta>step_to_step[OF this]
have "(cm, ?cm1) \<in> step" .
moreover have "rel_E\<^sub>0 cs1 cm ?cm1 ?rule" unfolding cm cs1
by (intro rel_E\<^sub>0.intros \<delta>step[unfolded cm], insert 1 2, auto)
ultimately show ?thesis by blast
qed
qed
fun enc2 :: "('a, 'q, 'k) mt_config \<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> ('a, 'k) st_tape_symbol"
where "enc2 (Config\<^sub>M q tc p) (Config\<^sub>M q1 tc1 p1) p' n = TUPLE (\<lambda> k. if p k < p'
then if p k = n then HAT (tc k n) else NO_HAT (tc k n)
else if p1 k = n then HAT (tc1 k n) else NO_HAT (tc1 k n))"
inductive rel_E :: "(('a, 'k) st_tape_symbol,('a, 'q, 'k) st_states)st_config
\<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> ('a, 'q, 'k) mt_config \<Rightarrow> ('a,'q,'k)mt_rule \<Rightarrow> nat \<Rightarrow> bool" where
"tc' 0 = \<turnstile> \<Longrightarrow>
(\<And> i. tc' (Suc i) = enc2 (Config\<^sub>M q tc p) (Config\<^sub>M q1 tc1 p1) p' i) \<Longrightarrow>
valid_config (Config\<^sub>M q tc p) \<Longrightarrow>
rule = (q,a,q1,b,d) \<Longrightarrow>
(Config\<^sub>M q tc p, Config\<^sub>M q1 tc1 p1) \<in> \<delta>step rule \<Longrightarrow>
bo = (\<lambda> k. if p k < p' then SYM (b k) else \<bullet>) \<Longrightarrow>
rel_E (Config\<^sub>S (E q1 bo d) tc' p') (Config\<^sub>M q tc p) (Config\<^sub>M q1 tc1 p1) rule p'"
lemma rel_E\<^sub>0_E: assumes "rel_E\<^sub>0 cs cm cm1 rule"
shows "\<exists> cs1. (cs, cs1) \<in> st.dstep \<and> rel_E cs1 cm cm1 rule (Suc (Max (range (mt_pos cm))))"
using assms(1)
proof (cases rule: rel_E\<^sub>0.cases)
case (1 tc' q tc p a q1 b d tc1 p1 p')
note cs = 1(1)
note cm = 1(2)
note cm1 = 1(3)
note rule = 1(7)
let ?rule = "(q, a, q1, b, d)"
have tc': "tc' p' \<in> \<Gamma>'" unfolding 1(10,5) enc.simps \<Gamma>'_def gamma_set_def using 1(6)
by (force intro!: imageI)
have rmem: "?rule \<in> \<delta>" using 1(8,7) by (cases rule: \<delta>step.cases, auto)
note elem = \<delta>[OF this]
have "((q1,b,d), tc' p') \<in> (Q \<times> (UNIV \<rightarrow> \<Gamma>) \<times> UNIV) \<times> \<Gamma>'"
using elem tc' by auto
hence "(\<lambda>((q, a, d), t). (E\<^sub>0 q a d, t, E q (SYM \<circ> a) d, t, dir.N)) ((q1,b,d), tc' p') \<in> \<delta>'"
unfolding \<delta>'_def by blast
hence mem: "(E\<^sub>0 q1 b d, tc' p', E q1 (SYM \<circ> b) d, tc' p', dir.N) \<in> \<delta>'" by simp
have Max: "Suc (Max (range (mt_pos cm))) = p'" unfolding cm using 1 by auto
let ?cs1 = "Config\<^sub>S (E q1 (SYM \<circ> b) d) tc' p'"
have "(cs, ?cs1) \<in> st.dstep" unfolding cs
by (intro st.dstepI[OF mem] refl, auto simp: \<delta>'_def)
moreover have "rel_E ?cs1 cm cm1 rule (Suc (Max (range (mt_pos cm))))"
unfolding Max unfolding cm cm1 rule
by (intro rel_E.intros, insert 1, auto)
ultimately show ?thesis by blast
qed
lemma rel_E_S\<^sub>0: assumes "rel_E cs cm cm1 rule 0"
shows "\<exists> cs1. (cs,cs1) \<in> st.dstep \<and> rel_S\<^sub>0 cs1 cm1"
using assms(1)
proof (cases rule: rel_E.cases)
case (1 tc' q tc p q1 tc1 p1 a b d bo)
note cs = 1(1)
note cm = 1(2)
note cm1 = 1(3)
from valid_step[OF \<delta>step_to_step[OF 1(8)] 1(6)]
have valid: "valid_config (Config\<^sub>M q1 tc1 p1)" .
from valid have q1: "q1 \<in> Q" by auto
hence mem: "(E q1 (\<lambda> _. \<bullet>) d, \<turnstile>, S\<^sub>0 q1, \<turnstile>, dir.N) \<in> \<delta>'" unfolding \<delta>'_def by auto
let ?cs1 = "Config\<^sub>S (S\<^sub>0 q1) tc' 0"
have "(cs, ?cs1) \<in> st.dstep" unfolding cs
by (intro st.dstepI[OF mem], insert 1, auto simp: \<delta>'_def)
moreover have "rel_S\<^sub>0 ?cs1 cm1" unfolding cm1
by (intro rel_S\<^sub>0.intros valid, insert 1, auto)
ultimately show ?thesis by blast
qed
lemma dsteps_to_steps: "a \<in> st.dstep ^^ n \<Longrightarrow> a \<in> st.step ^^ n"
using relpow_mono[OF st.dstep_step] by auto
lemma \<delta>'_mem: assumes "tup \<in> A"
and "f ` A \<subseteq> \<delta>'"
shows "f tup \<in> \<delta>'"
using assms by auto
lemma rel_E_E: assumes "rel_E cs cm cm1 rule (Suc p')"
shows "\<exists> cs1. (cs,cs1) \<in> st.dstep^^4 \<and> rel_E cs1 cm cm1 rule p'"
using assms
proof(cases rule: rel_E.cases)
case (1 tc' q tc p q1 tc1 p1 a b d bo)
let ?rule = "(q, a, q1, b, d)"
have valid_next: "valid_config(Config\<^sub>M q1 tc1 p1)"
using 1(8,6) \<delta>step_to_step valid_step by blast
have trans: "(\<lambda>(q, ys, ds, t). (E q ys ds, TUPLE t, Er q (update_ys t ys) ds (compute_idx_set t ys),
TUPLE (replace_sym t ys), dir.R)) ` (Q \<times> func_set \<times> UNIV \<times> gamma_set) \<subseteq> \<delta>'"
"(\<lambda>(q, ys, ds, I, t). (Er q ys ds I, TUPLE t, Em q ys ds I, TUPLE (place_hats_R t ds I), dir.L))
` (Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set) \<subseteq> \<delta>'"
"(\<lambda>(q, ys, ds, I, t). (Em q ys ds I, TUPLE t, El q ys ds I, TUPLE (place_hats_M t ds I), dir.L))
` (Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set) \<subseteq> \<delta>'"
"(\<lambda>(q, ys, ds, I). (El q ys ds I, \<turnstile>, E q ys ds, \<turnstile>, dir.N))
` (Q \<times> func_set \<times> UNIV \<times> Pow UNIV) \<subseteq> \<delta>'"
"(\<lambda> (q,ys,ds,I,t). (El q ys ds I, TUPLE t, E q ys ds, TUPLE (place_hats_L t ds I), dir.N))
` (Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set) \<subseteq> \<delta>'"
unfolding \<delta>'_def
by(blast, blast, blast, blast, blast)
(*---------------------------- first step start-----------------------------*)
obtain tup where tup: "tc' (Suc p') = TUPLE tup"
unfolding 1(5) \<Gamma>'_def gamma_set_def enc2.simps by auto
have tup_mem: "tup \<in> gamma_set"
using tup 1(6) valid_next unfolding gamma_set_def 1(5) enc2.simps valid_config.simps
by (smt (z3) Pi_iff UnI1 UnI2 image_iff range_subsetD st_tape_symbol.simps(1))
have bo_set: "bo \<in> func_set"
using 1 \<delta>(4) \<delta>step.simps unfolding func_set_def by fastforce
have rmem: "?rule \<in> \<delta>" using 1(8,7) by (cases rule: \<delta>step.cases, auto)
note elem = \<delta>[OF this]
let ?rep_tup = "TUPLE (replace_sym tup bo)"
let ?tc1 = "(tc'(Suc p' := ?rep_tup))"
let ?I = "compute_idx_set tup bo"
let ?ys' = "update_ys tup bo"
let ?er = "Er q1 ?ys' d ?I"
let ?cs1 = "Config\<^sub>S ?er ?tc1 (Suc(Suc p'))"
have "(q1,bo,d,tup) \<in> Q \<times> func_set \<times> UNIV \<times> gamma_set" using elem tup_mem bo_set by blast
hence mem: "(E q1 bo d, tc' (Suc p'), ?er, ?rep_tup, dir.R) \<in> \<delta>'"
using \<delta>'_mem[OF _ trans(1)] unfolding split tup by fast
note dstep_help = st.dstep[of "E q1 bo d" "tc'" "(Suc p')" ?er ?rep_tup "dir.R"]
have to_r: "(Config\<^sub>S (E q1 bo d) tc' (Suc p'), ?cs1) \<in> st.dstep"
using dstep_help[OF mem] unfolding \<delta>'_def go_dir.simps tup by fast
(*---------------------------- first step end-----------------------------*)
(*---------------------------- second step start-----------------------------*)
obtain tup2 where tup2: "tc' (Suc(Suc p')) = TUPLE tup2"
unfolding 1(5) \<Gamma>'_def gamma_set_def enc2.simps by auto
have tup2_mem: "tup2 \<in> gamma_set"
using tup2 1(6) valid_next
unfolding gamma_set_def 1(5) enc2.simps valid_config.simps
by (smt (z3) Pi_iff UnI1 UnI2 imageI range_subsetD st_tape_symbol.inject(1))
let ?em = "Em q1 ?ys' d ?I"
let ?tc2 = "(?tc1(Suc(Suc p') := TUPLE (place_hats_R tup2 d ?I)))"
let ?cs2 = "Config\<^sub>S ?em ?tc2 (Suc p')"
have "(q1,?ys',d,?I,tup2) \<in> Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set"
using update_ys_range[OF tup_mem bo_set] elem tup2_mem by blast
hence mem2: "(?er, ?tc1 (Suc(Suc p')), Em q1 ?ys' d ?I, TUPLE (place_hats_R tup2 d ?I), dir.L) \<in> \<delta>'"
using \<delta>'_mem[OF _ trans(2)] tup2 unfolding split by auto
note dstep_help2 = st.dstep[of ?er ?tc1 "Suc(Suc p')" ?em "TUPLE (place_hats_R tup2 d ?I)" "dir.L"]
have to_m: "(?cs1, ?cs2) \<in> st.dstep"
using dstep_help2[OF mem2] tup2 unfolding \<delta>'_def go_dir.simps by fastforce
(*---------------------------- second step end-----------------------------*)
(*---------------------------- third step start-----------------------------*)
have "(q1,?ys',d,?I,replace_sym tup bo) \<in> Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set"
using update_ys_range[OF tup_mem bo_set] replace_sym_range[OF tup_mem bo_set] elem(3) by blast
hence mem3: "(?em, ?tc2 (Suc p'), El q1 ?ys' d ?I, TUPLE (place_hats_M (replace_sym tup bo) d ?I), dir.L) \<in> \<delta>'"
using \<delta>'_mem[OF _ trans(3)] by auto
note dstep_help3 = st.dstep[of ?em ?tc2 "Suc p'" "El q1 ?ys' d ?I" "TUPLE (place_hats_M (replace_sym tup bo) d ?I)" dir.L]
let ?el = "El q1 (update_ys tup bo) d (compute_idx_set tup bo)"
let ?tc3 = "tc'(Suc p' := TUPLE (replace_sym tup bo),
Suc (Suc p') := TUPLE (place_hats_R tup2 d (compute_idx_set tup bo)),
Suc p' := TUPLE (place_hats_M (replace_sym tup bo) d (compute_idx_set tup bo)))"
let ?cs3 = "Config\<^sub>S ?el ?tc3 p'"
have to_l: "(?cs2, ?cs3) \<in> st.dstep"
using dstep_help3[OF mem3] unfolding \<delta>'_def go_dir.simps by fastforce
(*---------------------------- third step end-----------------------------*)
have steps3: "(cs, ?cs3) \<in> st.dstep ^^ 3" unfolding numeral_3_eq_3 using to_l to_m to_r 1(1) by auto
(*-------case distinction depending on whether end of tape is reached------------------*)
have tc1_def: "\<And> k. tc1 k = (tc k)(p k := b k)"
using 1(8) unfolding 1(7) by (simp add: \<delta>step.simps old.prod.inject)
have p1_def: "\<And> k. p1 k = go_dir (d k) (p k)"
using 1(8) unfolding 1(7) by (simp add: \<delta>step.simps old.prod.inject)
have not_I_mem_current_pos: "\<forall> k'. k' \<notin> ?I \<longrightarrow> p k' \<noteq> p'"
by(intro allI impI, insert tup elem 1(6), fastforce simp: 1 compute_idx_set_def)
have I_mem_current_pos: "\<forall> k. k \<in> ?I \<longrightarrow> p k = p'"
using compute_idx_set_def 1(5,9) tup by(simp, fastforce)
have I_mem_eq_cur_pos: "\<forall> k. k \<in> ?I \<longleftrightarrow> p k = p'"
using I_mem_current_pos not_I_mem_current_pos by auto
show ?thesis
proof(cases p')
case p_zero: 0
hence tc3_tup: "?tc3 p' = \<turnstile>" using 1(4) by simp
have "(q1,?ys',d,?I) \<in> Q \<times> func_set \<times> UNIV \<times> UNIV"
using update_ys_range[OF tup_mem bo_set] replace_sym_range[OF tup_mem bo_set] elem(3) by blast
hence mem4: "(El q1 ?ys' d ?I, ?tc3 p', E q1 ?ys' d, \<turnstile>, dir.N) \<in> \<delta>'"
using \<delta>'_mem[OF _ trans(4)] unfolding tc3_tup by auto
let ?tc4 = "?tc3(p' := \<turnstile>)"
let ?cs4 = "Config\<^sub>S (E q1 ?ys' d) ?tc4 p'"
note dstep_help4 = st.dstep[of "El q1 ?ys' d ?I" ?tc3 p' "E q1 ?ys' d" \<turnstile> dir.N]
have "(?cs3, ?cs4) \<in> st.dstep ^^ 1"
using dstep_help4[OF mem4] unfolding \<delta>'_def go_dir.simps relpow_1 tc3_tup by fastforce
hence steps: "(cs, ?cs4) \<in> st.dstep ^^ 4"
using relpow_transI[OF steps3] by fastforce
note intro_helper = rel_E.intros[of ?tc4 q tc p q1 tc1 p1 p' rule a b d "update_ys tup bo"]
have valid_subs: "(\<forall> i. (tc'(Suc p' := TUPLE (replace_sym tup bo),
Suc (Suc p') := TUPLE (place_hats_R tup2 d (compute_idx_set tup bo)),
Suc p' := TUPLE (place_hats_M (replace_sym tup bo) d (compute_idx_set tup bo)),
p' := \<turnstile>)) (Suc i) = enc2 (Config\<^sub>M q tc p) (Config\<^sub>M q1 tc1 p1) p' i)"
proof
fix i
consider (zer) "i = 0" | (suc) "i = Suc 0" | (ge_one) "i > Suc 0" by linarith
then show "(tc'(Suc p' := TUPLE (replace_sym tup bo),
Suc (Suc p') := TUPLE (place_hats_R tup2 d (compute_idx_set tup bo)),
Suc p' := TUPLE (place_hats_M (replace_sym tup bo) d (compute_idx_set tup bo)),
p' := \<turnstile>)) (Suc i) = enc2 (Config\<^sub>M q tc p) (Config\<^sub>M q1 tc1 p1) p' i"
proof(cases)
case zer
have "(case replace_sym tup bo k of
NO_HAT a \<Rightarrow> if k \<in> compute_idx_set tup bo \<and> d k = dir.N then HAT a else NO_HAT a
| HAT x \<Rightarrow> HAT x) = (if p1 k = 0 then HAT (tc1 k 0) else NO_HAT (tc1 k 0))" for k
proof(cases "k \<in> ?I")
case k_in_I: True
then obtain x where rep_no_hat: "replace_sym tup bo k = NO_HAT x"
unfolding replace_sym_def compute_idx_set_def by auto
have pk_zero: "p k = 0"
using k_in_I less_Suc0 p_zero unfolding compute_idx_set_def 1(9) by fastforce
show ?thesis
proof(cases "d k = dir.N")
case False
moreover have "tc k (p k) = LE"
using 1(6) pk_zero 1(8) by auto
moreover have "tc k (p k) = a k"
using 1(7,8) pk_zero unfolding \<delta>step.simps by blast
ultimately have "d k = dir.R"
using \<delta>LE[OF rmem] by auto
then show ?thesis
by(insert k_in_I p1_def tc1_def, simp, insert rep_no_hat, auto simp: replace_sym_def 1(9) p_zero pk_zero)
qed(insert k_in_I rep_no_hat pk_zero 1(9), auto simp: replace_sym_def tc1_def p1_def)
next
case False
show ?thesis
using tup False 1(5) p_zero not_I_mem_current_pos p1_def tc1_def
unfolding p_zero replace_sym_def by fastforce
qed
then show ?thesis
unfolding zer p_zero place_hats_M_def place_hats_to_dir_def by simp
next
case suc
have "(case tup2 k of
NO_HAT a \<Rightarrow> if k \<in> compute_idx_set tup bo \<and> d k = dir.R then HAT a else NO_HAT a
| HAT x \<Rightarrow> HAT x) = (if p1 k = Suc 0 then HAT (tc1 k (Suc 0)) else NO_HAT (tc1 k (Suc 0)))" for k
using tup2 p_zero elem(4) 1(5,6,9) gr_zeroI tm(4) tup
by (auto simp: compute_idx_set_def tc1_def p1_def, smt (verit, best) diff_0_eq_0 go_dir.elims not_gr0)
then show ?thesis unfolding suc p_zero place_hats_R_def place_hats_to_dir_def by simp
next
case ge_one
have "(if p k = 0 then if p k = i then HAT (tc k i) else NO_HAT (tc k i)
else if p1 k = i then HAT (tc1 k i) else NO_HAT (tc1 k i)) = (if p1 k = i then HAT (tc1 k i) else NO_HAT (tc1 k i))" for k
using insert ge_one p1_def tc1_def
by (smt (verit, ccfv_threshold) diff_0_eq_0 fun_upd_other go_dir.elims less_irrefl_nat less_nat_zero_code)
then show ?thesis using ge_one p_zero 1(5)[of i] enc2.simps by simp
qed
qed
have only_hats: "\<And> k. p k = 0 \<longrightarrow> tup k \<in> HAT ` \<Gamma>"
using tup unfolding p_zero 1(5)[of 0] enc2.simps by (simp, meson imageI tup_hat_content tup_mem)
have "(if k \<in> compute_idx_set tup bo then \<bullet> else bo k) = \<bullet>" for k
using only_hats elem(4) 1(9) by (auto simp: compute_idx_set_def p_zero)
hence replaced_all: "update_ys tup bo = (\<lambda>k. if p k < p' then SYM (b k) else \<bullet>)"
unfolding update_ys_def p_zero by auto
have invs: "rel_E ?cs4 cm cm1 rule p'"
using valid_subs p_zero intro_helper[OF _ _ 1(6) 1(7) 1(8) replaced_all] 1(2,3,7) by auto
then show ?thesis
by(insert steps invs, intro exI conjI, auto)
next
case (Suc nat)
obtain tup3 where tc3_p': "?tc3 p' = TUPLE tup3" and
tup3_def: "tup3 = (\<lambda>k. if p k < Suc (Suc nat) then if p k = nat then HAT (tc k nat) else NO_HAT (tc k nat)
else if p1 k = nat then HAT (tc1 k nat) else NO_HAT (tc1 k nat))"
using 1(5)[of nat] unfolding Suc enc2.simps by simp
have tup3_mem: "tup3 \<in> gamma_set"
using tup3_def 1(6) valid_next unfolding gamma_set_def 1(5) enc2.simps valid_config.simps
by (smt (z3) Pi_I UnI1 UnI2 imageI range_subsetD st_tape_symbol.inject(1))
let ?a4 = "TUPLE (place_hats_L tup3 d (compute_idx_set tup bo))"
let ?tc4 = "?tc3(p' := ?a4)"
let ?cs4 = "Config\<^sub>S (E q1 ?ys' d) ?tc4 p'"
have step_mem:"(q1, ?ys', d, ?I, tup3) \<in> Q \<times> func_set \<times> UNIV \<times> UNIV \<times> gamma_set"
using update_ys_range[OF tup_mem bo_set] replace_sym_range[OF tup_mem bo_set] elem(3) tup3_mem by blast
have mem5: "(El q1 ?ys' d ?I, ?tc3 p', E q1 ?ys' d, TUPLE (place_hats_L tup3 d (compute_idx_set tup bo)), dir.N) \<in> \<delta>'"
using \<delta>'_mem[OF step_mem trans(5)] unfolding split tc3_p' .
note dstep_help5 = st.dstep[of "El q1 ?ys' d ?I" ?tc3 p' "E q1 ?ys' d" ?a4 dir.N]
note intros_helper2 = rel_E.intros[of ?tc4 q tc p q1 tc1 p1 p' rule a b d "update_ys tup bo"]
have correct_shift: "(tc'(Suc p' := TUPLE (replace_sym tup bo),
Suc (Suc p') := TUPLE (place_hats_R tup2 d (compute_idx_set tup bo)),
Suc p' := TUPLE (place_hats_M (replace_sym tup bo) d (compute_idx_set tup bo)),
p' := TUPLE (place_hats_L tup3 d (compute_idx_set tup bo))))
(Suc i) = enc2 (Config\<^sub>M q tc p) (Config\<^sub>M q1 tc1 p1) p' i" for i
proof -
consider (one) "Suc i = Suc nat"
| (two) "Suc i = Suc(Suc nat)"
| (three) "Suc i = Suc(Suc(Suc nat))"
| (else) "Suc i \<notin> {Suc nat ,Suc(Suc nat), Suc(Suc(Suc nat))}" by blast
then show ?thesis
proof cases
case one
have "(case tup3 k of
NO_HAT a \<Rightarrow> if k \<in> compute_idx_set tup bo \<and> d k = dir.L then HAT a else NO_HAT a
| HAT x \<Rightarrow> HAT x) = (if p k < Suc nat then if p k = i then HAT (tc k i) else NO_HAT (tc k i)
else if p1 k = i then HAT (tc1 k i) else NO_HAT (tc1 k i))" for k
using one I_mem_eq_cur_pos Suc nat_less_le
by (cases "d k", auto simp: tc1_def p1_def tup3_def compute_idx_set_def)
then show ?thesis
using one unfolding Suc place_hats_L_def place_hats_to_dir_def by auto
next
case two
have "(case replace_sym tup bo k of
NO_HAT a \<Rightarrow> if k \<in> compute_idx_set tup bo \<and> d k = dir.N then HAT a else NO_HAT a
| HAT x \<Rightarrow> HAT x) = (if p k < Suc nat then if p k = i then HAT (tc k i) else NO_HAT (tc k i)
else if p1 k = i then HAT (tc1 k i) else NO_HAT (tc1 k i))" for k
using two 1(5,9) Suc tup elem(4) not_I_mem_current_pos
by (cases "d k", auto simp: replace_sym_def compute_idx_set_def p1_def tc1_def)
then show ?thesis
unfolding two Suc enc2.simps place_hats_M_def place_hats_to_dir_def by simp
next
case three
have "(case tup2 k of
NO_HAT a \<Rightarrow> if k \<in> compute_idx_set tup bo \<and> d k = dir.R then HAT a else NO_HAT a
| HAT x \<Rightarrow> HAT x) = (if p k < Suc nat then if p k = i then HAT (tc k i) else NO_HAT (tc k i)
else if p1 k = i then HAT (tc1 k i) else NO_HAT (tc1 k i))" for k
using three p1_def tc1_def compute_idx_set_def tup2 Suc 1(9) elem(4) I_mem_eq_cur_pos less_SucE
unfolding 1(5) enc2.simps by (cases "d k", auto)
then show ?thesis
unfolding three Suc enc2.simps place_hats_R_def place_hats_to_dir_def by simp
next
case else
have "(if p k < Suc (Suc nat) then if p k = i then HAT (tc k i) else NO_HAT (tc k i)
else if p1 k = i then HAT (tc1 k i) else NO_HAT (tc1 k i)) =
(if p k < Suc nat then if p k = i then HAT (tc k i) else NO_HAT (tc k i)
else if p1 k = i then HAT (tc1 k i) else NO_HAT (tc1 k i))" for k
unfolding 1(5) enc2.simps Suc
using else p1_def tc1_def
by (cases "d k") auto
then show ?thesis
using else Suc 1(5) enc2.simps by auto
qed
qed
have correct_replace: "update_ys tup bo = (\<lambda>k. if p k < p' then SYM (b k) else \<bullet>)"
by(insert I_mem_eq_cur_pos 1(9), auto simp: Suc update_ys_def)
have step: "(?cs3, ?cs4) \<in> st.dstep ^^ 1"
using mem5 dstep_help5[OF mem5]
unfolding \<delta>'_def go_dir.simps relpow_1 Suc by fastforce
hence "(cs, ?cs4) \<in> st.dstep ^^ 4"
using relpow_transI[OF steps3 step] by simp
moreover have "rel_E ?cs4 cm cm1 rule p'"
using Suc 1 intros_helper2[OF _ _ 1(6) 1(7) 1(8) correct_replace] correct_shift by simp
ultimately show ?thesis by blast
qed
qed
lemma E_phase: assumes "rel_E\<^sub>0 cs cm cm1 rule"
shows "\<exists> cs'. (cs,cs') \<in> st.dstep ^^ (6 + 4 * Max (range (mt_pos cm))) \<and> rel_S\<^sub>0 cs' cm1"
proof -
from rel_E\<^sub>0_E[OF assms] obtain n cs1 where step1: "(cs, cs1) \<in> st.dstep"
and n: "n = Suc (Max (range (mt_pos cm)))"
and rel: "rel_E cs1 cm cm1 rule n"
by auto
from rel have "\<exists> cs2. (cs1,cs2) \<in> st.dstep^^(4 * n) \<and> rel_E cs2 cm cm1 rule 0"
proof (induction n arbitrary: cs1 rule: nat_induct)
case (Suc n)
from rel_E_E[OF Suc.prems] obtain cs' where
step4: "(cs1, cs') \<in> st.dstep ^^ 4" and rel: "rel_E cs' cm cm1 rule n" by auto
from Suc.IH[OF rel] obtain cs2 where
steps: "(cs', cs2) \<in> st.dstep ^^ (4 * n)" and rel: "rel_E cs2 cm cm1 rule 0"
by auto
from relpow_transI[OF step4 steps] rel show ?case by auto
qed auto
then obtain cs2 where steps2: "(cs1,cs2) \<in> st.dstep^^(4 * n)" and rel: "rel_E cs2 cm cm1 rule 0" by auto
from rel_E_S\<^sub>0[OF rel] obtain cs' where step3: "(cs2, cs') \<in> st.dstep" and rel: "rel_S\<^sub>0 cs' cm1" by auto
from relpow_Suc_I2[OF step1 relpow_Suc_I[OF steps2 step3]]
have "(cs, cs') \<in> st.dstep ^^ Suc (Suc (4 * n))" by simp
also have "Suc (Suc (4 * n)) = 6 + 4 * Max (range (mt_pos cm))" unfolding n by simp
finally show ?thesis using rel by auto
qed
subsubsection \<open>Simulation of multitape TM by singletape TM\<close>
lemma step_simulation: assumes "rel_S\<^sub>0 cs cm"
and "(cm, cm') \<in> step"
shows "\<exists> cs'. (cs,cs') \<in> st.step ^^ (10 + 5 * Max (range (mt_pos cm))) \<and> rel_S\<^sub>0 cs' cm'"
proof -
let ?n = "Max (range (mt_pos cm))"
from assms(2) have "mt_state cm \<notin> {t, r}" using \<delta>_set
by (cases, auto)
from S_phase[OF assms(1) this] obtain cs1 where
steps1: "(cs, cs1) \<in> st.dstep ^^ (3 + ?n)" and rel: "rel_S\<^sub>1 cs1 cm"
by auto
from rel_S\<^sub>1_E\<^sub>0_step[OF rel assms(2)] obtain r cs2 where
step2: "(cs1, cs2) \<in> st.step" and rel: "rel_E\<^sub>0 cs2 cm cm' r"
by auto
from E_phase[OF rel] obtain cs' where
steps3: "(cs2, cs') \<in> st.dstep ^^ (6 + 4 * ?n)" and rel: "rel_S\<^sub>0 cs' cm'"
by auto
from relpow_transI[OF dsteps_to_steps[OF steps1] relpow_Suc_I2[OF step2 dsteps_to_steps[OF steps3]]]
have "(cs, cs') \<in> st.step ^^ ((3 + ?n) + Suc (6 + 4 * ?n))" by simp
also have "((3 + ?n) + Suc (6 + 4 * ?n)) = 10 + 5 * ?n" by simp
finally show ?thesis using rel by auto
qed
lemma steps_simulation_main: assumes "rel_S\<^sub>0 cs cm"
and "Max (range (mt_pos cm)) \<le> N"
and "(cm, cm') \<in> step^^n"
shows "\<exists> m cs'. (cs,cs') \<in> st.step^^m \<and> rel_S\<^sub>0 cs' cm' \<and> m \<le> sum (\<lambda> i. 10 + 5 * (N + i)) {..< n} \<and> Max (range (mt_pos cm')) \<le> N + n"
using assms(3,1,2)
proof (induct n arbitrary: cm' N)
case 0
show ?case
by (intro exI[of _ 0] exI[of _ cs], insert 0, auto)
next
case (Suc n cm' N)
from Suc(2) obtain cm'' where "(cm,cm'') \<in> step^^n" and step: "(cm'', cm') \<in> step" by auto
from Suc(1)[OF this(1) Suc(3-4)] obtain m cs'' where
steps: "(cs, cs'') \<in> st.step ^^ m" and m: "m \<le> (\<Sum>i < n. 10 + 5 * (N + i))" and rel: "rel_S\<^sub>0 cs'' cm''" and max: "Max (range (mt_pos cm'')) \<le> N + n"
by auto
from step_simulation[OF rel step] obtain cs' where
steps2: "(cs'', cs') \<in> st.step ^^ (10 + 5 * Max (range (mt_pos cm'')))" and rel: "rel_S\<^sub>0 cs' cm'" by auto
let ?m = "m + (10 + 5 * Max (range (mt_pos cm'')))"
from relpow_transI[OF steps steps2]
have steps: "(cs, cs') \<in> st.step ^^ ?m" by auto
show ?case
proof (intro exI conjI, rule steps, rule rel)
from max_mt_pos_step[OF step] max
show "Max (range (mt_pos cm')) \<le> N + Suc n" by linarith
have id: "{..<Suc n} = insert n {..< n}" by auto
have "?m \<le> m + (10 + 5 * (N + n))" using max by presburger
also have "\<dots> \<le> (\<Sum>i < Suc n. 10 + 5 * (N + i))" using m unfolding id by auto
finally show "?m \<le> (\<Sum>i < Suc n. 10 + 5 * (N + i))" by auto
qed
qed
lemma steps_simulation_rel_S\<^sub>0: assumes "rel_S\<^sub>0 cs (init_config w)"
and "(init_config w, cm') \<in> step^^n"
shows "\<exists> m cs'. (cs,cs') \<in> st.step^^m \<and> rel_S\<^sub>0 cs' cm' \<and> m \<le> 3 * n^2 + 7 * n"
proof -
from steps_simulation_main[OF assms(1) _ assms(2), unfolded max_mt_pos_init, OF le_refl]
obtain m cs' where steps: "(cs, cs') \<in> st.step ^^ m" and rel: "rel_S\<^sub>0 cs' cm'" and m: "m \<le> (\<Sum>i<n. 10 + 5 * i)"
by auto
have "m \<le> (\<Sum>i<n. 10 + 5 * i)" by fact
also have "\<dots> \<le> 3 * n^2 + 7 * n" using aux_sum_formula .
finally show ?thesis using steps rel by auto
qed
lemma simulation_with_complexity: assumes w: "set w \<subseteq> \<Sigma>"
and steps: "(init_config w, Config\<^sub>M q mtape p) \<in> step^^n"
shows "\<exists> stape k. (st.init_config (map INP w), Config\<^sub>S (S\<^sub>0 q) stape 0) \<in> st.step^^k \<and> k \<le> 2 * length w + 3 * n^2 + 7 * n + 3"
proof -
let ?INP = "INP :: 'a \<Rightarrow> ('a, 'k) st_tape_symbol"
let ?initm = "init_config w"
define x where "x = map ?INP w"
from R_phase[OF w, folded x_def] obtain cs where
steps1: "(st.init_config x, cs) \<in> st.dstep ^^ (3 + 2 * length w)" and rel: "rel_S\<^sub>0 cs ?initm"
by auto
from steps_simulation_rel_S\<^sub>0[of _ w, OF rel steps] obtain k' cs' where
steps2: "(cs, cs') \<in> st.step^^k'" and
rel: "rel_S\<^sub>0 cs' (Config\<^sub>M q mtape p)" and
k': "k' \<le> 3 * n^2 + 7 * n" by auto
let ?k = "3 + 2 * length w + k'"
from relpow_transI[OF dsteps_to_steps[OF steps1] steps2]
have steps: "(st.init_config x, cs') \<in> st.step ^^ ?k" .
from rel obtain stape where cs': "cs' = Config\<^sub>S (S\<^sub>0 q) stape 0"
by (cases, auto)
show ?thesis
by (intro exI[of _ stape] exI[of _ ?k], insert steps cs' k', auto simp: x_def)
qed
lemma simulation: "map INP ` Lang \<subseteq> st.Lang"
proof
fix x :: "('a, 'k) st_tape_symbol list"
assume "x \<in> map INP ` Lang"
then obtain w where mem: "w \<in> Lang" and x: "x = map INP w" by auto
define cm where "cm = init_config w"
from mem[unfolded Lang_def] obtain w' n where w: "set w \<subseteq> \<Sigma>" and steps: "(cm, Config\<^sub>M t w' n) \<in> step^*" by (auto simp: cm_def)
from rtrancl_imp_relpow[OF steps] obtain num where steps: "(cm, Config\<^sub>M t w' n) \<in> step^^num" by auto
from simulation_with_complexity[OF w, folded cm_def, OF steps] obtain stape
where steps: "(st.init_config (map INP w), Config\<^sub>S (S\<^sub>0 t) stape 0) \<in> st.step^*"
using relpow_imp_rtrancl by blast
show "x \<in> st.Lang" using steps w unfolding x st.Lang_def by auto
qed
subsubsection \<open>Simulation of singletape TM by multitape TM\<close>
lemma rev_simulation: "st.Lang \<subseteq> map INP ` Lang"
proof
fix x :: "('a, 'k) st_tape_symbol list"
let ?INP = "INP :: 'a \<Rightarrow> ('a, 'k) st_tape_symbol"
assume "x \<in> st.Lang"
from this[unfolded st.Lang_def] obtain ts p where x: "set x \<subseteq> ?INP ` \<Sigma>"
and steps: "(st.init_config x, Config\<^sub>S (S\<^sub>0 t) ts p) \<in> st.step^*" by force
let ?NF = "Config\<^sub>S (S\<^sub>0 t) ts p"
have NF: "\<not> (\<exists> c. (?NF, c) \<in> st.step)"
proof
assume "\<exists> c. (?NF, c) \<in> st.step"
then obtain c where "(?NF, c) \<in> st.step" by auto
thus False
by (cases rule: st.step.cases, insert st.\<delta>_set, auto)
qed
from INP_D[OF x] obtain w where x: "x = map ?INP w" and w: "set w \<subseteq> \<Sigma>" by auto
define cm where "cm = init_config w"
from R_phase[OF w, folded x] obtain cs where
dsteps: "(st.init_config x, cs) \<in> st.dstep ^^ (3 + 2 * length w)" and rel: "rel_S\<^sub>0 cs cm"
by (auto simp: cm_def)
from steps obtain k where "(st.init_config x, ?NF) \<in> st.step^^k" using rtrancl_power by blast
from st.dsteps_inj[OF dsteps this NF] obtain n where ssteps: "(cs, ?NF) \<in> st.step ^^ n" by auto
from rel ssteps have "\<exists> cm'. (cm,cm') \<in> step^* \<and> rel_S\<^sub>0 ?NF cm'"
proof (induct n arbitrary: cs cm rule: less_induct)
case (less n cs cm)
note rel = less(2)
note steps = less(3)
show ?case
proof (cases "mt_state cm \<in> {t, r}")
case True
with rel obtain ts' p' q where cs: "cs = Config\<^sub>S (S\<^sub>0 q) ts' p'" and q: "q \<in> {t,r}"
by (cases, auto)
have NF: False if "(cs, cs') \<in> st.step" for cs' using that unfolding cs using q
by (cases rule: st.step.cases, insert st.\<delta>_set, auto)
have "cs = ?NF"
proof (cases n)
case 0
thus ?thesis using steps by auto
next
case (Suc m)
from NF relpow_Suc_E2[OF steps[unfolded this]] show ?thesis by auto
qed
thus ?thesis using rel by auto
next
case False
define N where "N = Max (range (mt_pos cm))"
from S_phase[OF rel False] obtain cs1 where dsteps: "(cs, cs1) \<in> st.dstep ^^ (3 + N)" and rel: "rel_S\<^sub>1 cs1 cm" by (auto simp: N_def)
from st.dsteps_inj[OF dsteps steps NF] obtain k1 where n: "n = 3 + N + k1" and steps: "(cs1, ?NF) \<in> st.step ^^ k1" by auto
from rel have "cs1 \<noteq> ?NF" by (cases, auto)
then obtain k where k1: "k1 = Suc k" using steps by (cases k1, auto)
from relpow_Suc_E2[OF steps[unfolded this]] obtain cs2 where step: "(cs1, cs2) \<in> st.step" and steps: "(cs2,?NF) \<in> st.step ^^ k" by auto
from rel_S\<^sub>1_E\<^sub>0_st_step[OF rel step] obtain cm1 rule where mstep: "(cm, cm1) \<in> step" and rel: "rel_E\<^sub>0 cs2 cm cm1 rule" by auto
from E_phase[OF rel] obtain cs3 where dsteps: "(cs2, cs3) \<in> st.dstep ^^ (6 + 4 * N)" and rel: "rel_S\<^sub>0 cs3 cm1" by (auto simp: N_def)
from st.dsteps_inj[OF dsteps steps NF] obtain m where k: "k = 6 + 4 * N + m" and steps: "(cs3, Config\<^sub>S (S\<^sub>0 t) ts p) \<in> st.step ^^ m"
by auto
have "m < n" unfolding n k1 k by auto
from less(1)[OF this rel steps] obtain cm' where msteps: "(cm1, cm') \<in> step^*" and rel: "rel_S\<^sub>0 ?NF cm'" by auto
from mstep msteps have "(cm, cm') \<in> step^*" by auto
with rel show ?thesis by auto
qed
qed
then obtain cm' where msteps: "(cm, cm') \<in> step^*" and rel: "rel_S\<^sub>0 ?NF cm'" by auto
from rel obtain tc p where cm': "cm' = Config\<^sub>M t tc p" by (cases, auto)
from msteps have "w \<in> Lang" unfolding cm_def cm' Lang_def using w by auto
thus "x \<in> map INP ` Lang" unfolding x by auto
qed
lemma rev_simulation_complexity: assumes w: "set w \<subseteq> \<Sigma>"
and steps: "(st.init_config (map INP w), cs) \<in> st.step^^n"
and n: "n \<ge> 2 * length w + 3 * k^2 + 7 * k + 3"
shows "\<exists> cm. (init_config w, cm) \<in> step^^k"
proof -
let ?INP = "INP :: 'a \<Rightarrow> ('a, 'k) st_tape_symbol"
define cm1 where "cm1 = init_config w"
define x where "x = map ?INP w"
from R_phase[OF w, folded x_def] obtain cs1 where
steps1: "(st.init_config x, cs1) \<in> st.dstep ^^ (3 + 2 * length w)" and rel1: "rel_S\<^sub>0 cs1 cm1"
by (auto simp: cm1_def)
from st.dsteps_inj'[OF steps1 steps[folded x_def]] obtain n1 where
nn1: "n = 3 + 2 * length w + n1" and
ssteps1: "(cs1, cs) \<in> st.step ^^ n1"
using n by auto
define M where "M = (0 :: nat)"
have r: "Max (range (mt_pos cm1)) \<le> M" unfolding M_def cm1_def by (simp add: max_mt_pos_init)
from nn1 n have "n1 \<ge> 3 * k^2 + 7 * k" by auto
hence n1: "n1 \<ge> sum (\<lambda> i. 10 + 5 * (M + i)) {..< k}" unfolding M_def
using aux_sum_formula[of k] by simp
from ssteps1 rel1 n1 r show ?thesis unfolding cm1_def[symmetric]
proof (induct k arbitrary: cs1 cm1 M n1)
case (Suc k cs1 cm1 M n1)
let ?M = "Max (range (mt_pos cm1))"
define n where "n = (\<Sum>i<k. 10 + 5 * (Suc M + i))"
from Suc(4) have "n1 \<ge> n + 10 + M * 5" unfolding n_def
by (simp add: algebra_simps sum.distrib)
with Suc(5) have n1: "n1 \<ge> n + 10 + 5 * ?M" by linarith
show ?case
proof (cases "mt_state cm1 \<in> {t, r}")
case False
from S_phase[OF Suc(3) False]
obtain cs2 where steps2: "(cs1, cs2) \<in> st.dstep ^^ (3 + ?M)" and rel2: "rel_S\<^sub>1 cs2 cm1" by auto
from st.dsteps_inj'[OF steps2 Suc(2)] n1 obtain n2 where
n12: "n1 = 3 + ?M + n2" and
steps2: "(cs2, cs) \<in> st.step ^^ n2"
by auto
from n12 n1 obtain n3 where n23: "n2 = Suc n3" by (cases n2, auto)
from steps2 obtain cs3 where step: "(cs2, cs3) \<in> st.step" and steps3: "(cs3,cs) \<in> st.step ^^ n3" unfolding n23 by (metis relpow_Suc_E2)
from rel_S\<^sub>1_E\<^sub>0_st_step[OF rel2 step] obtain cm2 rule where step: "(cm1, cm2) \<in> step" and rel3: "rel_E\<^sub>0 cs3 cm1 cm2 rule" by auto
let ?M2 = "Max (range (mt_pos cm2))"
from n1 n12 n23 have n3: "6 + 4 * ?M \<le> n3" by auto
from E_phase[OF rel3] obtain cs4 where dsteps: "(cs3, cs4) \<in> st.dstep ^^ (6 + 4 * ?M)" and rel4: "rel_S\<^sub>0 cs4 cm2" by auto
from st.dsteps_inj'[OF dsteps steps3 n3] obtain n4 where n34: "n3 = 6 + 4 * ?M + n4"
and steps: "(cs4, cs) \<in> st.step ^^ n4" by auto
from max_mt_pos_step[OF step] Suc(5)
have M2: "?M2 \<le> Suc M" by linarith
have n4: "n \<le> n4" using n34 n12 n23 n1 by simp
from Suc(1)[OF steps rel4 n4[unfolded n_def] M2] obtain cm where "(cm2, cm) \<in> step ^^ k" ..
with step have "(cm1, cm) \<in> step ^^ (Suc k)" by (metis relpow_Suc_I2)
thus ?thesis ..
next
case True
from n1 obtain n2 where "n1 = Suc n2" by (cases n1, auto)
from relpow_Suc_E2[OF Suc(2)[unfolded this]]
obtain cs2 where step: "(cs1, cs2) \<in> st.step" by auto
from rel_S\<^sub>0.cases[OF Suc(3)] obtain tc' q tc p where
cs1: "cs1 = Config\<^sub>S (S\<^sub>0 q) tc' 0" and
cm1: "cm1 = Config\<^sub>M q tc p"
by metis
with True have q: "q \<in> {t,r}" by auto
from st.step.cases[OF step] obtain ts q' a dir where rule: "(S\<^sub>0 q, ts, q', a, dir) \<in> \<delta>'"
unfolding cs1 by fastforce
with q have False unfolding \<delta>'_def by auto
thus ?thesis by simp
qed
qed auto
qed
subsubsection \<open>Main Results\<close>
theorem language_equivalence: "st.Lang = map INP ` Lang"
using simulation rev_simulation by auto
theorem upper_time_bound_quadratic_increase: assumes "upper_time_bound f"
shows "st.upper_time_bound (\<lambda> n. 3 * (f n)^2 + 13 * f n + 2 * n + 12)"
unfolding st.upper_time_bound_def
proof (intro allI impI, rule ccontr)
fix ww c n
assume "set ww \<subseteq> INP ` \<Sigma>" and steps: "(st.init_config ww, c) \<in> st.step ^^ n"
and bnd: "\<not> n \<le> 3 * (f (length ww))\<^sup>2 + 13 * (f (length ww)) + 2 * length ww + 12"
from INP_D[OF this(1)] obtain w where w: "set w \<subseteq> \<Sigma>" and ww: "ww = map INP w" by auto
let ?lw = "length w"
from bnd have "n \<ge> 2 * ?lw + 3 * (f ?lw + 1)\<^sup>2 + 7 * (f ?lw + 1) + 3"
by (auto simp: ww power2_eq_square)
from rev_simulation_complexity[OF w steps[unfolded ww] this]
obtain cm where "(init_config w, cm) \<in> step ^^ (f ?lw + 1)" by auto
from assms[unfolded upper_time_bound_def, rule_format, OF w this] show False by simp
qed
end
subsection \<open>Main Results with Proper Renamings\<close>
text \<open>By using the renaming capabilities we can get rid of the @{term "map INP"} in the language
equivalence theorem. We just assume that there will always be enough symbols for the renaming,
i.e., an infinite supply of fresh names is available.\<close>
theorem multitape_to_singletape: assumes "valid_mttm (mttm :: ('p,'a,'k :: {finite,zero})mttm)"
and "infinite (UNIV :: 'q set)"
and "infinite (UNIV :: 'a set)"
shows "\<exists> tm :: ('q,'a)tm. valid_tm tm \<and>
Lang_mttm mttm = Lang_tm tm \<and>
(det_mttm mttm \<longrightarrow> det_tm tm) \<and>
(upperb_time_mttm mttm f \<longrightarrow> upperb_time_tm tm (\<lambda> n. 3 * (f n)^2 + 13 * f n + 2 * n + 12))"
proof (cases mttm)
let ?INP = "INP :: 'a \<Rightarrow> ('a, 'k) st_tape_symbol"
case (MTTM Q \<Sigma> \<Gamma> bl le \<delta> s t r)
from assms(1)[unfolded this]
interpret multitape_tm Q \<Sigma> \<Gamma> bl le \<delta> s t r by simp
let ?TM1 = "TM Q' (?INP ` \<Sigma>) \<Gamma>' blank' \<turnstile> \<delta>' (R\<^sub>1 \<bullet>) (S\<^sub>0 t) (S\<^sub>0 r)"
have valid: "valid_tm ?TM1" unfolding valid_tm.simps using valid_st .
interpret st: singletape_tm Q' "?INP ` \<Sigma>" \<Gamma>' blank' \<turnstile> \<delta>' "R\<^sub>1 \<bullet>" "S\<^sub>0 t" "S\<^sub>0 r" using valid_st .
from language_equivalence
have id: "Lang_tm ?TM1 = map INP ` Lang_mttm mttm" unfolding MTTM by auto
have "finite Q'" using st.fin_Q .
with assms(2) have "\<exists> tq :: (('a, 'p, 'k) st_states \<Rightarrow> 'q). inj_on tq Q'" by (metis finite_infinite_inj_on)
then obtain tq :: "_ \<Rightarrow> 'q" where "inj_on tq Q'" by blast
hence tq: "inj_on tq (Q_tm ?TM1)" by simp
from st.fin_\<Gamma> have finG': "finite \<Gamma>'" .
from fin_\<Sigma> assms(3) have "infinite (UNIV - \<Sigma>)" by auto
then obtain B :: "'a set" where B: "finite B" "card B = card \<Gamma>'" "B \<subseteq> UNIV - \<Sigma>"
by (meson infinite_arbitrarily_large)
from st.fin\<Sigma> have finS': "finite (?INP ` \<Sigma>)" .
from finG' B obtain ta' where bij: "bij_betw ta' \<Gamma>' B"
by (metis bij_betw_iff_card)
define ta where "ta x = (if x \<in> ?INP ` \<Sigma> then (case x of INP y \<Rightarrow> y) else ta' x)" for x
have ta: "inj_on ta (\<Gamma>_tm ?TM1)" using bij B(3)
by (auto simp: bij_betw_def inj_on_def ta_def split: st_tape_symbol.splits)
obtain tm' :: "('q,'a)tm" where valid: "valid_tm tm'" and lang: "Lang_tm tm' = map ta ` map INP ` Lang_mttm mttm"
and det: "st.deterministic \<Longrightarrow> det_tm tm'"
and upper: "\<And> f. st.upper_time_bound f \<Longrightarrow> upperb_time_tm tm' f"
using tm_renaming[OF valid ta tq, unfolded id] by auto
note lang also have "map ta ` map INP ` Lang_mttm mttm = (\<lambda> w. w) ` Lang_mttm mttm"
unfolding image_comp o_def map_map
proof (rule image_cong[OF refl])
fix w
assume "w \<in> Lang_mttm mttm"
hence w: "set w \<subseteq> \<Sigma>" unfolding Lang_def MTTM Lang_mttm.simps by auto
show "map (\<lambda>x. ta (INP x)) w = w"
by (intro map_idI, insert w, auto simp: ta_def)
qed
finally have lang: "Lang_tm tm' = Lang_mttm mttm" by simp
{
assume "det_mttm mttm"
hence deterministic unfolding MTTM by simp
from det_preservation[OF this] have st.deterministic by auto
from det[OF this] have "det_tm tm'" .
} note det = this
{
assume "upperb_time_mttm mttm f"
hence "upper_time_bound f" unfolding MTTM by simp
from upper[OF upper_time_bound_quadratic_increase[OF this]]
have "upperb_time_tm tm' (\<lambda>n. 3 * (f n)\<^sup>2 + 13 * f n + 2 * n + 12)" .
} note upper = this
from valid lang det upper show ?thesis by blast
qed
end
|
{"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Multitape_To_Singletape_TM/Multi_Single_TM_Translation.thy"}
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import json
import argparse
import numpy as np
import h5py
from graph_utils import graph
def build_vocab(imgs, params):
count_thr = params['word_count_threshold']
# count up the number of words
counts = {}
for img in imgs:
for sent in img['sentences']:
for w in sent['tokens']:
w = w.lower()
counts[w] = counts.get(w, 0) + 1
cw = sorted([(count,w) for w,count in counts.items()], reverse=True)
print('top words and their counts:')
print('\n'.join(map(str, cw[:20])))
# print some stats
total_words = sum(counts.values())
print('total words:', total_words)
bad_words = [w for w,n in counts.items() if n <= count_thr]
vocab = [w for w,n in counts.items() if n > count_thr]
bad_count = sum(counts[w] for w in bad_words)
print('number of bad words: %d/%d = %.2f%%' % (len(bad_words), len(counts), len(bad_words)*100.0/len(counts)))
print('number of words in vocab would be %d' % (len(vocab), ))
print('number of UNKs: %d/%d = %.2f%%' % (bad_count, total_words, bad_count*100.0/total_words))
# lets look at the distribution of lengths as well
sent_lengths = {}
for img in imgs:
for sent in img['sentences']:
txt = sent['tokens']
nw = len(txt)
sent_lengths[nw] = sent_lengths.get(nw, 0) + 1
max_len = max(sent_lengths.keys())
print('max length sentence in raw data: ', max_len)
print('sentence length distribution (count, number of words):')
sum_len = sum(sent_lengths.values())
for i in range(max_len+1):
print('%2d: %10d %f%%' % (i, sent_lengths.get(i,0), sent_lengths.get(i,0)*100.0/sum_len))
# lets now produce the final annotations
if bad_count > 0:
# additional special UNK token we will use below to map infrequent words to
print('inserting the special UNK token')
vocab.append('UNK')
def __gloss(x):
if x == "ROOT":
return x
else:
x = x.lower()
if counts.get(x, 0) > count_thr:
return x
else:
return 'UNK'
for img in imgs:
img['final_captions'] = []
for sent in img['sentences']:
txt, depends = sent['tokens'], sent['depends']
caption = [w.lower() if counts.get(w.lower(),0) > count_thr else 'UNK' for w in txt]
for d in depends:
d['dependentGloss'] = __gloss(d['dependentGloss'])
d['governorGloss'] = __gloss(d['governorGloss'])
img['final_captions'].append({'caption': caption, 'depends': depends})
vocab.append('ROOT')
vocab.append('EOB')
return vocab
def encode_captions(imgs, params, wtoi):
max_length = params['max_length']
max_treearray_length = params['max_treearray_length']
N = len(imgs)
M = sum(len(img['final_captions']) for img in imgs) # total number of captions
label_arrays = []
label_start_ix = np.zeros(N, dtype='int32') # note: these will be one-indexed
label_end_ix = np.zeros(N, dtype='int32')
label_length = np.zeros(M, dtype='int32')
tree_arrays = []
tree_array_idx = []
tree_array_length = np.zeros(M, dtype='int32')
caption_counter = 0
counter = 1
for i,img in enumerate(imgs):
n = len(img['final_captions'])
assert n > 0, 'error: some image has no captions'
Li = np.zeros((n, max_length), dtype='int32')
Ti = np.zeros((n, max_treearray_length), dtype='int32')
Fi = np.zeros((n, max_treearray_length), dtype='int32')
for j,fs in enumerate(img['final_captions']):
s = fs['caption']
label_length[caption_counter] = min(max_length, len(s))
for k,w in enumerate(s):
if k < max_length:
Li[j,k] = wtoi[w]
tarray, tarray_idx = graph.depends2array(fs['depends'])
tree_array_length[caption_counter] = min(max_treearray_length, len(tarray))
caption_counter += 1
for k,w in enumerate(tarray):
if k < max_treearray_length:
Ti[j,k] = wtoi[w]
for k,w in enumerate(tarray_idx):
if k < max_treearray_length:
Fi[j,k] = w
# note: word indices are 1-indexed, and captions are padded with zeros
label_arrays.append(Li)
tree_arrays.append(Ti)
tree_array_idx.append(Fi)
label_start_ix[i] = counter
label_end_ix[i] = counter + n - 1
counter += n
print("Writing to h5 file: {:.2f}%".format(i * 100 / N), end="\r")
print()
L = np.concatenate(label_arrays, axis=0) # put all the labels together
print(L.shape)
print(M)
assert L.shape[0] == M, 'L lengths don\'t match? that\'s weird'
assert np.all(label_length > 0), 'error: some caption had no words?'
T = np.concatenate(tree_arrays, axis=0) # put all treearrays together
F = np.concatenate(tree_array_idx, axis=0)
assert T.shape[0] == M, 'T lengths don\'t match? that\'s weird'
assert F.shape[0] == M, 'F lengths don\'t match? that\'s weird'
assert np.all(tree_array_length > 0), 'error: some caption had no trees?'
print('encoded captions to array of size ', L.shape)
return L, T, F, label_start_ix, label_end_ix, label_length, tree_array_length
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
# create the vocab
vocab = build_vocab(imgs, params)
# print(json.dumps(imgs[0], indent=2))
itow = {i+1:w for i,w in enumerate(vocab)} # a 1-indexed vocab translation table
wtoi = {w:i+1 for i,w in enumerate(vocab)} # inverse table
print(len(vocab))
# encode captions in large arrays, ready to ship to hdf5 file
L, T, F, label_start_ix, label_end_ix, label_length, tree_array_length = encode_captions(imgs, params, wtoi)
# create output h5 file
N = len(imgs)
f_lb = h5py.File(params['output_h5']+'_label.h5', "w")
f_lb.create_dataset("labels", dtype='int32', data=L)
f_lb.create_dataset("treearray", dtype='int32', data=T)
f_lb.create_dataset("treearray_idx", dtype='int32', data=F)
f_lb.create_dataset("label_start_ix", dtype='int32', data=label_start_ix)
f_lb.create_dataset("label_end_ix", dtype='int32', data=label_end_ix)
f_lb.create_dataset("label_length", dtype='int32', data=label_length)
f_lb.create_dataset("treearray_length", dtype='int32', data=tree_array_length)
f_lb.close()
# create output json file
out = {}
out['ix_to_word'] = itow # encode the (1-indexed) vocab
out['images'] = []
for i,img in enumerate(imgs):
jimg = {}
jimg['split'] = 'train'
jimg['id'] = img['img_id']
if 'filename' in img:
jimg['file_path'] = os.path.join(img.get('filepath', ''), img['filename'])
out['images'].append(jimg)
json.dump(out, open(params['output_json'], 'w'))
print('wrote ', params['output_json'])
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# input_json
parser.add_argument('--input_json', required=True, help='input json file to process into hdf5')
parser.add_argument('--output_h5', default='dataset/cocotree', help='output h5 file')
parser.add_argument('--output_json', default='dataset/cocotree.json', help='output json file')
# options
parser.add_argument('--max_length', default=16, type=int, help='max length of a caption, in number of words. captions longer than this get clipped.')
parser.add_argument('--word_count_threshold', default=5, type=int, help='only words that occur more than this number of times will be put in vocab')
parser.add_argument('--max_treearray_length', default=40, type=int, help='max length of the vector representing a tree')
args = parser.parse_args()
params = vars(args)
print('parsed input parameters:')
print(json.dumps(params, indent = 2))
start_time = time.time()
main(params)
print("Finish, takes {} seconds.".format(time.time() - start_time))
|
{"hexsha": "87850bd07ffd68e886e742f68f15308300a960a6", "size": 8284, "ext": "py", "lang": "Python", "max_stars_repo_path": "scripts/prepro_tree_labels.py", "max_stars_repo_name": "mazm13/Image-to-Tree.pytorch", "max_stars_repo_head_hexsha": "1d32e31d489ea6be784dbbe173acc362b82c59dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/prepro_tree_labels.py", "max_issues_repo_name": "mazm13/Image-to-Tree.pytorch", "max_issues_repo_head_hexsha": "1d32e31d489ea6be784dbbe173acc362b82c59dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/prepro_tree_labels.py", "max_forks_repo_name": "mazm13/Image-to-Tree.pytorch", "max_forks_repo_head_hexsha": "1d32e31d489ea6be784dbbe173acc362b82c59dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6545454545, "max_line_length": 153, "alphanum_fraction": 0.620593916, "include": true, "reason": "import numpy", "num_tokens": 2198}
|
#pragma once
#include <nano/lib/utility.hpp>
#include <nano/node/common.hpp>
#include <nano/secure/common.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index_container.hpp>
#include <functional>
#include <memory>
namespace mi = boost::multi_index;
namespace nano
{
class network;
class stat;
class ledger;
class thread_pool;
namespace transport
{
class channel;
}
/*
* Holds a response from a telemetry request
*/
class telemetry_data_response
{
public:
nano::telemetry_data telemetry_data;
nano::endpoint endpoint;
bool error{ true };
};
class telemetry_info final
{
public:
telemetry_info () = default;
telemetry_info (nano::endpoint const & endpoint, nano::telemetry_data const & data, std::chrono::steady_clock::time_point last_response, bool undergoing_request);
bool awaiting_first_response () const;
nano::endpoint endpoint;
nano::telemetry_data data;
std::chrono::steady_clock::time_point last_response;
bool undergoing_request{ false };
uint64_t round{ 0 };
};
/*
* This class requests node telemetry metrics from peers and invokes any callbacks which have been aggregated.
* All calls to get_metrics return cached data, it does not do any requests, these are periodically done in
* ongoing_req_all_peers. This can be disabled with the disable_ongoing_telemetry_requests node flag.
* Calls to get_metrics_single_peer_async will wait until a response is made if it is not within the cache
* cut off.
*/
class telemetry : public std::enable_shared_from_this<telemetry>
{
public:
telemetry (nano::network &, nano::thread_pool &, nano::observer_set<nano::telemetry_data const &, nano::endpoint const &> &, nano::stat &, nano::network_params &, bool);
void start ();
void stop ();
/*
* Received telemetry metrics from this peer
*/
void set (nano::telemetry_ack const &, nano::transport::channel const &);
/*
* This returns what ever is in the cache
*/
std::unordered_map<nano::endpoint, nano::telemetry_data> get_metrics ();
/*
* This makes a telemetry request to the specific channel.
* Error is set for: no response received, no payload received, invalid signature or unsound metrics in message (e.g different genesis block)
*/
void get_metrics_single_peer_async (std::shared_ptr<nano::transport::channel> const &, std::function<void (telemetry_data_response const &)> const &);
/*
* A blocking version of get_metrics_single_peer_async
*/
telemetry_data_response get_metrics_single_peer (std::shared_ptr<nano::transport::channel> const &);
/*
* Return the number of node metrics collected
*/
std::size_t telemetry_data_size ();
/*
* Returns the time for the cache, response and a small buffer for alarm operations to be scheduled and completed
*/
std::chrono::milliseconds cache_plus_buffer_cutoff_time () const;
private:
class tag_endpoint
{
};
class tag_last_updated
{
};
nano::network & network;
nano::thread_pool & workers;
nano::observer_set<nano::telemetry_data const &, nano::endpoint const &> & observers;
nano::stat & stats;
/* Important that this is a reference to the node network_params for tests which want to modify genesis block */
nano::network_params & network_params;
bool disable_ongoing_requests;
std::atomic<bool> stopped{ false };
nano::mutex mutex{ mutex_identifier (mutexes::telemetry) };
// clang-format off
// This holds the last telemetry data received from peers or can be a placeholder awaiting the first response (check with awaiting_first_response ())
boost::multi_index_container<nano::telemetry_info,
mi::indexed_by<
mi::hashed_unique<mi::tag<tag_endpoint>,
mi::member<nano::telemetry_info, nano::endpoint, &nano::telemetry_info::endpoint>>,
mi::ordered_non_unique<mi::tag<tag_last_updated>,
mi::member<nano::telemetry_info, std::chrono::steady_clock::time_point, &nano::telemetry_info::last_response>>>> recent_or_initial_request_telemetry_data;
// clang-format on
// Anything older than this requires requesting metrics from other nodes.
std::chrono::seconds const cache_cutoff{ nano::telemetry_cache_cutoffs::network_to_time (network_params.network) };
// The maximum time spent waiting for a response to a telemetry request
std::chrono::seconds const response_time_cutoff{ network_params.network.is_dev_network () ? (is_sanitizer_build || nano::running_within_valgrind () ? 6 : 3) : 10 };
std::unordered_map<nano::endpoint, std::vector<std::function<void (telemetry_data_response const &)>>> callbacks;
void ongoing_req_all_peers (std::chrono::milliseconds);
void fire_request_message (std::shared_ptr<nano::transport::channel> const &);
void channel_processed (nano::endpoint const &, bool);
void flush_callbacks_async (nano::endpoint const &, bool);
void invoke_callbacks (nano::endpoint const &, bool);
bool within_cache_cutoff (nano::telemetry_info const &) const;
bool within_cache_plus_buffer_cutoff (telemetry_info const &) const;
bool verify_message (nano::telemetry_ack const &, nano::transport::channel const &);
friend std::unique_ptr<nano::container_info_component> collect_container_info (telemetry &, std::string const &);
friend class telemetry_remove_peer_invalid_signature_Test;
};
std::unique_ptr<nano::container_info_component> collect_container_info (telemetry & telemetry, std::string const & name);
nano::telemetry_data consolidate_telemetry_data (std::vector<telemetry_data> const & telemetry_data);
nano::telemetry_data local_telemetry_data (nano::ledger const & ledger_a, nano::network &, uint64_t, nano::network_params const &, std::chrono::steady_clock::time_point, uint64_t, nano::keypair const &);
}
|
{"hexsha": "cd902cac40cebfeb420f3f2795ddf4b6ca9aac84", "size": 5720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nano/node/telemetry.hpp", "max_stars_repo_name": "Sukhmai/nano-node", "max_stars_repo_head_hexsha": "d4b3e5473ed85366edbd91aebc698ccc28e018fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-11-24T19:02:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T08:24:35.000Z", "max_issues_repo_path": "nano/node/telemetry.hpp", "max_issues_repo_name": "Sukhmai/nano-node", "max_issues_repo_head_hexsha": "d4b3e5473ed85366edbd91aebc698ccc28e018fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-05T03:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-05T03:59:09.000Z", "max_forks_repo_path": "nano/node/telemetry.hpp", "max_forks_repo_name": "Sukhmai/nano-node", "max_forks_repo_head_hexsha": "d4b3e5473ed85366edbd91aebc698ccc28e018fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-06T03:02:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T03:02:40.000Z", "avg_line_length": 37.1428571429, "max_line_length": 203, "alphanum_fraction": 0.7667832168, "num_tokens": 1305}
|
# -------------------------------------------------------------------
# Data Exploration
# -------------------------------------------------------------------
# Creates plots of steering angles by consecutive timestamps
from __future__ import print_function
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
from pylab import *
from config import StatsConfig
config = StatsConfig()
data_path = config.data_path
def plotFeatures(data):
# Plot all the time sections of steering data
j = 0 # Rotating Color
k = 0 # Rotating Marker
jj = 0 # Subplot Number
timebreak = [0] # Store indices of timebreaks
start = 0
c = ['r','b','g','k','m','y','c']
marker = ['.','o','x','+','*','s','d']
for i in range(1,data.shape[0]):
if data[i,0] != data[i-1,0] and data[i,0] != (data[i-1,0] + 1):
timebreak.append(int(data[i-1,0]))
if jj < 70:
jj = jj + 1
print(jj)
plt.subplot(4,1,jj)
plt.plot(data[start:i-1,0],data[start:i-1,1],c=c[j],marker=marker[k])
start = i
j = j + 1
if jj == 69:
plt.subplot(7,10,jj+1)
plt.plot(data[start:-1,0],data[start:-1,1],c=c[j],marker=marker[k])
if j == 6:
j = 0
k = 0 #k = k + 1
if k == 7:
k = 0
for i in range (1,5):
plt.subplot(4,1,i)
plt.xlabel('TimeStamp')
plt.ylabel('Steering Angle')
plt.grid(True)
plt.suptitle('Consecutive Timestamp Steering')
plt.subplots_adjust(left=0.05,bottom=0.05,right=0.95,top=0.95,wspace=0.4,hspace=0.25)
fig = plt.gcf()
fig.set_size_inches(30, 15)
fig.savefig('Steering.png', dpi=200)
# Main Program
def main():
# Stats on steering data
df_steer = pd.read_csv(data_path,usecols=['timestamp','angle'],index_col = False)
u_A = str(len(list(set(df_steer['angle'].values.tolist()))))
counts_A = df_steer['angle'].value_counts()
# Mod the timestamp data
time_factor = 10
time_scale = int(1e9) / time_factor
df_steer['time_mod'] = df_steer['timestamp'].astype(int) / time_scale
u_T = str(len(list(set(df_steer['time_mod'].astype(int).values.tolist()))))
# Some stats on steering angles/timestamps
print('Number of unique steering angles...')
print (u_A,df_steer.shape)
print('Number of unique timestamps...')
print (u_T,df_steer.shape)
np.set_printoptions(suppress=False)
counts_A.to_csv('counts.csv')
df_steer['time_mod'].astype(int).to_csv('timestamps.csv',index=False)
# Plot the steering data
angle = np.zeros((df_steer.shape[0],1))
time = np.zeros((df_steer.shape[0],1))
angle[:,0] = df_steer['angle'].values
time[:,0] = df_steer['time_mod'].values.astype(int)
data = np.append(time,angle,axis=1)
plotFeatures(data)
if __name__ == '__main__':
main()
config = StatsConfig()
data_path = config.data_path
|
{"hexsha": "b254609872fb1c91cec9e1da989f3b2eb3512c37", "size": 3088, "ext": "py", "lang": "Python", "max_stars_repo_path": "datacurve.py", "max_stars_repo_name": "shahidul56/CNN_Steering_Angle", "max_stars_repo_head_hexsha": "a2f8b19e936cc0436469e61fc72e30d93f7f1fee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-14T07:07:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T07:07:59.000Z", "max_issues_repo_path": "datacurve.py", "max_issues_repo_name": "shahidul56/CNN_Steering_Angle", "max_issues_repo_head_hexsha": "a2f8b19e936cc0436469e61fc72e30d93f7f1fee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "datacurve.py", "max_forks_repo_name": "shahidul56/CNN_Steering_Angle", "max_forks_repo_head_hexsha": "a2f8b19e936cc0436469e61fc72e30d93f7f1fee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8350515464, "max_line_length": 89, "alphanum_fraction": 0.557642487, "include": true, "reason": "import numpy", "num_tokens": 843}
|
#include "leela_zero.h"
#include "log_file.h"
#include "exit_status.h"
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#ifdef WIN32
#include <boost/process/windows.hpp>
#endif
static const boost::regex reFirstLine(R"(Using \d++ thread\(s\)\..*+)");
LeelaZero::LeelaZero(const String& lz, const String& networkWeights, int nThreads, std::atomic<bool>& ss)
: shouldStop(ss)
{
if (!boost::filesystem::exists(lz)
|| !boost::filesystem::exists(networkWeights)) {
throw ExitStatus::FAILED;
}
// networkWeightsのファイルサイズが公開されている0番のファイルより小さいならば
// 確実にパスを間違えている
bool tooSmall = false;
try {
if (boost::filesystem::file_size(networkWeights) < 1373631U) {
tooSmall = true;
}
} catch (...) {
throw ExitStatus::FAILED;
}
if (tooSmall) {
throw ExitStatus::FAILED;
}
String t = ToString(std::to_string(nThreads));
String command = ToString("\"") + lz
+ ToString("\" -g -w \"") + networkWeights
+ ToString("\" -r 0 -t ") + t
+ ToString(" --noponder");
Log("<Command>");
Log(ToUtf8String(command));
Log("");
child = new boost::process::child(
command,
boost::process::std_in < ops,
boost::process::std_out > ips,
boost::process::std_err > eps
#ifdef WIN32
, boost::process::windows::hide
#endif
);
if (!child->running()) {
delete child;
throw ExitStatus::FAILED;
}
// 設定に間違ったプログラムのパスが書かれているときに
// このプログラムがフリーズしないようにする
// その間違って設定されたプログラムが--noponder等の不明なオプションから
// 何らかのエラーメッセージを出力することを期待して
// 標準エラー出力の最初の一行を読んでLeela Zeroか判定する
Log("<Information>");
const auto firstLine = getLine();
if (!boost::regex_match(firstLine, reFirstLine)) {
throw ExitStatus::FAILED;
}
// ログが読みにくくなるので起動時の出力はすべて読んでおく
getLine("Setting");
Log("");
}
LeelaZero::~LeelaZero()
{
delete child;
}
std::string LeelaZero::getLine()
{
if (shouldStop.load()) {
throw ExitStatus::CANCELED;
}
std::string line;
if (eps && std::getline(eps, line)) {
Trim(line, '\r');
Log(line);
return line;
}
return std::string();
}
std::string LeelaZero::getLine(const std::string& s)
{
std::string line;
while (eps) {
line = getLine();
if (s.empty() || line.substr(0U, s.length()) == s) {
return line;
}
}
return std::string();
}
std::string LeelaZero::getResult()
{
if (shouldStop.load()) {
throw ExitStatus::CANCELED;
}
std::string line;
std::ostringstream result;
while (ips && std::getline(ips, line) && !line.empty() && line.front() != '\r') {
Trim(line, '\r');
Log(line);
result << line << '\n';
}
Log("");
return result.str();
}
void LeelaZero::send(const std::string& gtpCommand)
{
if (ops) {
Log(gtpCommand);
ops << gtpCommand << std::endl;
}
}
|
{"hexsha": "9c315234bc7e52d3c1e00438c88017b520307ecb", "size": 2757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/leela_zero.cpp", "max_stars_repo_name": "wentaol/zero-problem", "max_stars_repo_head_hexsha": "887e61826225137b5c7e40feea8ae932bdcf333b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T01:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T00:58:12.000Z", "max_issues_repo_path": "src/leela_zero.cpp", "max_issues_repo_name": "wentaol/zero-problem", "max_issues_repo_head_hexsha": "887e61826225137b5c7e40feea8ae932bdcf333b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/leela_zero.cpp", "max_forks_repo_name": "wentaol/zero-problem", "max_forks_repo_head_hexsha": "887e61826225137b5c7e40feea8ae932bdcf333b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T00:12:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-11T00:12:25.000Z", "avg_line_length": 21.2076923077, "max_line_length": 106, "alphanum_fraction": 0.6256800871, "num_tokens": 915}
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
"""
tf2onnx.utils - misc utilities for tf2onnx
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import re
import six
import numpy as np
import tensorflow as tf
from tensorflow.core.framework import types_pb2, tensor_pb2
from google.protobuf import text_format
from onnx import helper, onnx_pb, defs, numpy_helper
#
# mapping dtypes from tensorflow to onnx
#
TF_TO_ONNX_DTYPE = {
types_pb2.DT_FLOAT: onnx_pb.TensorProto.FLOAT,
types_pb2.DT_HALF: onnx_pb.TensorProto.FLOAT16,
types_pb2.DT_DOUBLE: onnx_pb.TensorProto.DOUBLE,
types_pb2.DT_INT32: onnx_pb.TensorProto.INT32,
types_pb2.DT_INT16: onnx_pb.TensorProto.INT16,
types_pb2.DT_INT8: onnx_pb.TensorProto.INT8,
types_pb2.DT_UINT8: onnx_pb.TensorProto.UINT8,
types_pb2.DT_UINT16: onnx_pb.TensorProto.UINT16,
types_pb2.DT_INT64: onnx_pb.TensorProto.INT64,
types_pb2.DT_STRING: onnx_pb.TensorProto.STRING,
types_pb2.DT_COMPLEX64: onnx_pb.TensorProto.COMPLEX64,
types_pb2.DT_COMPLEX128: onnx_pb.TensorProto.COMPLEX128,
types_pb2.DT_BOOL: onnx_pb.TensorProto.BOOL,
types_pb2.DT_RESOURCE: onnx_pb.TensorProto.INT64, # TODO: hack to allow processing on control flow
types_pb2.DT_QUINT8: onnx_pb.TensorProto.UINT8, # TODO: map quint8 to uint8 for now
}
#
# mapping dtypes from onnx to numpy
#
ONNX_TO_NUMPY_DTYPE = {
onnx_pb.TensorProto.FLOAT: np.float32,
onnx_pb.TensorProto.FLOAT16: np.float16,
onnx_pb.TensorProto.DOUBLE: np.float64,
onnx_pb.TensorProto.INT32: np.int32,
onnx_pb.TensorProto.INT16: np.int16,
onnx_pb.TensorProto.INT8: np.int8,
onnx_pb.TensorProto.UINT8: np.uint8,
onnx_pb.TensorProto.UINT16: np.uint16,
onnx_pb.TensorProto.INT64: np.int64,
onnx_pb.TensorProto.BOOL: np.bool,
}
#
# onnx dtype names
#
ONNX_DTYPE_NAMES = {
onnx_pb.TensorProto.FLOAT: "float",
onnx_pb.TensorProto.FLOAT16: "float16",
onnx_pb.TensorProto.DOUBLE: "double",
onnx_pb.TensorProto.INT32: "int32",
onnx_pb.TensorProto.INT16: "int16",
onnx_pb.TensorProto.INT8: "int8",
onnx_pb.TensorProto.UINT8: "uint8",
onnx_pb.TensorProto.UINT16: "uint16",
onnx_pb.TensorProto.INT64: "int64",
onnx_pb.TensorProto.STRING: "string",
onnx_pb.TensorProto.BOOL: "bool"
}
ONNX_UNKNOWN_DIMENSION = -1
#
# attributes onnx understands. Everything else coming from tensorflow
# will be ignored.
#
ONNX_VALID_ATTRIBUTES = {
'p', 'bias', 'axes', 'pads', 'mean', 'activation_beta', 'spatial_scale', 'broadcast', 'pooled_shape', 'high',
'activation_alpha', 'is_test', 'hidden_size', 'activations', 'beta', 'input_as_shape', 'drop_states', 'alpha',
'momentum', 'scale', 'axis', 'dilations', 'transB', 'axis_w', 'blocksize', 'output_sequence', 'mode', 'perm',
'min', 'seed', 'ends', 'paddings', 'to', 'gamma', 'width_scale', 'normalize_variance', 'group', 'ratio', 'values',
'dtype', 'output_shape', 'spatial', 'split', 'input_forget', 'keepdims', 'transA', 'auto_pad', 'border', 'low',
'linear_before_reset', 'height_scale', 'output_padding', 'shape', 'kernel_shape', 'epsilon', 'size', 'starts',
'direction', 'max', 'clip', 'across_channels', 'value', 'strides', 'extra_shape', 'scales', 'k', 'sample_size',
'blocksize', 'epsilon', 'momentum', 'body', 'directions', 'num_scan_inputs', 'then_branch', 'else_branch'
}
# index for internally generated names
INTERNAL_NAME = 1
# Fake onnx op type which is used for Graph input.
GRAPH_INPUT_TYPE = "NON_EXISTENT_ONNX_TYPE"
def make_name(name):
"""Make op name for inserted ops."""
global INTERNAL_NAME
INTERNAL_NAME += 1
return "{}__{}".format(name, INTERNAL_NAME)
def split_nodename_and_shape(name):
"""input name with shape into name and shape."""
# pattern for a node name
inputs = []
shapes = {}
# input takes in most cases the format name:0, where 0 is the output number
# in some cases placeholders don't have a rank which onnx can't handle so we let uses override the shape
# by appending the same, ie : [1,28,28,3]
name_pattern = r"(?:([\w\d/\-\._:]+)(\[[\-\d,]+\])?),?"
splits = re.split(name_pattern, name)
for i in range(1, len(splits), 3):
inputs.append(splits[i])
if splits[i + 1] is not None:
shapes[splits[i]] = [int(n) for n in splits[i + 1][1:-1].split(",")]
if not shapes:
shapes = None
return inputs, shapes
def tf_to_onnx_tensor(tensor, name=""):
"""Convert tensorflow tensor to onnx tensor."""
new_type = TF_TO_ONNX_DTYPE[tensor.dtype]
tdim = tensor.tensor_shape.dim
dims = [d.size for d in tdim]
# FIXME: something is fishy here
if dims == [0]:
dims = [1]
is_raw, data = get_tf_tensor_data(tensor)
if not is_raw and len(data) == 1 and np.prod(dims) > 1:
batch_data = np.zeros(dims, dtype=ONNX_TO_NUMPY_DTYPE[new_type])
batch_data.fill(data[0])
onnx_tensor = numpy_helper.from_array(batch_data, name=name)
else:
onnx_tensor = helper.make_tensor(name, new_type, dims, data, is_raw)
return onnx_tensor
def get_tf_tensor_data(tensor):
"""Get data from tensor."""
assert isinstance(tensor, tensor_pb2.TensorProto)
is_raw = False
if tensor.tensor_content:
data = tensor.tensor_content
is_raw = True
elif tensor.float_val:
data = tensor.float_val
elif tensor.dcomplex_val:
data = tensor.dcomplex_val
elif tensor.int_val:
data = tensor.int_val
elif tensor.int64_val:
data = tensor.int64_val
elif tensor.bool_val:
data = tensor.bool_val
elif tensor.dtype == tf.int32:
data = [0]
elif tensor.dtype == tf.int64:
data = [0]
elif tensor.dtype == tf.float32:
data = [0.]
elif tensor.dtype == tf.float16:
data = [0]
elif tensor.string_val:
data = tensor.string_val
else:
raise ValueError('tensor data not supported')
return [is_raw, data]
def get_shape(node):
"""Get shape from tensorflow node."""
# FIXME: do we use this?
dims = None
try:
if node.type == "Const":
shape = get_tf_node_attr(node, "value").tensor_shape
dims = [int(d.size) for d in shape.dim]
else:
shape = get_tf_node_attr(node, "shape")
dims = [d.size for d in shape.dim]
except: # pylint: disable=bare-except
pass
return dims
def map_tf_dtype(dtype):
if dtype:
dtype = TF_TO_ONNX_DTYPE[dtype]
return dtype
def map_numpy_to_onnx_dtype(np_dtype):
for onnx_dtype, numpy_dtype in ONNX_TO_NUMPY_DTYPE.items():
if numpy_dtype == np_dtype:
return onnx_dtype
raise ValueError("unsupported dtype " + np_dtype + " for mapping")
def node_name(name):
"""Get node name without io#."""
pos = name.find(":")
if pos >= 0:
return name[:pos]
return name
def make_onnx_shape(shape):
"""shape with -1 is not valid in onnx ... make it a name."""
if shape:
# don't do this if input is a scalar
return [make_name("unk") if i == -1 else i for i in shape]
return shape
def port_name(name, nr=0):
"""Map node output number to name."""
return name + ":" + str(nr)
def make_onnx_identity(node_input, node_output, name=None):
if name is None:
name = make_name("identity")
return helper.make_node("Identity", [node_input], [node_output], name=name)
def make_onnx_inputs_outputs(name, elem_type, shape, **kwargs):
"""Wrapper for creating onnx graph inputs or outputs
name, # type: Text
elem_type, # type: TensorProto.DataType
shape, # type: Optional[Sequence[int]]
"""
return helper.make_tensor_value_info(name, elem_type, make_onnx_shape(shape), **kwargs)
PREFERRED_OPSET = 7
def find_opset(opset):
"""Find opset."""
if opset is None or opset == 0:
opset = defs.onnx_opset_version()
if opset > PREFERRED_OPSET:
# if we use a newer onnx opset than most runtimes support, default to the one most supported
opset = PREFERRED_OPSET
return opset
def get_tf_node_attr(node, name):
"""Parser TF node attribute."""
if six.PY2:
# For python2, TF get_attr does not accept unicode
name = str(name)
return node.get_attr(name)
def save_onnx_model(save_path_root, onnx_file_name, feed_dict, model_proto, include_test_data=False, as_text=False):
"""Save onnx model as file. Save a pbtxt file as well if as_text is True"""
save_path = save_path_root
if not os.path.exists(save_path):
os.makedirs(save_path)
if include_test_data:
data_path = os.path.join(save_path, "test_data_set_0")
if not os.path.exists(data_path):
os.makedirs(data_path)
i = 0
for data_key in feed_dict:
data = feed_dict[data_key]
t = numpy_helper.from_array(data)
t.name = data_key
data_full_path = os.path.join(data_path, "input_" + str(i) + ".pb")
with open(data_full_path, 'wb') as f:
f.write(t.SerializeToString())
i += 1
target_path = os.path.join(save_path, onnx_file_name + ".onnx")
with open(target_path, "wb") as f:
f.write(model_proto.SerializeToString())
if as_text:
with open(target_path + ".pbtxt", "w") as f:
f.write(text_format.MessageToString(model_proto))
return target_path
def make_sure(bool_val, error_msg, *args):
if not bool_val:
raise ValueError("make_sure failure: " + error_msg % args)
def construct_graph_from_nodes(parent_g, nodes, outputs, shapes, dtypes):
"""Construct Graph from nodes and outputs with specified shapes and dtypes."""
# pylint: disable=protected-access
g = parent_g.create_new_graph_with_same_config()
g.parent_graph = parent_g
nodes = set(nodes)
all_outputs = set()
ops = []
for op in nodes:
all_outputs |= set(op.output)
new_node = g.make_node(op.type, op.input, outputs=op.output, attr=op.attr, name=op.name,
skip_conversion=op._skip_conversion)
body_graphs = op.graph.contained_graphs.pop(op.name, None)
if body_graphs:
for attr_name, body_graph in body_graphs.items():
body_graph.parent_graph = g
new_node.set_body_graph_as_attr(attr_name, body_graph)
ops.append(new_node)
for i in all_outputs:
if i not in g._output_shapes:
g._output_shapes[i] = parent_g._output_shapes[i]
if i not in g._dtypes:
g._dtypes[i] = parent_g._dtypes[i]
g.set_nodes(ops)
# handle cell graph: insert identity node, since sometimes we need output same output_id
# as state_output and scan_out, but ONNX don't allow the same output_id to appear more
# than once as output node.
cell_body_nodes = []
new_output_names = []
for output, shape, dtype in zip(outputs, shapes, dtypes):
node = g.make_node("Identity", inputs=[output], op_name_scope="sub_graph_ending_node",
shapes=[shape], dtypes=[dtype])
new_output_names.append(node.output[0])
cell_body_nodes.append(node)
cell_nodes = g.get_nodes()
cell_nodes.extend(cell_body_nodes)
g.set_nodes(cell_nodes)
g.outputs = new_output_names
return g
def tf_name_scope(name):
return '/'.join(name.split('/')[:-1])
def create_vague_shape_like(shape):
make_sure(len(shape) >= 0, "rank should be >= 0")
return [-1 for i in enumerate(shape)]
|
{"hexsha": "0ec3f6bf6b8606aba5b5993c16ed6f721f3c1b2b", "size": 11759, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf2onnx/utils.py", "max_stars_repo_name": "kadeng/tensorflow-onnx", "max_stars_repo_head_hexsha": "db91f5b25cc2a053f46af3b2c04b65a679cff03b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tf2onnx/utils.py", "max_issues_repo_name": "kadeng/tensorflow-onnx", "max_issues_repo_head_hexsha": "db91f5b25cc2a053f46af3b2c04b65a679cff03b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tf2onnx/utils.py", "max_forks_repo_name": "kadeng/tensorflow-onnx", "max_forks_repo_head_hexsha": "db91f5b25cc2a053f46af3b2c04b65a679cff03b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5971428571, "max_line_length": 118, "alphanum_fraction": 0.6645122885, "include": true, "reason": "import numpy", "num_tokens": 3107}
|
program test_bit
use lfortran_intrinsic_bit, only: iand, ior, ibclr, ibset, btest
implicit none
integer(kind=4) :: a
integer(kind=4) :: b
integer(kind=8) :: x
integer(kind=8) :: y
a = 4
b = 1
if (iand(a, b) /= 0) error stop
x = 3
y = 1
if (iand(x, y) /= 1) error stop
a = 1
b = 2
if (ior(a, b) /= 3) error stop
x = 2
y = 3
if (ior(x, y) /= 3) error stop
a = 1
if (ibclr(a, 0) /= 0) error stop
if (ibset(a, 2) /= 5) error stop
x = 2
if (ibclr(x, 1) /= 0) error stop
if (ibset(x, 3) /= 10) error stop
a = 2
if (btest(a, 0)) error stop
x = 4
if (btest(x, 0)) error stop
end program
|
{"hexsha": "8748ba9bc9fa272acb402d737e750a432e4b89d4", "size": 590, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "src/runtime/tests/test_bit.f90", "max_stars_repo_name": "Thirumalai-Shaktivel/lfortran", "max_stars_repo_head_hexsha": "bb39faf1094b028351d5aefe27d64ee69302300a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 316, "max_stars_repo_stars_event_min_datetime": "2019-03-24T16:23:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:28:33.000Z", "max_issues_repo_path": "src/runtime/tests/test_bit.f90", "max_issues_repo_name": "Thirumalai-Shaktivel/lfortran", "max_issues_repo_head_hexsha": "bb39faf1094b028351d5aefe27d64ee69302300a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-07-29T04:58:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T16:40:06.000Z", "max_forks_repo_path": "src/runtime/tests/test_bit.f90", "max_forks_repo_name": "Thirumalai-Shaktivel/lfortran", "max_forks_repo_head_hexsha": "bb39faf1094b028351d5aefe27d64ee69302300a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2019-03-28T19:40:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:28:55.000Z", "avg_line_length": 14.0476190476, "max_line_length": 64, "alphanum_fraction": 0.5881355932, "num_tokens": 273}
|
import hdnntools as hdt
import nmstools as nmt
import pyanitools as pyt
import pyaniasetools as aat
import pyanitrainer as atr
import pymolfrag as pmf
from pyNeuroChem import cachegenerator as cg
import numpy as np
from time import sleep
import subprocess
import random
#import pyssh
import re
import os
import pyaniasetools as aat
from multiprocessing import Process
import shutil
import matplotlib.pyplot as plt
class alconformationalsampler():
# Constructor
def __init__(self, ldtdir, datdir, optlfile, fpatoms, netdict):
self.ldtdir = ldtdir # local working dir
self.datdir = datdir # working data dir
self.cdir = ldtdir+datdir+'/confs/' # confs store dir (the data gen code looks here for conformations to run QM on)
self.fpatoms = fpatoms # atomic species being sampled
self.optlfile = optlfile # Optimized molecules store path file
self.idir = [f for f in open(optlfile).read().split('\n') if f != ''] # read and store the paths to the opt files
# create cdir if it does not exist
if not os.path.exists(self.cdir):
os.mkdir(self.cdir)
# store network parameters dictionary
self.netdict = netdict
# Runs NMS sampling (single GPU only currently)
def run_sampling_nms(self, nmsparams, gpus=[0]):
print('Running NMS sampling...')
p = Process(target=self.normal_mode_sampling, args=(nmsparams['T'],
nmsparams['Ngen'],
nmsparams['Nkep'],
nmsparams['maxd'],
nmsparams['sig'],
gpus[0]))
p.start()
p.join()
# Run MD sampling on N GPUs. This code will automatically run 2 mds per GPU for better utilization
def run_sampling_md(self, mdparams, perc=1.0, gpus=[0]):
md_work = []
for di, id in enumerate(self.idir):
files = os.listdir(id)
for f in files:
if len(f) > 4:
if ".ipt" in f[-4:]:
md_work.append(id+f)
else:
print('Incorrect extension:',id+f)
gpus2 = gpus
md_work = np.array(md_work)
np.random.shuffle(md_work)
md_work = md_work[0:int(perc*md_work.size)]
md_work = np.array_split(md_work,len(gpus2))
proc = []
for i,(md,g) in enumerate(zip(md_work,gpus2)):
proc.append(Process(target=self.mol_dyn_sampling, args=(md,i,
mdparams['N'],
mdparams['T1'],
mdparams['T2'],
mdparams['dt'],
mdparams['Nc'],
mdparams['Ns'],
mdparams['sig'],
g)))
print('Running MD Sampling...')
for i,p in enumerate(proc):
p.start()
for p in proc:
p.join()
print('Finished sampling.')
# Run the dimer sampling code on N gpus
def run_sampling_dimer(self, dmparams, gpus=[0]):
proc = []
for i,g in enumerate(gpus):
proc.append(Process(target=self.dimer_sampling, args=(i, int(dmparams['Nr']/len(gpus)),
dmparams,
g)))
print('Running Dimer-MD Sampling...')
for i,p in enumerate(proc):
p.start()
for p in proc:
p.join()
print('Finished sampling.')
# Run cluster sampling on N gpus
def run_sampling_cluster(self, gcmddict, gpus=[0]):
Nmols = np.random.randint(low=gcmddict['MolLow'],
high=gcmddict['MolHigh'],
size=gcmddict['Nr'])
Ntmps = np.random.randint(low=gcmddict['T']-200,
high=gcmddict['T']+200,
size=gcmddict['Nr'])
print('Box Sizes:',Nmols)
print('Sim Temps:',Ntmps)
seeds = np.random.randint(0,1000000,len(gpus))
mol_sizes = np.array_split(Nmols, len(gpus))
mol_temps = np.array_split(Ntmps, len(gpus))
proc = []
for i,g in enumerate(gpus):
proc.append(Process(target=self.cluster_sampling, args=(i, int(gcmddict['Nr']/len(gpus)),
mol_sizes[i],
mol_temps[i],
seeds[i],
gcmddict,
g)))
print('Running Cluster-MD Sampling...')
for i,p in enumerate(proc):
p.start()
for p in proc:
p.join()
print('Finished sampling.')
# Normal mode sampler function
def normal_mode_sampling(self, T, Ngen, Nkep, maxd, sig, gpuid):
of = open(self.ldtdir + self.datdir + '/info_data_nms.nfo', 'w')
aevsize = self.netdict['aevsize']
anicv = aat.anicrossvalidationconformer(self.netdict['cnstfile'],
self.netdict['saefile'],
self.netdict['nnfprefix'],
self.netdict['num_nets'],
[gpuid], False)
dc = aat.diverseconformers(self.netdict['cnstfile'],
self.netdict['saefile'],
self.netdict['nnfprefix']+'0/networks/',
aevsize,
gpuid, False)
Nkp = 0
Nkt = 0
Ntt = 0
idx = 0
for di,id in enumerate(self.idir):
of.write(str(di)+' of '+str(len(self.idir))+') dir: '+ str(id) +'\n')
#print(di,'of',len(self.idir),') dir:', id)
files = os.listdir(id)
files.sort()
Nk = 0
Nt = 0
for fi,f in enumerate(files):
print(f)
data = hdt.read_rcdb_coordsandnm(id+f)
#print(id+f)
spc = data["species"]
xyz = data["coordinates"]
nmc = data["nmdisplacements"]
frc = data["forceconstant"]
if "charge" in data and "multip" in data:
chg = data["charge"]
mlt = data["multip"]
else:
chg = "0"
mlt = "1"
nms = nmt.nmsgenerator(xyz,nmc,frc,spc,T,minfc=5.0E-2,maxd=maxd)
conformers = nms.get_Nrandom_structures(Ngen)
if conformers.shape[0] > 0:
if conformers.shape[0] > Nkep:
ids = dc.get_divconfs_ids(conformers, spc, Ngen, Nkep, [])
conformers = conformers[ids]
sigma = anicv.compute_stddev_conformations(conformers,spc)
sid = np.where( sigma > sig )[0]
Nt += sigma.size
Nk += sid.size
if 100.0*sid.size/float(Ngen) > 0:
Nkp += sid.size
cfn = f.split('.')[0].split('-')[0]+'_'+str(idx).zfill(5)+'-'+f.split('.')[0].split('-')[1]+'_2.xyz'
cmts = [' '+chg+' '+mlt for c in range(Nk)]
hdt.writexyzfilewc(self.cdir+cfn,conformers[sid],spc,cmts)
idx += 1
Nkt += Nk
Ntt += Nt
of.write(' -Total: '+str(Nk)+' of '+str(Nt)+' percent: '+"{:.2f}".format(100.0*Nk/Nt)+'\n')
of.flush()
#print(' -Total:',Nk,'of',Nt,'percent:',"{:.2f}".format(100.0*Nk/Nt))
del anicv
del dc
of.write('\nGrand Total: '+ str(Nkt)+ ' of '+ str(Ntt)+' percent: '+"{:.2f}".format(100.0*Nkt/Ntt)+ ' Kept '+str(Nkp)+'\n')
#print('\nGrand Total:', Nkt, 'of', Ntt,'percent:',"{:.2f}".format(100.0*Nkt/Ntt), 'Kept',Nkp)
of.close()
# MD Sampling function
def mol_dyn_sampling(self,md_work, i, N, T1, T2, dt, Nc, Ns, sig, gpuid):
activ = aat.moldynactivelearning(self.netdict['cnstfile'],
self.netdict['saefile'],
self.netdict['nnfprefix'],
self.netdict['num_nets'],
gpuid)
difo = open(self.ldtdir + self.datdir + '/info_data_mdso-'+str(i)+'.nfo', 'w')
Nmol = 0
dnfo = 'MD Sampler running: ' + str(md_work.size)
difo.write(dnfo + '\n')
Nmol = md_work.size
ftme_t = 0.0
for di, id in enumerate(md_work):
data = hdt.read_rcdb_coordsandnm(id)
#print(di, ') Working on', id, '...')
S = data["species"]
# Set mols
activ.setmol(data["coordinates"], S)
# Generate conformations
X = activ.generate_conformations(N, T1, T2, dt, Nc, Ns, dS=sig)
ftme_t += activ.failtime
nfo = activ._infostr_
m = id.rsplit('/',1)[1].rsplit('.',1)[0]
difo.write(' -' + m + ': ' + nfo + '\n')
difo.flush()
#print(nfo)
if X.size > 0:
hdt.writexyzfile(self.cdir + 'mds_' + m.split('.')[0] + '_' + str(i).zfill(2) + str(di).zfill(4) + '.xyz', X, S)
difo.write('Complete mean fail time: ' + "{:.2f}".format(ftme_t / float(Nmol)) + '\n')
print(Nmol)
del activ
difo.close()
# Dimer sampling function
def dimer_sampling(self, tid, Nr, dparam, gpuid):
mds_select = dparam['mdselect']
#N = dparam['N']
T = dparam['T']
L = dparam['L']
V = dparam['V']
maxNa = dparam['maxNa']
dt = dparam['dt']
sig = dparam['sig']
Nm = dparam['Nm']
Ni = dparam['Ni']
Ns = dparam['Ns']
mols = []
difo = open(self.ldtdir + self.datdir + '/info_data_mddimer-'+str(tid)+'.nfo', 'w')
for di,id in enumerate(dparam['mdselect']):
files = os.listdir(self.idir[id[1]])
random.shuffle(files)
dnfo = str(di) + ' of ' + str(len(dparam['mdselect'])) + ') dir: ' + str(self.idir[id[1]]) + ' Selecting: '+str(id[0]*len(files))
#print(dnfo)
difo.write(dnfo+'\n')
for i in range(id[0]):
for n,m in enumerate(files):
data = hdt.read_rcdb_coordsandnm(self.idir[id[1]]+m)
if len(data['species']) < maxNa:
mols.append(data)
dgen = pmf.dimergenerator(self.netdict['cnstfile'],
self.netdict['saefile'],
self.netdict['nnfprefix'],
self.netdict['num_nets'],
mols, gpuid)
difo.write('Beginning dimer generation...\n')
Nt = 0
Nd = 0
for i in range(Nr):
dgen.init_dynamics(Nm, V, L, dt, T)
for j in range(Ns):
if j != 0:
dgen.run_dynamics(Ni)
fname = self.cdir + 'dimer-'+str(tid).zfill(2)+str(i).zfill(2)+'-'+str(j).zfill(2)+'_'
max_sig = dgen.__fragmentbox__(fname,sig)
print('MaxSig:',max_sig)
#difo.write('Step ('+str(i)+',',+str(j)+') ['+ str(dgen.Nd)+ '/'+ str(dgen.Nt)+']\n')
difo.write('Step ('+str(i)+','+str(j)+') ['+ str(dgen.Nd)+ '/'+ str(dgen.Nt)+'] max sigma: ' + "{:.2f}".format(max_sig) + ' generated '+str(len(dgen.frag_list))+' dimers...\n')
Nt += dgen.Nt
Nd += dgen.Nd
#print('Step (',tid,',',i,') [', str(dgen.Nd), '/', str(dgen.Nt),'] generated ',len(dgen.frag_list), 'dimers...')
#difo.write('Step ('+str(i)+') ['+ str(dgen.Nd)+ '/'+ str(dgen.Nt)+'] generated '+str(len(dgen.frag_list))+'dimers...\n')
if max_sig > 3.0*sig:
difo.write('Terminating dynamics -- max sigma: '+"{:.2f}".format(max_sig)+' Ran for: '+"{:.2f}".format(j*Ni*dt)+'fs\n')
break
difo.write('Generated '+str(Nd)+' of '+str(Nt)+' tested dimers. Percent: ' + "{:.2f}".format(100.0*Nd/float(Nt)))
difo.close()
# Cluster sampling function
def cluster_sampling(self, tid, Nr, mol_sizes, mol_temps, seed, gcmddict, gpuid):
os.environ["OMP_NUM_THREADS"] = "2"
dictc = gcmddict.copy()
solv_file = dictc['solv_file']
solu_dirs = dictc['solu_dirs']
np.random.seed(seed)
dictc['Nr'] = Nr
dictc['molfile'] = self.cdir + 'clst'
dictc['dstore'] = self.ldtdir + self.datdir + '/'
solv = [hdt.read_rcdb_coordsandnm(solv_file)]
if solu_dirs:
solu = [hdt.read_rcdb_coordsandnm(solu_dirs+f) for f in os.listdir(solu_dirs)]
else:
solu = []
dgen = pmf.clustergenerator(self.netdict['cnstfile'],
self.netdict['saefile'],
self.netdict['nnfprefix'],
self.netdict['num_nets'],
solv, solu, gpuid)
dgen.generate_clusters(dictc, mol_sizes, mol_temps, tid)
# Run the TS sampler
def run_sampling_TS(self, tsparams, gpus=[0], perc=1.0):
TS_infiles = []
for di, id in enumerate(tsparams['tsfiles']):
files = [fl for fl in os.listdir(id) if '.xyz' in fl]
for f in files:
TS_infiles.append(id+f)
gpus2 = gpus
TS_infiles = np.array(TS_infiles)
np.random.shuffle(TS_infiles)
TS_infiles = TS_infiles[0:int(perc*len(TS_infiles))]
TS_infiles = np.array_split(TS_infiles,len(gpus2))
proc = []
for i,g in enumerate(gpus2):
proc.append(Process(target=self.TS_sampling, args=(i, TS_infiles[i], tsparams, g)))
print('Running MD Sampling...')
for p in proc:
p.start()
for p in proc:
p.join()
print('Finished sampling.')
# TS sampler function
def TS_sampling(self, tid, TS_infiles, tsparams, gpuid):
activ = aat.MD_Sampler(TS_infiles,
self.netdict['cnstfile'],
self.netdict['saefile'],
self.netdict['nnfprefix'],
self.netdict['num_nets'],
gpuid)
T=tsparams['T']
sig=tsparams['sig']
Ns=tsparams['n_samples']
n_steps=tsparams['n_steps']
steps=tsparams['steps']
min_steps=tsparams['min_steps']
nm=tsparams['normalmode']
displacement=tsparams['displacement']
difo = open(self.ldtdir + self.datdir + '/info_tssampler-'+str(tid)+'.nfo', 'w')
for f in TS_infiles:
X = []
ftme_t = 0.0
fail_count=0
sumsig = 0.0
for i in range(Ns):
#x, S, t, stddev, fail, temp = activ.run_md(f, T, steps, n_steps, nmfile=f.rsplit(".",1)[0]+'.log', displacement=displacement, min_steps=min_steps, sig=sig, nm=nm)
x, S, t, stddev, fail, temp = activ.run_md(f, T, steps, n_steps, min_steps=min_steps, sig=sig, nm=nm)
sumsig += stddev
if fail:
#print('Job '+str(i)+' failed in '+"{:.2f}".format(t)+' Sigma: ' + "{:.2f}".format(stddev)+' SetTemp: '+"{:.2f}".format(temp))
difo.write('Job '+str(i)+' failed in '+"{:.2f}".format(t)+'fs Sigma: ' + "{:.2f}".format(stddev) + ' SetTemp: ' + "{:.2f}".format(temp) + '\n')
X.append(x[np.newaxis,:,:])
fail_count+=1
else:
#print('Job '+str(i)+' succeeded.')
difo.write('Job '+str(i)+' succeeded.\n')
ftme_t += t
print('Complete mean fail time: ' + "{:.2f}".format(ftme_t / float(Ns)) + ' failed ' + str(fail_count) + '/' + str(Ns) + '\n')
difo.write('Complete mean fail time: ' + "{:.2f}".format(ftme_t / float(Ns)) + ' failed ' + str(fail_count) + '/' + str(Ns) + ' MeanSig: ' + "{:.2f}".format(sumsig / float(Ns)) + '\n')
X = np.vstack(X)
hdt.writexyzfile(self.cdir + os.path.basename(f), X, S)
del activ
difo.close()
# Run the dihedral sampler
def run_sampling_dhl(self, dhlparams, gpus):
dhlparams['Nmol'] = int(np.ceil(dhlparams['Nmol']/len(gpus)))
seeds = np.random.randint(0,1000000,len(gpus))
proc = []
for i,g in enumerate(gpus):
proc.append(Process(target=self.DHL_sampling, args=(i, dhlparams, self.fpatoms, g, seeds[i])))
print('Running DHL Sampling...')
for p in proc:
p.start()
for p in proc:
p.join()
print('Finished sampling.')
# Dihedral sampling function
def DHL_sampling(self, i, dhlparams, fpatoms, gpuid, seed):
activ = aat.aniTortionSampler(self.netdict,
self.cdir,
dhlparams['smilefile'],
dhlparams['Nmol'],
dhlparams['Nsamp'],
dhlparams['sig'],
dhlparams['rng'],
fpatoms,
seed,
gpuid)
activ.generate_dhl_samples(MaxNa=dhlparams['MaxNa'], fpref='dhl_scan-'+str(i).zfill(2), freqname='vib'+str(i)+'.')
def run_sampling_pDynTS(self, pdynparams, gpus=0):
gpus2 = gpus
proc = []
for g in enumerate(gpus2):
proc.append(Process(target=self.pDyn_QMsampling, args=(pdynparams, g)))
print('Running pDynamo Sampling...')
for p in proc:
p.start()
for p in proc:
p.join()
print('Finished pDynamo sampling.')
def pDyn_QMsampling(self, pdynparams, gpuid):
#Call subproc_pDyn class in pyaniasetools as activ
activ = aat.subproc_pDyn(self.netdict['cnstfile'],
self.netdict['saefile'],
self.netdict['nnfprefix'],
self.netdict['num_nets'],
gpuid)
pDyn_dir=pdynparams['pDyn_dir'] #Folder to write pDynamo input file
num_rxn=pdynparams['num_rxn'] #Number of input rxn
logfile_OPT=pdynparams['logfile_OPT'] #logfile for FIRE OPT output
logfile_TS=pdynparams['logfile_TS'] #logfile for ANI TS output
logfile_IRC=pdynparams['logfile_IRC'] #logfile for ANI IRC output
sbproc_cmdOPT=pdynparams['sbproc_cmdOPT'] #Subprocess commands to run pDyanmo
sbproc_cmdTS=pdynparams['sbproc_cmdTS']
sbproc_cmdIRC=pdynparams['sbproc_cmdIRC']
IRCdir=pdynparams['IRCdir'] #path to get pDynamo saved IRC points
indir=pdynparams['indir'] #path to save XYZ files of IRC points to check stddev
XYZfile=pdynparams['XYZfile'] #XYZ file with high standard deviations structures
l_val=pdynparams['l_val'] #Ri --> randomly perturb in the interval [+x,-x]
h_val=pdynparams['h_val']
n_points=pdynparams['n_points'] #Number of points along IRC (forward+backward+1 for TS)
sig=pdynparams['sig']
N=pdynparams['N']
wkdir=pdynparams['wkdir']
cnstfilecv=pdynparams['cnstfilecv']
saefilecv=pdynparams['saefilecv']
Nnt=pdynparams['Nnt']
# --------------------------------- Run pDynamo ---------------------------
# auto-TS ---> FIRE constraint OPT of core C atoms ---> ANI TS ---> ANI IRC
activ.write_pDynOPT(num_rxn, pDyn_dir, wkdir, cnstfilecv, saefilecv, Nnt) #Write pDynamo input file in pDyndir
activ.write_pDynTS(num_rxn, pDyn_dir, wkdir, cnstfilecv, saefilecv, Nnt)
activ.write_pDynIRC(num_rxn, pDyn_dir, wkdir, cnstfilecv, saefilecv, Nnt)
chk_OPT = activ.subprocess_cmd(sbproc_cmdOPT, False, logfile_OPT)
if chk_OPT == 0: #Wait until previous subproc is done!!
chk_TS = activ.subprocess_cmd(sbproc_cmdTS, False, logfile_TS)
if chk_TS == 0:
chk_IRC = activ.subprocess_cmd(sbproc_cmdIRC, False, logfile_IRC)
# ----------------------- Save points along ANI IRC ------------------------
IRCfils=os.listdir(IRCdir)
IRCfils.sort()
for f in IRCfils:
activ.getIRCpoints_toXYZ(n_points, IRCdir+f, f, indir)
infils=os.listdir(indir)
infils.sort()
# ------ Check for high standard deviation structures and get vib modes -----
for f in infils:
stdev = activ.check_stddev(indir+f, sig)
if stdev > sig: #if stddev is high then get modes for that point
nmc = activ.get_nm(indir+f) #save modes in memory for later use
activ.write_nm_xyz(XYZfile) #writes all the structures with high standard deviations to xyz file
# ----------------------------- Read XYZ for NM -----------------------------
X, spc, Na, C = hdt.readxyz3(XYZfile)
# --------- NMS for XYZs with high stddev --------
for i in range(len(X)):
for j in range (len(nmc)):
gen = nmt.nmsgenerator_RXN(X[i],nmc[j],spc[i],l_val,h_val) # xyz,nmo,fcc,spc,T,Ri_-x,Ri_+x,minfc = 1.0E-3
N = 500
gen_crd = np.zeros((N, len(spc[i]),3),dtype=np.float32)
for k in range(N):
gen_crd[k] = gen.get_random_structure()
hdt.writexyzfile(self.cdir + 'nms_TS%i.xyz' %N, gen_crd, spc[i])
del activ
def interval(v,S):
ps = 0.0
ds = 1.0 / float(S)
for s in range(S):
if v > ps and v <= ps+ds:
return s
ps = ps + ds
class anitrainerinputdesigner:
def __init__(self):
self.params = {"sflparamsfile":None, # AEV parameters file
"ntwkStoreDir":"networks/", # Store network dir
"atomEnergyFile":None, # Atomic energy shift file
"nmax": 0, # Max training iterations
"tolr": 50, # Annealing tolerance (patience)
"emult": 0.5, # Annealing multiplier
"eta": 0.001, # Learning rate
"tcrit": 1.0e-5, # eta termination crit.
"tmax": 0, # Maximum time (0 = inf)
"tbtchsz": 2048, # training batch size
"vbtchsz": 2048, # validation batch size
"gpuid": 0, # Default GPU id (is overridden by -g flag for HDAtomNNP-Trainer exe)
"ntwshr": 0, # Use a single network for all types... (THIS IS BROKEN, DO NOT USE)
"nkde": 2, # Energy delta regularization
"energy": 1, # Enable/disable energy training
"force": 0, # Enable/disable force training
"fmult": 1.0, # Multiplier of force cost
"pbc": 0, # Use PBC in training (Warning, this only works for data with a single rect. box size)
"cmult": 1.0, # Charge cost multiplier (CHARGE TRAINING BROKEN IN CURRENT VERSION)
"runtype" : "ANNP_CREATE_HDNN_AND_TRAIN", # DO NOT CHANGE - For NeuroChem backend
"adptlrn" : "OFF",
"decrate" : 0.9,
"moment" : "ADAM",
"mu" : 0.99
}
self.layers = dict()
def add_layer(self, atomtype, layer_dict):
layer_dict.update({"type":0})
if atomtype not in self.layers:
self.layers[atomtype]=[layer_dict]
else:
self.layers[atomtype].append(layer_dict)
def set_parameter(self,key,value):
self.params[key]=value
def print_layer_parameters(self):
for ak in self.layers.keys():
print('Species:',ak)
for l in self.layers[ak]:
print(' -',l)
def print_training_parameters(self):
print(self.params)
def __get_value_string__(self,value):
if type(value)==float:
string="{0:10.7e}".format(value)
else:
string=str(value)
return string
def __build_network_str__(self, iptsize):
network = "network_setup {\n"
network += " inputsize="+str(iptsize)+";\n"
for ak in self.layers.keys():
network += " atom_net " + ak + " $\n"
self.layers[ak].append({"nodes":1,"activation":6,"type":0})
for l in self.layers[ak]:
network += " layer [\n"
for key in l.keys():
network += " "+key+"="+self.__get_value_string__(l[key])+";\n"
network += " ]\n"
network += " $\n"
network += "}\n"
return network
def write_input_file(self, file, iptsize):
f = open(file,'w')
for key in self.params.keys():
f.write(key+'='+self.__get_value_string__(self.params[key])+'\n')
f.write(self.__build_network_str__(iptsize))
f.close()
class alaniensembletrainer():
def __init__(self, train_root, netdict, h5dir, Nn):
self.train_root = train_root
#self.train_pref = train_pref
self.h5dir = h5dir
self.Nn = Nn
self.netdict = netdict
self.h5file = [f for f in os.listdir(self.h5dir) if f.rsplit('.',1)[1] == 'h5']
#print(self.h5dir,self.h5file)
def build_training_cache(self,forces=True):
store_dir = self.train_root + "cache-data-"
N = self.Nn
for i in range(N):
if not os.path.exists(store_dir + str(i)):
os.mkdir(store_dir + str(i))
if os.path.exists(store_dir + str(i) + '/../testset/testset' + str(i) + '.h5'):
os.remove(store_dir + str(i) + '/../testset/testset' + str(i) + '.h5')
if not os.path.exists(store_dir + str(i) + '/../testset'):
os.mkdir(store_dir + str(i) + '/../testset')
cachet = [cg('_train', self.netdict['saefile'], store_dir + str(r) + '/', False) for r in range(N)]
cachev = [cg('_valid', self.netdict['saefile'], store_dir + str(r) + '/', False) for r in range(N)]
testh5 = [pyt.datapacker(store_dir + str(r) + '/../testset/testset' + str(r) + '.h5') for r in range(N)]
Nd = np.zeros(N, dtype=np.int32)
Nbf = 0
for f, fn in enumerate(self.h5file):
print('Processing file(' + str(f + 1) + ' of ' + str(len(self.h5file)) + '):', fn)
adl = pyt.anidataloader(self.h5dir+fn)
To = adl.size()
Ndc = 0
Fmt = []
Emt = []
for c, data in enumerate(adl):
Pn = data['path'] + '_' + str(f).zfill(6) + '_' + str(c).zfill(6)
# Progress indicator
#sys.stdout.write("\r%d%% %s" % (int(100 * c / float(To)), Pn))
#sys.stdout.flush()
# print(data.keys())
# Extract the data
X = data['coordinates']
E = data['energies']
S = data['species']
# 0.0 forces if key doesnt exist
if forces:
F = data['forces']
else:
F = 0.0*X
Fmt.append(np.max(np.linalg.norm(F, axis=2), axis=1))
Emt.append(E)
Mv = np.max(np.linalg.norm(F, axis=2), axis=1)
index = np.where(Mv > 10.5)[0]
indexk = np.where(Mv <= 10.5)[0]
Nbf += index.size
# CLear forces
X = X[indexk]
F = F[indexk]
E = E[indexk]
Esae = hdt.compute_sae(self.netdict['saefile'],S)
hidx = np.where(np.abs(E-Esae) > 10.0)
lidx = np.where(np.abs(E-Esae) <= 10.0)
if hidx[0].size > 0:
print(' -('+str(c).zfill(3)+')High energies detected:\n ',E[hidx])
X = X[lidx]
E = E[lidx]
F = F[lidx]
Ndc += E.size
if (set(S).issubset(self.netdict['atomtyp'])):
#if (set(S).issubset(['C', 'N', 'O', 'H', 'F', 'S', 'Cl'])):
# Random mask
R = np.random.uniform(0.0, 1.0, E.shape[0])
idx = np.array([interval(r, N) for r in R])
# Build random split lists
split = []
for j in range(N):
split.append([i for i, s in enumerate(idx) if s == j])
nd = len([i for i, s in enumerate(idx) if s == j])
Nd[j] = Nd[j] + nd
# Store data
for i, t, v, te in zip(range(N), cachet, cachev, testh5):
## Store training data
X_t = np.array(np.concatenate([X[s] for j, s in enumerate(split) if j != i]), order='C',
dtype=np.float32)
F_t = np.array(np.concatenate([F[s] for j, s in enumerate(split) if j != i]), order='C',
dtype=np.float32)
E_t = np.array(np.concatenate([E[s] for j, s in enumerate(split) if j != i]), order='C',
dtype=np.float64)
if E_t.shape[0] != 0:
t.insertdata(X_t, F_t, E_t, list(S))
## Split test/valid data and store\
#tv_split = np.array_split(split[i], 2)
## Store Validation
if np.array(split[i]).size > 0:
X_v = np.array(X[split[i]], order='C', dtype=np.float32)
F_v = np.array(F[split[i]], order='C', dtype=np.float32)
E_v = np.array(E[split[i]], order='C', dtype=np.float64)
if E_v.shape[0] != 0:
v.insertdata(X_v, F_v, E_v, list(S))
## Store testset
#if tv_split[1].size > 0:
#X_te = np.array(X[split[i]], order='C', dtype=np.float32)
#F_te = np.array(F[split[i]], order='C', dtype=np.float32)
#E_te = np.array(E[split[i]], order='C', dtype=np.float64)
#if E_te.shape[0] != 0:
# te.store_data(Pn, coordinates=X_te, forces=F_te, energies=E_te, species=list(S))
#sys.stdout.write("\r%d%%" % int(100))
#print(" Data Kept: ", Ndc, 'High Force: ', Nbf)
#sys.stdout.flush()
#print("")
# Print some stats
print('Data count:', Nd)
print('Data split:', 100.0 * Nd / np.sum(Nd), '%')
# Save train and valid meta file and cleanup testh5
for t, v, th in zip(cachet, cachev, testh5):
t.makemetadata()
v.makemetadata()
th.cleanup()
def sae_linear_fitting(self, Ekey='energies', energy_unit=1.0, Eax0sum=False):
from sklearn import linear_model
print('Performing linear fitting...')
datadir = self.h5dir
sae_out = self.netdict['saefile']
smap = dict()
for i,Z in enumerate(self.netdict['atomtyp']):
smap.update({Z:i})
Na = len(smap)
files = os.listdir(datadir)
X = []
y = []
for f in files[0:20]:
print(f)
adl = pyt.anidataloader(datadir + f)
for data in adl:
# print(data['path'])
S = data['species']
if data[Ekey].size > 0:
if Eax0sum:
E = energy_unit*np.sum(np.array(data[Ekey], order='C', dtype=np.float64), axis=1)
else:
E = energy_unit*np.array(data[Ekey], order='C', dtype=np.float64)
S = S[0:data['coordinates'].shape[1]]
unique, counts = np.unique(S, return_counts=True)
x = np.zeros(Na, dtype=np.float64)
for u, c in zip(unique, counts):
x[smap[u]] = c
for e in E:
X.append(np.array(x))
y.append(np.array(e))
X = np.array(X)
y = np.array(y).reshape(-1, 1)
lin = linear_model.LinearRegression(fit_intercept=False)
lin.fit(X, y)
coef = lin.coef_
print(coef)
sae = open(sae_out, 'w')
for i, c in enumerate(coef[0]):
sae.write(next(key for key, value in smap.items() if value == i) + ',' + str(i) + '=' + str(c) + '\n')
sae.close()
print('Linear fitting complete.')
def build_strided_training_cache(self,Nblocks,Nvalid,Ntest,build_test=True, build_valid=False, forces=True, grad=False, Fkey='forces', forces_unit=1.0, Ekey='energies', energy_unit=1.0, Eax0sum=False, rmhighe=True):
if not os.path.isfile(self.netdict['saefile']):
self.sae_linear_fitting(Ekey=Ekey, energy_unit=energy_unit, Eax0sum=Eax0sum)
h5d = self.h5dir
store_dir = self.train_root + "cache-data-"
N = self.Nn
Ntrain = Nblocks - Nvalid - Ntest
if Nblocks % N != 0:
raise ValueError('Error: number of networks must evenly divide number of blocks.')
Nstride = Nblocks/N
for i in range(N):
if not os.path.exists(store_dir + str(i)):
os.mkdir(store_dir + str(i))
if build_test:
if os.path.exists(store_dir + str(i) + '/../testset/testset' + str(i) + '.h5'):
os.remove(store_dir + str(i) + '/../testset/testset' + str(i) + '.h5')
if not os.path.exists(store_dir + str(i) + '/../testset'):
os.mkdir(store_dir + str(i) + '/../testset')
cachet = [cg('_train', self.netdict['saefile'], store_dir + str(r) + '/', False) for r in range(N)]
cachev = [cg('_valid', self.netdict['saefile'], store_dir + str(r) + '/', False) for r in range(N)]
if build_test:
testh5 = [pyt.datapacker(store_dir + str(r) + '/../testset/testset' + str(r) + '.h5') for r in range(N)]
if build_valid:
valdh5 = [pyt.datapacker(store_dir + str(r) + '/../testset/valdset' + str(r) + '.h5') for r in range(N)]
if rmhighe:
dE = []
for f in self.h5file:
adl = pyt.anidataloader(h5d+f)
for data in adl:
S = data['species']
E = data['energies']
X = data['coordinates']
Esae = hdt.compute_sae(self.netdict['saefile'], S)
dE.append((E-Esae)/np.sqrt(len(S)))
dE = np.concatenate(dE)
cidx = np.where(np.abs(dE) < 15.0)
std = np.abs(dE[cidx]).std()
men = np.mean(dE[cidx])
print(men,std,men+std)
idx = np.intersect1d(np.where(dE>=-np.abs(15*std+men))[0],np.where(dE<=np.abs(11*std+men))[0])
cnt = idx.size
print('DATADIST: ',dE.size,cnt,(dE.size-cnt),100.0*((dE.size-cnt)/dE.size))
E = []
data_count = np.zeros((N,3),dtype=np.int32)
for f in self.h5file:
print('Reading data file:',h5d+f)
adl = pyt.anidataloader(h5d+f)
for data in adl:
#print(data['path'],data['energies'].size)
S = data['species']
if data[Ekey].size > 0 and (set(S).issubset(self.netdict['atomtyp'])):
X = np.array(data['coordinates'], order='C',dtype=np.float32)
#print(np.array(data[Ekey].shape),np.sum(np.array(data[Ekey], order='C', dtype=np.float64),axis=1).shape,data[Fkey].shape)
if Eax0sum:
E = energy_unit*np.sum(np.array(data[Ekey], order='C', dtype=np.float64),axis=1)
else:
E = energy_unit*np.array(data[Ekey], order='C',dtype=np.float64)
if forces and not grad:
F = forces_unit*np.array(data[Fkey], order='C', dtype=np.float32)
elif forces and grad:
F = -forces_unit*np.array(data[Fkey], order='C', dtype=np.float32)
else:
F = 0.0*X
if rmhighe:
Esae = hdt.compute_sae(self.netdict['saefile'], S)
ind_dE = (E - Esae)/np.sqrt(len(S))
hidx = np.union1d(np.where(ind_dE<-(15.0*std+men))[0],np.where(ind_dE>(11.0*std+men))[0])
lidx = np.intersect1d(np.where(ind_dE>=-(15.0*std+men))[0],np.where(ind_dE<=(11.0*std+men))[0])
if hidx.size > 0:
print(' -(' + f + ':' + data['path'] + ')High energies detected:\n ', (E[hidx]-Esae)/np.sqrt(len(S)))
X = X[lidx]
E = E[lidx]
F = F[lidx]
# Build random split index
ridx = np.random.randint(0,Nblocks,size=E.size)
Didx = [np.argsort(ridx)[np.where(ridx == i)] for i in range(Nblocks)]
# Build training cache
for nid,cache in enumerate(cachet):
set_idx = np.concatenate([Didx[((bid+nid*int(Nstride)) % Nblocks)] for bid in range(Ntrain)])
if set_idx.size != 0:
data_count[nid,0]+=set_idx.size
cache.insertdata(X[set_idx], F[set_idx], E[set_idx], list(S))
# for nid,cache in enumerate(cachev):
# set_idx = np.concatenate([Didx[((1+bid+nid*int(Nstride)) % Nblocks)] for bid in range(Ntrain)])
# if set_idx.size != 0:
# data_count[nid,0]+=set_idx.size
# cache.insertdata(X[set_idx], F[set_idx], E[set_idx], list(S))
for nid,cache in enumerate(cachev):
set_idx = np.concatenate([Didx[(Ntrain+bid+nid*int(Nstride)) % Nblocks] for bid in range(Nvalid)])
if set_idx.size != 0:
data_count[nid, 1] += set_idx.size
cache.insertdata(X[set_idx], F[set_idx], E[set_idx], list(S))
if build_valid:
valdh5[nid].store_data(f+data['path'], coordinates=X[set_idx], forces=F[set_idx], energies=E[set_idx], species=list(S))
if build_test:
for nid,th5 in enumerate(testh5):
set_idx = np.concatenate([Didx[(Ntrain+Nvalid+bid+nid*int(Nstride)) % Nblocks] for bid in range(Ntest)])
if set_idx.size != 0:
data_count[nid, 2] += set_idx.size
th5.store_data(f+data['path'], coordinates=X[set_idx], forces=F[set_idx], energies=E[set_idx], species=list(S))
# Save train and valid meta file and cleanup testh5
for t, v in zip(cachet, cachev):
t.makemetadata()
v.makemetadata()
if build_test:
for th in testh5:
th.cleanup()
if build_valid:
for vh in valdh5:
vh.cleanup()
print(' Train ',' Valid ',' Test ')
print(data_count)
print('Training set built.')
def train_ensemble(self, GPUList, remove_existing=False):
print('Training Ensemble...')
processes = []
indicies = np.array_split(np.arange(self.Nn), len(GPUList))
for gpu,idc in enumerate(indicies):
processes.append(Process(target=self.train_network, args=(GPUList[gpu], idc, remove_existing)))
processes[-1].start()
#self.train_network(pyncdict, trdict, layers, id, i)
for p in processes:
p.join()
print('Training Complete.')
def train_network(self, gpuid, indicies, remove_existing=False):
for index in indicies:
pyncdict = dict()
pyncdict['wkdir'] = self.train_root + 'train' + str(index) + '/'
pyncdict['ntwkStoreDir'] = self.train_root + 'train' + str(index) + '/' + 'networks/'
pyncdict['datadir'] = self.train_root + "cache-data-" + str(index) + '/'
pyncdict['gpuid'] = str(gpuid)
if not os.path.exists(pyncdict['wkdir']):
os.mkdir(pyncdict['wkdir'])
if remove_existing:
shutil.rmtree(pyncdict['ntwkStoreDir'])
if not os.path.exists(pyncdict['ntwkStoreDir']):
os.mkdir(pyncdict['ntwkStoreDir'])
outputfile = pyncdict['wkdir']+'output.opt'
shutil.copy2(self.netdict['iptfile'], pyncdict['wkdir'])
shutil.copy2(self.netdict['cnstfile'], pyncdict['wkdir'])
shutil.copy2(self.netdict['saefile'], pyncdict['wkdir'])
if "/" in self.netdict['iptfile']:
nfile = self.netdict['iptfile'].rsplit("/",1)[1]
else:
nfile = self.netdict['iptfile']
command = "cd " + pyncdict['wkdir'] + " && HDAtomNNP-Trainer -i " + nfile + " -d " + pyncdict['datadir'] + " -p 1.0 -m -g " + pyncdict['gpuid'] + " > output.opt"
proc = subprocess.Popen (command, shell=True)
proc.communicate()
print(' -Model',index,'complete')
def get_train_stats(self):
#rerr = re.compile('EPOCH\s+?(\d+?)\n[\s\S]+?E \(kcal\/mol\)\s+?(\d+?\.\d+?)\s+?(\d+?\.\d+?)\s+?(\d+?\.\d+?)\n\s+?dE \(kcal\/mol\)\s+?(\d+?\.\d+?)\s+?(\d+?\.\d+?)\s+?(\d+?\.\d+?)\n[\s\S]+?Current best:\s+?(\d+?)\n[\s\S]+?Learning Rate:\s+?(\S+?)\n[\s\S]+?TotalEpoch:\s+([\s\S]+?)\n')
#rerr = re.compile('EPOCH\s+?(\d+?)\s+?\n[\s\S]+?E \(kcal\/mol\)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\n\s+?dE \(kcal\/mol\)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\n')
rblk = re.compile('=+?\n([\s\S]+?=+?\n[\s\S]+?(?:=|Deleting))')
repo = re.compile('EPOCH\s+?(\d+?)\s+?\n')
rerr = re.compile('\s+?(\S+?\s+?\(\S+?)\s+?((?:\d|inf)\S*?)\s+?((?:\d|inf)\S*?)\s+?((?:\d|inf)\S*?)\n')
rtme = re.compile('TotalEpoch:\s+?(\d+?)\s+?dy\.\s+?(\d+?)\s+?hr\.\s+?(\d+?)\s+?mn\.\s+?(\d+?\.\d+?)\s+?sc\.')
allnets = []
for index in range(self.Nn):
print('reading:',self.train_root + 'train' + str(index) + '/' + 'output.opt')
optfile = open(self.train_root + 'train' + str(index) + '/' + 'output.opt','r').read()
matches = re.findall(rblk, optfile)
run = dict({'EPOCH':[],'RTIME':[],'ERROR':dict()})
for i,data in enumerate(matches):
run['EPOCH'].append(int(re.search(repo,data).group(1)))
m = re.search(rtme, data)
run['RTIME'].append(86400.0*float(m.group(1))+
3600.0*float(m.group(2))+
60.0*float(m.group(3))+
float(m.group(4)))
err = re.findall(rerr,data)
for e in err:
if e[0] in run['ERROR']:
run['ERROR'][e[0]].append(np.array([float(e[1]),float(e[2]),float(e[3])],dtype=np.float64))
else:
run['ERROR'].update({e[0]:[np.array([float(e[1]), float(e[2]), float(e[3])], dtype=np.float64)]})
for key in run['ERROR'].keys():
run['ERROR'][key] = np.vstack(run['ERROR'][key])
allnets.append(run)
return allnets
|
{"hexsha": "980e6c37b9c028142ebe2cddb9ecb468a69fb9ce", "size": 45991, "ext": "py", "lang": "Python", "max_stars_repo_path": "lib/anialtools.py", "max_stars_repo_name": "plin1112/ANI-Tools", "max_stars_repo_head_hexsha": "76280c918fc79fee8c266b8bc9ab57f86104ec99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-10-30T16:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T01:44:41.000Z", "max_issues_repo_path": "lib/anialtools.py", "max_issues_repo_name": "plin1112/ANI-Tools", "max_issues_repo_head_hexsha": "76280c918fc79fee8c266b8bc9ab57f86104ec99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/anialtools.py", "max_forks_repo_name": "plin1112/ANI-Tools", "max_forks_repo_head_hexsha": "76280c918fc79fee8c266b8bc9ab57f86104ec99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-04-05T15:51:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-23T21:38:31.000Z", "avg_line_length": 42.154903758, "max_line_length": 291, "alphanum_fraction": 0.4718097019, "include": true, "reason": "import numpy", "num_tokens": 11562}
|
\chapter{Mitigations}
\label{ch:mitigations}
In this chapter we describe the mitigations to the threats we found in
the previous chapter.
\section{Mitigation by Threat}
The threat tables detail a proposed mitigation for each identified
threat. The final implementation is left to the designers who would
address each threat through the bug list. For a product in
development, additional visibility can be afforded by generating
requirements or test cases that identify each threat or risk.
\section{Risk and Prioritization}
\label{sec:risk}
While it is beyond the scope of this assignment to describe any technical or
business processes used to manage risk, we implicitly manage risk through our
assumptions and mitigations. For example, the risk from the threat of loss of
the USB (resulting in a denial of service) is transferred to the owner of the
device by assuming that the owner will take adequate precautions to prevent loss
or theft of the device. For the unlikely lucky guess threat, the risk is
accepted because the likelihood of properly guessing a complex password in a
very small, fixed number of tries is unlikely.
\begin{marginfigure}
\centering
\includegraphics[width=\linewidth]{riskcats}
\caption{Risk Categories Used in Threat Modeling}
\label{fig:riskcats}
\end{marginfigure}
In general, we would expect to pay most attention to priority risks in
increasing order; for example, a category one risk would be addressed before a
category 3 threat risk.
\subsection{Risk Determination}
We used a modified OWASP risk methodology to determine the risks posed by each
threat or group of similar threats. Detailed information concerning the assessed
risks can be found in \nameref{ch:a4}.
|
{"hexsha": "df1c87c8bc6b01b4cfd2543a54d4fbea3427c74b", "size": 1726, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "text/mitigation.tex", "max_stars_repo_name": "pacman47403/B547A1", "max_stars_repo_head_hexsha": "e5b21e352efa257102ffe9ea8674ea73e910e449", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "text/mitigation.tex", "max_issues_repo_name": "pacman47403/B547A1", "max_issues_repo_head_hexsha": "e5b21e352efa257102ffe9ea8674ea73e910e449", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "text/mitigation.tex", "max_forks_repo_name": "pacman47403/B547A1", "max_forks_repo_head_hexsha": "e5b21e352efa257102ffe9ea8674ea73e910e449", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2564102564, "max_line_length": 80, "alphanum_fraction": 0.8035921205, "num_tokens": 378}
|
[STATEMENT]
lemma step_Stuck_prop:
assumes step: "\<Gamma> \<turnstile> (c, s) \<rightarrow> (c', s')"
shows "s=Stuck \<Longrightarrow> s'=Stuck"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. s = Stuck \<Longrightarrow> s' = Stuck
[PROOF STEP]
using step
[PROOF STATE]
proof (prove)
using this:
\<Gamma>\<turnstile> (c, s) \<rightarrow> (c', s')
goal (1 subgoal):
1. s = Stuck \<Longrightarrow> s' = Stuck
[PROOF STEP]
by (induct) auto
|
{"llama_tokens": 182, "file": "Complx_SmallStep", "length": 2}
|
/*
* Copyright (c) 2018, Sunanda Bose (Neel Basu) (neel.basu.z@gmail.com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include "mathematica++/compatibility.h"
#include "mathematica++/exceptions.h"
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include "mathematica++/connection.h"
mathematica::exceptions::error::error(int ec, const std::string& context, const std::string& message): runtime_error((boost::format("WSTP Error (%1%) in <%2%> \"%3%\"") % ec % context % message).str()), _code(ec), _context(context), _message(message){
}
mathematica::exceptions::error mathematica::exceptions::dispatch(WMK_LINK link, const std::string& context){
int ec = WMK_Error(link);
return error(ec, context, std::string(WMK_ErrorMessage(link)));
}
mathematica::exceptions::error mathematica::exceptions::dispatch(mathematica::driver::io::connection& conn, const std::string& context){
int ec = 0;
std::string message = conn.error(ec);
return error(ec, context, message);
}
|
{"hexsha": "3559a75155e2eea97e550d84f1902cd37bbdbf01", "size": 2319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/exceptions.cpp", "max_stars_repo_name": "DominikLindorfer/mathematicapp", "max_stars_repo_head_hexsha": "ce9de342501d803ccd115533d19c7e3ace51e475", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-10-04T16:27:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T22:28:51.000Z", "max_issues_repo_path": "sources/exceptions.cpp", "max_issues_repo_name": "DominikLindorfer/mathematicapp", "max_issues_repo_head_hexsha": "ce9de342501d803ccd115533d19c7e3ace51e475", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/exceptions.cpp", "max_forks_repo_name": "DominikLindorfer/mathematicapp", "max_forks_repo_head_hexsha": "ce9de342501d803ccd115533d19c7e3ace51e475", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-22T03:33:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-17T07:10:21.000Z", "avg_line_length": 48.3125, "max_line_length": 251, "alphanum_fraction": 0.7391116861, "num_tokens": 532}
|
#include <boost/text/trie_set.hpp>
#include <boost/text/trie_set.hpp>
|
{"hexsha": "6d358d077612d87b575d0fb073c847bad5dbcaae", "size": 70, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/compile_include_trie_set_2.cpp", "max_stars_repo_name": "eightysquirrels/text", "max_stars_repo_head_hexsha": "d935545648777786dc196a75346cde8906da846a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/compile_include_trie_set_2.cpp", "max_issues_repo_name": "eightysquirrels/text", "max_issues_repo_head_hexsha": "d935545648777786dc196a75346cde8906da846a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T12:56:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T13:11:53.000Z", "max_forks_repo_path": "test/compile_include_trie_set_2.cpp", "max_forks_repo_name": "eightysquirrels/text", "max_forks_repo_head_hexsha": "d935545648777786dc196a75346cde8906da846a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-30T18:38:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T12:10:13.000Z", "avg_line_length": 23.3333333333, "max_line_length": 34, "alphanum_fraction": 0.7714285714, "num_tokens": 18}
|
"""
Optimization of the CADRE MDP.
"""
from __future__ import print_function
import numpy as np
from openmdao.api import Problem, PETScKrylov # , LinearBlockGS
from CADRE.CADRE_mdp import CADRE_MDP_Group
import cProfile
import pstats
import sys
argv = sys.argv[1:]
if 'paper' in argv:
# These numbers are for the CADRE problem in the paper.
n = 1500
m = 300
npts = 6
print("Using parameters from paper:", n, m, npts)
else:
# These numbers are for quick testing
n = 150
m = 6
npts = 2
print("Using parameters for quick test:", n, m, npts)
# instantiate model
model = CADRE_MDP_Group(n=n, m=m, npts=npts)
# add design variables and constraints to each CADRE instance
names = ['pt%s' % i for i in range(npts)]
for i, name in enumerate(names):
model.add_design_var('%s.CP_Isetpt' % name, lower=0., upper=0.4)
model.add_design_var('%s.CP_gamma' % name, lower=0, upper=np.pi/2.)
model.add_design_var('%s.CP_P_comm' % name, lower=0., upper=25.)
model.add_design_var('%s.iSOC' % name, indices=[0], lower=0.2, upper=1.)
model.add_constraint('%s.ConCh' % name, upper=0.0)
model.add_constraint('%s.ConDs' % name, upper=0.0)
model.add_constraint('%s.ConS0' % name, upper=0.0)
model.add_constraint('%s.ConS1' % name, upper=0.0)
model.add_constraint('%s_con5.val' % name, equals=0.0)
# add broadcast parameters
model.add_design_var('bp.cellInstd', lower=0., upper=1.0)
model.add_design_var('bp.finAngle', lower=0., upper=np.pi/2.)
model.add_design_var('bp.antAngle', lower=-np.pi/4, upper=np.pi/4)
# add objective
model.add_objective('obj.val')
# for parallel execution, we must use KSP
model.linear_solver = PETScKrylov()
# model.linear_solver = LinearBlockGS()
# model.parallel.linear_solver = LinearBlockGS()
# model.parallel.pt0.linear_solver = LinearBlockGS()
# model.parallel.pt1.linear_solver = LinearBlockGS()
# create problem
prob = Problem(model)
prob.setup()
prob.run_driver()
# ----------------------------------------------------------------
# Below this line, code used for verifying and profiling.
# ----------------------------------------------------------------
cProfile.run("prob.compute_totals()", 'profout')
p = pstats.Stats('profout')
p.strip_dirs()
p.sort_stats('cumulative', 'time')
p.print_stats()
print('\n\n---------------------\n\n')
p.print_callers()
print('\n\n---------------------\n\n')
p.print_callees()
|
{"hexsha": "421958f0dfebbdb509faeeffa3471614ba27eb4f", "size": 2419, "ext": "py", "lang": "Python", "max_stars_repo_path": "profile/profile_derivs.py", "max_stars_repo_name": "robfalck/CADRE", "max_stars_repo_head_hexsha": "f1fb419aade62fe830d56d958f35f1e153f04363", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-05-13T23:44:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T07:23:30.000Z", "max_issues_repo_path": "profile/profile_derivs.py", "max_issues_repo_name": "robfalck/CADRE", "max_issues_repo_head_hexsha": "f1fb419aade62fe830d56d958f35f1e153f04363", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-07-24T20:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-07T17:16:51.000Z", "max_forks_repo_path": "profile/profile_derivs.py", "max_forks_repo_name": "robfalck/CADRE", "max_forks_repo_head_hexsha": "f1fb419aade62fe830d56d958f35f1e153f04363", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-07-21T17:41:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-31T09:49:09.000Z", "avg_line_length": 28.4588235294, "max_line_length": 76, "alphanum_fraction": 0.651508888, "include": true, "reason": "import numpy", "num_tokens": 676}
|
program givcor
! Given two arrays of equal length of unordered values, find a
! "matching value" in the second array for each value in the
! first so that the global correlation coefficient reaches
! exactly a given target.
! _________________________________________________________________
! The routine first sorts the two arrays, so as to get the
! match of maximum correlation.
! It then will iterate, applying the random permutation algorithm
! of controlled disorder ctrper to the second array. When the
! resulting correlation goes beyond (lower than) the target
! correlation, one steps back and reduces the disorder parameter
! of the permutation. When the resulting correlation lies between
! the current one and the target, one replaces the array with
! the newly permuted one. When the resulting correlation increases
! from the current value, one increases the disorder parameter.
! That way, the target correlation is approached from above, by
! a controlled increase in randomness.
! The example is two arrays representing parents' incomes and
! children's incomes, but where it is not known which parents
! correspond to which children. The output is a list of pairs
! {parents' income, children's income} such that the target
! correlation is approached.
! Michel Olagnon - December 2001.
! Corrected August 2007 (dot_product (xnewt, xpart) line 87,
! and negative correlation targets).
! _________________________________________________________________
use m_ctrper
use m_refsor
!
Integer, Parameter :: ndim = 21571 ! Number of pairs
Integer, Parameter :: kdp = selected_real_kind(15)
Real(kind=kdp), Parameter :: dtar = 0.1654_kdp ! Target correlation
Real(kind=kdp) :: dsum, dref, dmoyp, dsigp, dmoyc, dsigc, dtarw
Real(kind=kdp), Dimension (ndim) :: xpart, xchit, xnewt
Real :: xper = 0.25
Real :: xdec = 0.997
Integer, Dimension (:), Allocatable :: jseet, jsavt
Integer :: nsee, ibcl
!
Call random_seed (size=nsee)
Allocate (jseet(1:nsee), jsavt(1:nsee))
!
! Read parent's incomes
!
Open (unit=11, file="parents.dat", form="formatted", status="old", action="read")
Do ibcl = 1, ndim
read (unit=11, fmt=*) xpart (ibcl)
End Do
Close (unit=11)
!
! Sort, and normalize to make further correlation computations faster
!
call refsor (xpart)
dmoyp = sum (xpart) / real (ndim, kind=kdp)
xpart = xpart - dmoyp
dsigp = sqrt(dot_product(xpart,xpart))
xpart = xpart * (1.0_kdp/dsigp)
!
! Read children's incomes
!
Open (unit=12, file="children.dat", form="formatted", status="old", action="read")
Do ibcl = 1, ndim
read (unit=12, fmt=*) xchit (ibcl)
End Do
Close (unit=12)
!
! Sort, and normalize
!
call refsor (xchit)
dmoyc = sum (xchit) / real (ndim, kind=kdp)
xchit = xchit - dmoyc
dsigc = sqrt(dot_product(xchit,xchit))
if (dtar < 0.0_kdp) then
xchit = - xchit * (1.0_kdp/dsigc)
else
xchit = xchit * (1.0_kdp/dsigc)
endif
dtarw = abs (dtar)
!
! Compute starting value, maximum correlation
!
dref = dot_product(xpart,xchit)
! write (unit=*, fmt="(f8.6)") dref
!
! Iterate
!
Do ibcl = 1, 100000
xnewt = xchit
!
! Add some randomness to the current order
!
Call ctrper (xnewt, xper)
dsum = dot_product(xnewt, xpart)
! if (modulo (ibcl,100) == 1) write (unit=*, fmt=*) ibcl, dref, dsum, xper
!
! Check for hit of target
!
if (abs (dsum-dtarw) < 0.00001_kdp) then
dref = dsum
xchit = xnewt
exit
End If
!
! Better, but not yet reached target: take new set as current one
!
if (dsum < dref .and. dsum > dtarw) then
dref = dsum
xchit = xnewt
!
! We went too far, beyond the target: try to be a little less random
!
elseif (dsum < dtarw) then
xper = max (xper * xdec, 0.5 / Real(ndim))
!
! We are going in the ordered direction: try to be a little more random
!
elseif (dsum > dref) then
xper = min (xper / xdec, 0.25)
endif
End Do
!
! Unnormalize and output pairs
!
write (unit=*, fmt="(a,f10.8,a,i8)") "Reached ", dref, &
"after iteration ", ibcl
xpart = dmoyp + dsigp * xpart
if (dtar < 0.0_kdp) then
xchit = dmoyc - dsigc * xchit
else
xchit = dmoyc + dsigc * xchit
endif
Open (unit=13, file="corchild.dat", form="formatted", status="unknown",&
action="write")
Do ibcl = 1, ndim
write (unit=13, fmt=*) nint(xpart(ibcl)), nint(xchit(ibcl))
End Do
Close (unit=13)
!
end program givcor
|
{"hexsha": "f59ab32931206c067c2d990549146d47cf78bbb1", "size": 4845, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "source/f2000/givcor.f90", "max_stars_repo_name": "agforero/FTFramework", "max_stars_repo_head_hexsha": "6caf0bc7bae8dc54a62da62df37e852625f0427d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-08-19T21:43:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T02:57:25.000Z", "max_issues_repo_path": "source/f2000/givcor.f90", "max_issues_repo_name": "agforero/fortran-testing-framework", "max_issues_repo_head_hexsha": "6caf0bc7bae8dc54a62da62df37e852625f0427d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-07T21:17:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-09T02:18:07.000Z", "max_forks_repo_path": "source/f2000/givcor.f90", "max_forks_repo_name": "agforero/fortran-testing-framework", "max_forks_repo_head_hexsha": "6caf0bc7bae8dc54a62da62df37e852625f0427d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-31T08:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:41:53.000Z", "avg_line_length": 34.3617021277, "max_line_length": 88, "alphanum_fraction": 0.6276573787, "num_tokens": 1443}
|
# Copyright 2017 Google Inc. 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.
# ==============================================================================
"""Creates random embedding."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import numpy as np
embeds = (5 * np.squeeze(np.random.randn(1, 100))).tolist()
json_object = {'key': '0', 'embeddings': embeds}
print(json.dumps(json_object))
|
{"hexsha": "0e431fa38d41cea1a8636d8c52ba67154905e005", "size": 992, "ext": "py", "lang": "Python", "max_stars_repo_path": "vae-gan/data/create_random_embedding.py", "max_stars_repo_name": "google/generativemloncloud", "max_stars_repo_head_hexsha": "29c4a7b14b5fababaa4570c9efce07517dd0d79f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60, "max_stars_repo_stars_event_min_datetime": "2017-08-30T17:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T18:45:16.000Z", "max_issues_repo_path": "vae-gan/data/create_random_embedding.py", "max_issues_repo_name": "google/generativemloncloud", "max_issues_repo_head_hexsha": "29c4a7b14b5fababaa4570c9efce07517dd0d79f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-01-23T01:34:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T01:34:14.000Z", "max_forks_repo_path": "vae-gan/data/create_random_embedding.py", "max_forks_repo_name": "google/generativemloncloud", "max_forks_repo_head_hexsha": "29c4a7b14b5fababaa4570c9efce07517dd0d79f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15, "max_forks_repo_forks_event_min_datetime": "2017-09-09T15:05:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-13T22:43:57.000Z", "avg_line_length": 36.7407407407, "max_line_length": 80, "alphanum_fraction": 0.6995967742, "include": true, "reason": "import numpy", "num_tokens": 212}
|
Add LoadPath "D:\sfsol".
Require Export Imp.
Definition aequiv (a1 a2 : aexp) : Prop :=
forall (st:state),
aeval st a1 = aeval st a2.
Definition bequiv (b1 b2 : bexp) : Prop :=
forall (st:state),
beval st b1 = beval st b2.
Definition cequiv (c1 c2 : com) : Prop :=
forall (st st' : state),
(c1 / st || st') <-> (c2 / st || st').
(* {a}{b}{c,h}{d}{e}{f,i}{g} *)
Theorem aequiv_example:
aequiv (AMinus (AId X) (AId X)) (ANum 0).
Proof.
unfold aequiv.
intros.
unfold aeval.
induction (st X); simpl; try reflexivity; try assumption.
Qed.
Theorem bequiv_example:
bequiv (BEq (AMinus (AId X) (AId X)) (ANum 0)) BTrue.
Proof.
unfold bequiv.
intros.
unfold beval.
rewrite -> aequiv_example. simpl. auto.
Qed.
Theorem skip_left: forall c,
cequiv
(SKIP;; c)
c.
Proof.
(* WORKED IN CLASS *)
intros c st st'.
split; intros H.
Case "->".
inversion H. subst.
inversion H2. subst.
assumption.
Case "<-".
apply E_Seq with st.
apply E_Skip.
assumption.
Qed.
Theorem skip_right: forall c,
cequiv
(c;; SKIP)
c.
Proof.
intros c st st'.
split; intros.
inversion H. inversion H5.
rewrite H8 in H2. auto.
apply E_Seq with st'. auto.
apply E_Skip.
Qed.
Theorem IFB_true_simple: forall c1 c2,
cequiv
(IFB BTrue THEN c1 ELSE c2 FI)
c1.
Proof.
intros c1 c2 st st'.
split; intros H.
inversion H; try inversion H5; try auto.
apply E_IfTrue; auto.
Qed.
Theorem IFB_true: forall b c1 c2,
bequiv b BTrue ->
cequiv
(IFB b THEN c1 ELSE c2 FI)
c1.
Proof.
intros b c1 c2 Hb.
split; intros H.
Case "->".
inversion H; subst.
SCase "b evaluates to true".
assumption.
SCase "b evaluates to false (contradiction)".
rewrite Hb in H5.
inversion H5.
Case "<-".
apply E_IfTrue; try assumption.
rewrite Hb. reflexivity. Qed.
Theorem IFB_false: forall b c1 c2,
bequiv b BFalse ->
cequiv
(IFB b THEN c1 ELSE c2 FI)
c2.
Proof.
intros b c1 c2 Hb.
split; intros H.
inversion H; subst.
rewrite Hb in H5. inversion H5.
auto.
apply E_IfFalse; try rewrite Hb; auto.
Qed.
Theorem swap_if_branches: forall b e1 e2,
cequiv
(IFB b THEN e1 ELSE e2 FI)
(IFB BNot b THEN e2 ELSE e1 FI).
Proof.
intros b e1 e2; split; intros H; inversion H; subst.
apply E_IfFalse; simpl; try rewrite H5; try auto.
apply E_IfTrue; simpl; try rewrite H5; try auto.
apply E_IfFalse; inversion H5; destruct (beval st b); inversion H1; auto.
apply E_IfTrue; inversion H5; destruct (beval st b); inversion H1; auto.
Qed.
Theorem WHILE_false : forall b c,
bequiv b BFalse ->
cequiv
(WHILE b DO c END)
SKIP.
Proof.
intros b c Hb st st'.
split; intros H.
inversion H; subst; try apply E_Skip; rewrite Hb in H2; inversion H2.
inversion H; apply E_WhileEnd; rewrite Hb; auto.
Qed.
Lemma WHILE_true_nonterm : forall b c st st',
bequiv b BTrue ->
~( (WHILE b DO c END) / st || st' ).
Proof.
(* WORKED IN CLASS *)
intros b c st st' Hb.
intros H.
remember (WHILE b DO c END) as cw eqn:Heqcw.
ceval_cases (induction H) Case;
(* Most rules don't apply, and we can rule them out
by inversion *)
inversion Heqcw; subst; clear Heqcw.
(* The two interesting cases are the ones for WHILE loops: *)
Case "E_WhileEnd". (* contradictory -- b is always true! *)
unfold bequiv in Hb.
(* rewrite is able to instantiate the quantifier in st *)
rewrite Hb in H. inversion H.
Case "E_WhileLoop". (* immediate from the IH *)
apply IHceval2. reflexivity. Qed.
Theorem WHILE_true: forall b c,
bequiv b BTrue ->
cequiv
(WHILE b DO c END)
(WHILE BTrue DO SKIP END).
Proof.
intros b c Hb st st'.
split; intros. assert (~(WHILE b DO c END) / st || st').
apply WHILE_true_nonterm. auto.
apply H0 in H. inversion H.
assert (~(WHILE BTrue DO SKIP END) / st || st').
apply loop_stop. auto.
apply H0 in H. inversion H.
Qed.
Theorem loop_unrolling: forall b c,
cequiv
(WHILE b DO c END)
(IFB b THEN (c;; WHILE b DO c END) ELSE SKIP FI).
Proof.
intros b c st st'.
split; intros H.
inversion H; subst.
apply E_IfFalse; auto; try apply E_Skip.
apply E_IfTrue; auto; try apply E_Seq with st'0; auto.
inversion H; subst; inversion H6; subst.
apply E_WhileLoop with st'0; auto.
apply E_WhileEnd. auto.
Qed.
Theorem seq_assoc : forall c1 c2 c3,
cequiv ((c1;;c2);;c3) (c1;;(c2;;c3)).
Proof.
intros c1 c2 c3 st st'; split; intros H.
inversion H; subst; inversion H2; subst.
apply E_Seq with st'1; auto.
apply E_Seq with st'0; auto.
inversion H; subst; inversion H5; subst.
apply E_Seq with st'1; auto.
apply E_Seq with st'0; auto.
Qed.
Axiom functional_extensionality : forall {X Y: Type} {f g : X -> Y},
(forall (x: X), f x = g x) -> f = g.
Theorem identity_assignment : forall (X:id),
cequiv
(X ::= AId X)
SKIP.
Proof.
intros. split; intro H.
Case "->".
inversion H; subst. simpl.
replace (update st X (st X)) with st.
constructor.
apply functional_extensionality. intro.
rewrite update_same; reflexivity.
Case "<-".
inversion H; subst.
assert (st' = (update st' X (st' X))).
apply functional_extensionality. intro.
rewrite update_same; reflexivity.
rewrite H0 at 2.
constructor. reflexivity.
Qed.
Theorem assign_aequiv : forall X e,
aequiv (AId X) e ->
cequiv SKIP (X ::= e).
Proof.
intros X e He st st';
split; intros H.
inversion H. replace ((X ::= e) / st' || st') with ((X ::= e) / st' || update st' X (aeval st' e)).
constructor; auto.
replace (update st' X (aeval st' e)) with st'.
auto. apply functional_extensionality. intro.
rewrite update_same; auto; apply He.
inversion H; subst.
replace (update st X (aeval st e)) with st.
constructor.
apply functional_extensionality. intro.
rewrite update_same; auto.
apply He.
Qed.
Lemma refl_aequiv : forall (a : aexp), aequiv a a.
Proof.
intros a st. auto. Qed.
Lemma sym_aequiv : forall (a1 a2 : aexp),
aequiv a1 a2 -> aequiv a2 a1.
Proof.
intros a1 a2 H st. symmetry. apply H. Qed.
Lemma trans_aequiv : forall (a1 a2 a3 : aexp),
aequiv a1 a2 -> aequiv a2 a3 -> aequiv a1 a3.
Proof.
intros a1 a2 a3 H1 H2 st. rewrite H1. auto. Qed.
Lemma refl_bequiv : forall (b : bexp), bequiv b b.
Proof.
intros b st. auto. Qed.
Lemma sym_bequiv : forall (b1 b2 : bexp),
bequiv b1 b2 -> bequiv b2 b1.
Proof.
intros b1 b2 H st. auto. Qed.
Lemma trans_bequiv : forall (b1 b2 b3 : bexp),
bequiv b1 b2 -> bequiv b2 b3 -> bequiv b1 b3.
Proof.
intros b1 b2 b3 H1 H2 st. rewrite H1. auto. Qed.
Lemma refl_cequiv : forall (c : com), cequiv c c.
Proof.
intros c st; split; intros H; auto. Qed.
Lemma sym_cequiv : forall (c1 c2 : com),
cequiv c1 c2 -> cequiv c2 c1.
Proof.
intros c1 c2 H st; split; apply H. Qed.
Lemma iff_trans : forall (P1 P2 P3 : Prop),
(P1 <-> P2) -> (P2 <-> P3) -> (P1 <-> P3).
Proof.
intros P1 P2 P3 H1 H2; split.
rewrite H1. apply H2.
rewrite <- H2. apply H1.
Qed.
Lemma trans_cequiv : forall (c1 c2 c3 : com),
cequiv c1 c2 -> cequiv c2 c3 -> cequiv c1 c3.
Proof.
intros c1 c2 c3 H1 H2 st; split; intros H.
apply H2. apply H1. apply H.
apply H1. apply H2. apply H.
Qed.
Theorem CAss_congruence : forall i a1 a1',
aequiv a1 a1' ->
cequiv (CAss i a1) (CAss i a1').
Proof.
intros; split; intro;
inversion H0; subst; apply E_Ass; rewrite H; auto.
Qed.
Theorem CWhile_congruence : forall b1 b1' c1 c1',
bequiv b1 b1' -> cequiv c1 c1' ->
cequiv (WHILE b1 DO c1 END) (WHILE b1' DO c1' END).
Proof.
(* WORKED IN CLASS *)
unfold bequiv,cequiv.
intros b1 b1' c1 c1' Hb1e Hc1e st st'.
split; intros Hce.
Case "->".
remember (WHILE b1 DO c1 END) as cwhile eqn:Heqcwhile.
induction Hce; inversion Heqcwhile; subst.
SCase "E_WhileEnd".
apply E_WhileEnd. rewrite <- Hb1e. apply H.
SCase "E_WhileLoop".
apply E_WhileLoop with (st' := st').
SSCase "show loop runs". rewrite <- Hb1e. apply H.
SSCase "body execution".
apply (Hc1e st st'). apply Hce1.
SSCase "subsequent loop execution".
apply IHHce2. reflexivity.
Case "<-".
remember (WHILE b1' DO c1' END) as c'while eqn:Heqc'while.
induction Hce; inversion Heqc'while; subst.
SCase "E_WhileEnd".
apply E_WhileEnd. rewrite -> Hb1e. apply H.
SCase "E_WhileLoop".
apply E_WhileLoop with (st' := st').
SSCase "show loop runs". rewrite -> Hb1e. apply H.
SSCase "body execution".
apply (Hc1e st st'). apply Hce1.
SSCase "subsequent loop execution".
apply IHHce2. reflexivity. Qed.
Theorem CSeq_congruence : forall c1 c1' c2 c2',
cequiv c1 c1' -> cequiv c2 c2' ->
cequiv (c1;;c2) (c1';;c2').
Proof.
intros c1 c1' c2 c2' H1 H2 st st';
split; intros H; inversion H; subst;
apply E_Seq with st'0; try apply H1; try apply H2; auto.
Qed.
Theorem CIf_congruence : forall b b' c1 c1' c2 c2',
bequiv b b' -> cequiv c1 c1' -> cequiv c2 c2' ->
cequiv (IFB b THEN c1 ELSE c2 FI) (IFB b' THEN c1' ELSE c2' FI).
Proof.
intros; split; intros Htmp; inversion Htmp; subst.
rewrite H in H7; apply E_IfTrue; auto; apply H0; auto.
rewrite H in H7; apply E_IfFalse; auto; apply H1; auto.
rewrite <- H in H7; apply E_IfTrue; auto; apply H0; auto.
rewrite <- H in H7; apply E_IfFalse; auto; apply H1; auto.
Qed.
Example congruence_example:
cequiv
(* Program 1: *)
(X ::= ANum 0;;
IFB (BEq (AId X) (ANum 0))
THEN
Y ::= ANum 0
ELSE
Y ::= ANum 42
FI)
(* Program 2: *)
(X ::= ANum 0;;
IFB (BEq (AId X) (ANum 0))
THEN
Y ::= AMinus (AId X) (AId X) (* <--- changed here *)
ELSE
Y ::= ANum 42
FI).
Proof.
apply CSeq_congruence.
apply refl_cequiv.
apply CIf_congruence.
apply refl_bequiv.
apply CAss_congruence. unfold aequiv. simpl.
symmetry. apply minus_diag.
apply refl_cequiv.
Qed.
Definition atrans_sound (atrans : aexp -> aexp) : Prop :=
forall (a : aexp),
aequiv a (atrans a).
Definition btrans_sound (btrans : bexp -> bexp) : Prop :=
forall (b : bexp),
bequiv b (btrans b).
Definition ctrans_sound (ctrans : com -> com) : Prop :=
forall (c : com),
cequiv c (ctrans c).
Fixpoint fold_constants_aexp (a : aexp) : aexp :=
match a with
| ANum n => ANum n
| AId i => AId i
| APlus a1 a2 =>
match (fold_constants_aexp a1, fold_constants_aexp a2) with
| (ANum n1, ANum n2) => ANum (n1 + n2)
| (a1', a2') => APlus a1' a2'
end
| AMinus a1 a2 =>
match (fold_constants_aexp a1, fold_constants_aexp a2) with
| (ANum n1, ANum n2) => ANum (n1 - n2)
| (a1', a2') => AMinus a1' a2'
end
| AMult a1 a2 =>
match (fold_constants_aexp a1, fold_constants_aexp a2) with
| (ANum n1, ANum n2) => ANum (n1 * n2)
| (a1', a2') => AMult a1' a2'
end
end.
Example fold_aexp_ex1 :
fold_constants_aexp
(AMult (APlus (ANum 1) (ANum 2)) (AId X))
= AMult (ANum 3) (AId X).
Proof. reflexivity. Qed.
Example fold_aexp_ex2 :
fold_constants_aexp
(AMinus (AId X) (APlus (AMult (ANum 0) (ANum 6)) (AId Y)))
= AMinus (AId X) (APlus (ANum 0) (AId Y)).
Proof. reflexivity. Qed.
Fixpoint fold_constants_bexp (b : bexp) : bexp :=
match b with
| BTrue => BTrue
| BFalse => BFalse
| BEq a1 a2 =>
match (fold_constants_aexp a1, fold_constants_aexp a2) with
| (ANum n1, ANum n2) => if beq_nat n1 n2 then BTrue else BFalse
| (a1', a2') => BEq a1' a2'
end
| BLe a1 a2 =>
match (fold_constants_aexp a1, fold_constants_aexp a2) with
| (ANum n1, ANum n2) => if ble_nat n1 n2 then BTrue else BFalse
| (a1', a2') => BLe a1' a2'
end
| BNot b1 =>
match (fold_constants_bexp b1) with
| BTrue => BFalse
| BFalse => BTrue
| b1' => BNot b1'
end
| BAnd b1 b2 =>
match (fold_constants_bexp b1, fold_constants_bexp b2) with
| (BTrue, BTrue) => BTrue
| (BTrue, BFalse) => BFalse
| (BFalse, BTrue) => BFalse
| (BFalse, BFalse) => BFalse
| (b1', b2') => BAnd b1' b2'
end
end.
Example fold_bexp_ex1 :
fold_constants_bexp (BAnd BTrue (BNot (BAnd BFalse BTrue)))
= BTrue.
Proof. reflexivity. Qed.
Example fold_bexp_ex2 :
fold_constants_bexp
(BAnd (BEq (AId X) (AId Y))
(BEq (ANum 0)
(AMinus (ANum 2) (APlus (ANum 1) (ANum 1)))))
= BAnd (BEq (AId X) (AId Y)) BTrue.
Proof. reflexivity. Qed.
Fixpoint fold_constants_com (c : com) : com :=
match c with
| SKIP =>
SKIP
| i ::= a =>
CAss i (fold_constants_aexp a)
| c1 ;; c2 =>
(fold_constants_com c1) ;; (fold_constants_com c2)
| IFB b THEN c1 ELSE c2 FI =>
match fold_constants_bexp b with
| BTrue => fold_constants_com c1
| BFalse => fold_constants_com c2
| b' => IFB b' THEN fold_constants_com c1
ELSE fold_constants_com c2 FI
end
| WHILE b DO c END =>
match fold_constants_bexp b with
| BTrue => WHILE BTrue DO SKIP END
| BFalse => SKIP
| b' => WHILE b' DO (fold_constants_com c) END
end
end.
Example fold_com_ex1 :
fold_constants_com
(* Original program: *)
(X ::= APlus (ANum 4) (ANum 5);;
Y ::= AMinus (AId X) (ANum 3);;
IFB BEq (AMinus (AId X) (AId Y)) (APlus (ANum 2) (ANum 4)) THEN
SKIP
ELSE
Y ::= ANum 0
FI;;
IFB BLe (ANum 0) (AMinus (ANum 4) (APlus (ANum 2) (ANum 1))) THEN
Y ::= ANum 0
ELSE
SKIP
FI;;
WHILE BEq (AId Y) (ANum 0) DO
X ::= APlus (AId X) (ANum 1)
END)
= (* After constant folding: *)
(X ::= ANum 9;;
Y ::= AMinus (AId X) (ANum 3);;
IFB BEq (AMinus (AId X) (AId Y)) (ANum 6) THEN
SKIP
ELSE
(Y ::= ANum 0)
FI;;
Y ::= ANum 0;;
WHILE BEq (AId Y) (ANum 0) DO
X ::= APlus (AId X) (ANum 1)
END).
Proof. reflexivity. Qed.
Theorem fold_constants_aexp_sound :
atrans_sound fold_constants_aexp.
Proof.
intros a st.
induction a; try auto; simpl;
remember (fold_constants_aexp a1) as af1;
destruct af1;
remember (fold_constants_aexp a2) as af2;
destruct af2; rewrite IHa1; rewrite IHa2; auto.
Qed.
Theorem fold_constants_bexp_sound:
btrans_sound fold_constants_bexp.
Proof.
unfold btrans_sound. intros b. unfold bequiv. intros st.
bexp_cases (induction b) Case;
(* BTrue and BFalse are immediate *)
try reflexivity.
Case "BEq".
(* Doing induction when there are a lot of constructors makes
specifying variable names a chore, but Coq doesn't always
choose nice variable names. We can rename entries in the
context with the rename tactic: rename a into a1 will
change a to a1 in the current goal and context. *)
rename a into a1. rename a0 into a2. simpl.
remember (fold_constants_aexp a1) as a1' eqn:Heqa1'.
remember (fold_constants_aexp a2) as a2' eqn:Heqa2'.
replace (aeval st a1) with (aeval st a1') by
(subst a1'; rewrite <- fold_constants_aexp_sound; reflexivity).
replace (aeval st a2) with (aeval st a2') by
(subst a2'; rewrite <- fold_constants_aexp_sound; reflexivity).
destruct a1'; destruct a2'; try reflexivity.
(* The only interesting case is when both a1 and a2
become constants after folding *)
simpl. destruct (beq_nat n n0); reflexivity.
Case "BLe".
simpl.
rewrite -> fold_constants_aexp_sound.
replace (aeval st a0) with (aeval st (fold_constants_aexp a0)).
remember (fold_constants_aexp a) as af;
remember (fold_constants_aexp a0) as af0;
destruct af; simpl; try auto.
destruct af0; simpl; try auto.
destruct (ble_nat n n0); auto.
rewrite <- fold_constants_aexp_sound. auto.
Case "BNot".
simpl. remember (fold_constants_bexp b) as b' eqn:Heqb'.
rewrite IHb.
destruct b'; reflexivity.
Case "BAnd".
simpl.
remember (fold_constants_bexp b1) as b1' eqn:Heqb1'.
remember (fold_constants_bexp b2) as b2' eqn:Heqb2'.
rewrite IHb1. rewrite IHb2.
destruct b1'; destruct b2'; reflexivity. Qed.
Theorem fold_constants_com_sound :
ctrans_sound fold_constants_com.
Proof.
unfold ctrans_sound. intros c.
com_cases (induction c) Case; simpl.
Case "SKIP". apply refl_cequiv.
Case "::=". apply CAss_congruence. apply fold_constants_aexp_sound.
Case ";;". apply CSeq_congruence; assumption.
Case "IFB".
assert (bequiv b (fold_constants_bexp b)).
SCase "Pf of assertion". apply fold_constants_bexp_sound.
destruct (fold_constants_bexp b) eqn:Heqb;
(* If the optimization doesn't eliminate the if, then the result
is easy to prove from the IH and fold_constants_bexp_sound *)
try (apply CIf_congruence; assumption).
SCase "b always true".
apply trans_cequiv with c1; try assumption.
apply IFB_true; assumption.
SCase "b always false".
apply trans_cequiv with c2; try assumption.
apply IFB_false; assumption.
Case "WHILE".
assert (bequiv b (fold_constants_bexp b)).
apply fold_constants_bexp_sound.
destruct (fold_constants_bexp b) eqn:Heqb.
apply WHILE_true; auto.
apply WHILE_false; auto.
try apply CWhile_congruence; auto.
try apply CWhile_congruence; auto.
try apply CWhile_congruence; auto.
try apply CWhile_congruence; auto.
Qed.
Fixpoint optimize_0plus_aexp (e:aexp) : aexp :=
match e with
| ANum n =>
ANum n
| AId i => AId i
| APlus (ANum 0) e2 =>
optimize_0plus_aexp e2
| APlus e1 e2 =>
APlus (optimize_0plus_aexp e1) (optimize_0plus_aexp e2)
| AMinus e1 e2 =>
AMinus (optimize_0plus_aexp e1) (optimize_0plus_aexp e2)
| AMult e1 e2 =>
AMult (optimize_0plus_aexp e1) (optimize_0plus_aexp e2)
end.
Fixpoint optimize_0plus_bexp (b : bexp) : bexp :=
match b with
| BTrue => BTrue
| BFalse => BFalse
| BEq a1 a2 => BEq (optimize_0plus_aexp a1) (optimize_0plus_aexp a2)
| BLe a1 a2 => BLe (optimize_0plus_aexp a1) (optimize_0plus_aexp a2)
| BNot b1 => BNot (optimize_0plus_bexp b1)
| BAnd b1 b2 => BAnd (optimize_0plus_bexp b1) (optimize_0plus_bexp b2)
end.
Fixpoint optimize_0plus_com (c : com) : com :=
match c with
| SKIP =>
SKIP
| i ::= a =>
CAss i (optimize_0plus_aexp a)
| c1 ;; c2 =>
(optimize_0plus_com c1) ;; (optimize_0plus_com c2)
| IFB b THEN c1 ELSE c2 FI =>
IFB (optimize_0plus_bexp b) THEN optimize_0plus_com c1
ELSE optimize_0plus_com c2 FI
| WHILE b DO c END =>
WHILE (optimize_0plus_bexp b) DO (optimize_0plus_com c) END
end.
Theorem optimize_0plus_aexp_sound :
atrans_sound optimize_0plus_aexp.
Proof.
intros a st.
induction a; simpl; try auto.
destruct a1 eqn:Heqa1; try simpl; auto.
destruct n; simpl; auto.
Qed.
Theorem optimize_0plus_bexp_sound:
btrans_sound optimize_0plus_bexp.
Proof.
intros b st.
induction b; try auto;
simpl; try rewrite <- optimize_0plus_aexp_sound;
try rewrite <- optimize_0plus_aexp_sound; auto.
rewrite IHb; auto.
rewrite IHb1; rewrite IHb2; auto.
Qed.
Theorem optimize_0plus_com_sound :
ctrans_sound optimize_0plus_com.
Proof.
unfold ctrans_sound. intros c.
induction c; simpl.
split; auto.
apply CAss_congruence. apply optimize_0plus_aexp_sound.
apply CSeq_congruence; auto.
apply CIf_congruence; auto; try apply optimize_0plus_bexp_sound.
apply CWhile_congruence; auto; try apply optimize_0plus_bexp_sound.
Qed.
Definition optimizer_0plus_const_com (c : com) : com :=
optimize_0plus_com (fold_constants_com c).
Example optexam1 :
optimizer_0plus_const_com
(* Original program: *)
(X ::= APlus (ANum 4) (ANum 5);;
X ::= APlus (ANum 0) (AId X);;
Y ::= AMinus (AId X) (ANum 3);;
IFB BEq (AMinus (AId X) (AId Y)) (APlus (ANum 2) (ANum 4)) THEN
SKIP
ELSE
Y ::= ANum 0
FI;;
IFB BLe (ANum 0) (AMinus (ANum 4) (APlus (ANum 2) (ANum 1))) THEN
Y ::= ANum 0
ELSE
SKIP
FI;;
WHILE BEq (AId Y) (ANum 0) DO
X ::= APlus (AId X) (ANum 1)
END)
= (* After constant folding: *)
(X ::= ANum 9;;
X ::= AId X;;
Y ::= AMinus (AId X) (ANum 3);;
IFB BEq (AMinus (AId X) (AId Y)) (ANum 6) THEN
SKIP
ELSE
(Y ::= ANum 0)
FI;;
Y ::= ANum 0;;
WHILE BEq (AId Y) (ANum 0) DO
X ::= APlus (AId X) (ANum 1)
END).
Proof. reflexivity. Qed.
Theorem optimizer_0plus_const_com_sound :
ctrans_sound optimizer_0plus_const_com.
Proof.
unfold ctrans_sound.
intro.
unfold optimizer_0plus_const_com.
split.
intro.
apply fold_constants_com_sound in H.
apply optimize_0plus_com_sound in H.
auto.
intros.
apply fold_constants_com_sound.
apply optimize_0plus_com_sound.
auto.
Qed.
Fixpoint subst_aexp (i : id) (u : aexp) (a : aexp) : aexp :=
match a with
| ANum n => ANum n
| AId i' => if eq_id_dec i i' then u else AId i'
| APlus a1 a2 => APlus (subst_aexp i u a1) (subst_aexp i u a2)
| AMinus a1 a2 => AMinus (subst_aexp i u a1) (subst_aexp i u a2)
| AMult a1 a2 => AMult (subst_aexp i u a1) (subst_aexp i u a2)
end.
Example subst_aexp_ex :
subst_aexp X (APlus (ANum 42) (ANum 53)) (APlus (AId Y) (AId X)) =
(APlus (AId Y) (APlus (ANum 42) (ANum 53))).
Proof. reflexivity. Qed.
Definition subst_equiv_property := forall i1 i2 a1 a2,
cequiv (i1 ::= a1;; i2 ::= a2)
(i1 ::= a1;; i2 ::= subst_aexp i1 a1 a2).
Theorem subst_inequiv :
~ subst_equiv_property.
Proof.
unfold subst_equiv_property.
intros Contra.
(* Here is the counterexample: assuming that subst_equiv_property
holds allows us to prove that these two programs are
equivalent... *)
remember (X ::= APlus (AId X) (ANum 1);;
Y ::= AId X)
as c1.
remember (X ::= APlus (AId X) (ANum 1);;
Y ::= APlus (AId X) (ANum 1))
as c2.
assert (cequiv c1 c2) by (subst; apply Contra).
(* ... allows us to show that the command c2 can terminate
in two different final states:
st1 = {X |-> 1, Y |-> 1}
st2 = {X |-> 1, Y |-> 2}. *)
remember (update (update empty_state X 1) Y 1) as st1.
remember (update (update empty_state X 1) Y 2) as st2.
assert (H1: c1 / empty_state || st1);
assert (H2: c2 / empty_state || st2);
try (subst;
apply E_Seq with (st' := (update empty_state X 1));
apply E_Ass; reflexivity).
apply H in H1.
(* Finally, we use the fact that evaluation is deterministic
to obtain a contradiction. *)
assert (Hcontra: st1 = st2)
by (apply (ceval_deterministic c2 empty_state); assumption).
assert (Hcontra': st1 Y = st2 Y)
by (rewrite Hcontra; reflexivity).
subst. inversion Hcontra'. Qed.
Inductive var_not_used_in_aexp (X:id) : aexp -> Prop :=
| VNUNum: forall n, var_not_used_in_aexp X (ANum n)
| VNUId: forall Y, X <> Y -> var_not_used_in_aexp X (AId Y)
| VNUPlus: forall a1 a2,
var_not_used_in_aexp X a1 ->
var_not_used_in_aexp X a2 ->
var_not_used_in_aexp X (APlus a1 a2)
| VNUMinus: forall a1 a2,
var_not_used_in_aexp X a1 ->
var_not_used_in_aexp X a2 ->
var_not_used_in_aexp X (AMinus a1 a2)
| VNUMult: forall a1 a2,
var_not_used_in_aexp X a1 ->
var_not_used_in_aexp X a2 ->
var_not_used_in_aexp X (AMult a1 a2).
Lemma aeval_weakening : forall i st a ni,
var_not_used_in_aexp i a ->
aeval (update st i ni) a = aeval st a.
Proof.
intros.
induction a; inversion H; simpl; try auto; try rewrite IHa1; try rewrite IHa2; auto.
apply neq_id. auto.
Qed.
Definition subst_equiv_property' := forall i1 i2 a1 a2,
var_not_used_in_aexp i1 a1 ->
cequiv (i1 ::= a1;; i2 ::= a2)
(i1 ::= a1;; i2 ::= subst_aexp i1 a1 a2).
Theorem subst_equiv :
subst_equiv_property'.
Proof.
intros i1 i2 a1 a2 H.
split; intro; inversion H0; subst.
apply E_Seq with st'0; auto. clear H0.
generalize dependent st'.
induction a2. intros. simpl. auto.
intros; inversion H6; subst; simpl; try apply E_Ass; auto; simpl; try rewrite IHa2_1.
destruct (eq_id_dec i1 i) eqn:eqid; auto.
inversion H3; subst.
simpl. rewrite aeval_weakening; auto. unfold update. rewrite eq_id. auto.
intros. inversion H6; subst.
assert((i2 ::= subst_aexp i1 a1 a2_1) / st'0
|| update st'0 i2 (aeval st'0 a2_1)). apply IHa2_1. constructor. auto.
assert((i2 ::= subst_aexp i1 a1 a2_2) / st'0
|| update st'0 i2 (aeval st'0 a2_2)). apply IHa2_2. constructor. auto.
simpl. apply E_Ass. simpl.
assert(aeval st'0 (subst_aexp i1 a1 a2_1) = aeval st'0 a2_1).
inversion H0. rewrite H7.
assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_1) i2).
rewrite H8; auto.
rewrite update_eq in H9. rewrite update_eq in H9. auto.
assert(aeval st'0 (subst_aexp i1 a1 a2_2) = aeval st'0 a2_2).
inversion H1. rewrite H8.
assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_2) i2).
rewrite H9; auto.
rewrite update_eq in H10. rewrite update_eq in H10. auto.
rewrite H2. rewrite H4. auto.
intros.
assert((i2 ::= subst_aexp i1 a1 a2_1) / st'0
|| update st'0 i2 (aeval st'0 a2_1)). apply IHa2_1. constructor. auto.
assert((i2 ::= subst_aexp i1 a1 a2_2) / st'0
|| update st'0 i2 (aeval st'0 a2_2)). apply IHa2_2. constructor. auto.
inversion H6; subst. simpl. apply E_Ass. simpl.
assert(aeval st'0 (subst_aexp i1 a1 a2_1) = aeval st'0 a2_1).
inversion H0. rewrite H7.
assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_1) i2).
rewrite H8; auto.
rewrite update_eq in H9. rewrite update_eq in H9. auto.
assert(aeval st'0 (subst_aexp i1 a1 a2_2) = aeval st'0 a2_2).
inversion H1. rewrite H8.
assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_2) i2).
rewrite H9; auto.
rewrite update_eq in H10. rewrite update_eq in H10. auto.
rewrite H2. rewrite H4. auto. intros.
assert((i2 ::= subst_aexp i1 a1 a2_1) / st'0
|| update st'0 i2 (aeval st'0 a2_1)). apply IHa2_1. constructor. auto.
assert((i2 ::= subst_aexp i1 a1 a2_2) / st'0
|| update st'0 i2 (aeval st'0 a2_2)). apply IHa2_2. constructor. auto.
inversion H6; subst. simpl. apply E_Ass. simpl.
assert(aeval st'0 (subst_aexp i1 a1 a2_1) = aeval st'0 a2_1).
inversion H0. rewrite H7.
assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_1) i2).
rewrite H8; auto.
rewrite update_eq in H9. rewrite update_eq in H9. auto.
assert(aeval st'0 (subst_aexp i1 a1 a2_2) = aeval st'0 a2_2).
inversion H1. rewrite H8.
assert (update st'0 i2 n i2 = update st'0 i2 (aeval st'0 a2_2) i2).
rewrite H9; auto.
rewrite update_eq in H10. rewrite update_eq in H10. auto.
rewrite H2. rewrite H4. auto. intros.
apply E_Seq with st'0. auto.
generalize dependent st'.
induction a2; intros; inversion H6; subst; auto. destruct (eq_id_dec i1 i).
apply E_Ass. rewrite <- e. inversion H3; subst.
assert(aeval (update st i (aeval st a1)) a1 = aeval st a1).
rewrite aeval_weakening; auto.
rewrite H1. simpl. apply update_eq.
apply E_Ass. auto.
assert((i2 ::= a2_1) / st'0 || update st'0 i2
(aeval st'0 (subst_aexp i1 a1 a2_1))).
apply IHa2_1. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto.
assert((i2 ::= a2_2) / st'0 || update st'0 i2
(aeval st'0 (subst_aexp i1 a1 a2_2))).
apply IHa2_2. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto.
inversion H1; subst. inversion H2; subst. apply E_Ass. simpl.
assert(aeval st'0 a2_1 = aeval st'0 (subst_aexp i1 a1 a2_1)).
symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry.
rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H9. auto.
assert(aeval st'0 a2_2 = aeval st'0 (subst_aexp i1 a1 a2_2)).
symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry.
rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H10. auto.
rewrite <- H4. rewrite <- H5. auto.
assert((i2 ::= a2_1) / st'0 || update st'0 i2
(aeval st'0 (subst_aexp i1 a1 a2_1))).
apply IHa2_1. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto.
assert((i2 ::= a2_2) / st'0 || update st'0 i2
(aeval st'0 (subst_aexp i1 a1 a2_2))).
apply IHa2_2. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto.
inversion H1; subst. inversion H2; subst. apply E_Ass. simpl.
assert(aeval st'0 a2_1 = aeval st'0 (subst_aexp i1 a1 a2_1)).
symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry.
rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H9. auto.
assert(aeval st'0 a2_2 = aeval st'0 (subst_aexp i1 a1 a2_2)).
symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry.
rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H10. auto.
rewrite <- H4. rewrite <- H5. auto.
assert((i2 ::= a2_1) / st'0 || update st'0 i2
(aeval st'0 (subst_aexp i1 a1 a2_1))).
apply IHa2_1. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto.
assert((i2 ::= a2_2) / st'0 || update st'0 i2
(aeval st'0 (subst_aexp i1 a1 a2_2))).
apply IHa2_2. apply E_Seq with st'0. auto. apply E_Ass. auto. apply E_Ass. auto.
inversion H1; subst. inversion H2; subst. apply E_Ass. simpl.
assert(aeval st'0 a2_1 = aeval st'0 (subst_aexp i1 a1 a2_1)).
symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry.
rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H9. auto.
assert(aeval st'0 a2_2 = aeval st'0 (subst_aexp i1 a1 a2_2)).
symmetry. rewrite <- update_eq with (X:=i2) (st:=st'0). symmetry.
rewrite <- update_eq with (X:=i2) (st:=st'0). rewrite H10. auto.
rewrite <- H4. rewrite <- H5. auto.
Qed.
Theorem inequiv_exercise:
~ cequiv (WHILE BTrue DO SKIP END) SKIP.
Proof.
intros contra.
unfold cequiv in contra.
assert(forall st: state, SKIP / st || st).
intros. apply E_Skip.
assert(forall st: state, (WHILE BTrue DO SKIP END) / st || st).
intros; apply contra; apply H.
assert(forall st: state, ~((WHILE BTrue DO SKIP END) / st || st)).
intros. apply loop_never_stops.
assert((WHILE BTrue DO SKIP END) / empty_state || empty_state -> False).
apply H1. apply H2. apply H0.
Qed.
Module Himp.
Inductive com : Type :=
| CSkip : com
| CAss : id -> aexp -> com
| CSeq : com -> com -> com
| CIf : bexp -> com -> com -> com
| CWhile : bexp -> com -> com
| CHavoc : id -> com.
Tactic Notation "com_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "SKIP" | Case_aux c "::=" | Case_aux c ";;"
| Case_aux c "IFB" | Case_aux c "WHILE" | Case_aux c "HAVOC" ].
Notation "'SKIP'" :=
CSkip.
Notation "X '::=' a" :=
(CAss X a) (at level 60).
Notation "c1 ;; c2" :=
(CSeq c1 c2) (at level 80, right associativity).
Notation "'WHILE' b 'DO' c 'END'" :=
(CWhile b c) (at level 80, right associativity).
Notation "'IFB' e1 'THEN' e2 'ELSE' e3 'FI'" :=
(CIf e1 e2 e3) (at level 80, right associativity).
Notation "'HAVOC' l" := (CHavoc l) (at level 60).
Reserved Notation "c1 '/' st '||' st'" (at level 40, st at level 39).
Inductive ceval : com -> state -> state -> Prop :=
| E_Skip : forall st : state, SKIP / st || st
| E_Ass : forall (st : state) (a1 : aexp) (n : nat) (X : id),
aeval st a1 = n -> (X ::= a1) / st || update st X n
| E_Seq : forall (c1 c2 : com) (st st' st'' : state),
c1 / st || st' -> c2 / st' || st'' -> (c1 ;; c2) / st || st''
| E_IfTrue : forall (st st' : state) (b1 : bexp) (c1 c2 : com),
beval st b1 = true ->
c1 / st || st' -> (IFB b1 THEN c1 ELSE c2 FI) / st || st'
| E_IfFalse : forall (st st' : state) (b1 : bexp) (c1 c2 : com),
beval st b1 = false ->
c2 / st || st' -> (IFB b1 THEN c1 ELSE c2 FI) / st || st'
| E_WhileEnd : forall (b1 : bexp) (st : state) (c1 : com),
beval st b1 = false -> (WHILE b1 DO c1 END) / st || st
| E_WhileLoop : forall (st st' st'' : state) (b1 : bexp) (c1 : com),
beval st b1 = true ->
c1 / st || st' ->
(WHILE b1 DO c1 END) / st' || st'' ->
(WHILE b1 DO c1 END) / st || st''
| E_Havoc : forall (st : state) (n : nat) (X : id),
(HAVOC X) / st || update st X n
where "c1 '/' st '||' st'" := (ceval c1 st st').
Tactic Notation "ceval_cases" tactic(first) ident(c) :=
first;
[ Case_aux c "E_Skip" | Case_aux c "E_Ass" | Case_aux c "E_Seq"
| Case_aux c "E_IfTrue" | Case_aux c "E_IfFalse"
| Case_aux c "E_WhileEnd" | Case_aux c "E_WhileLoop"
| Case_aux c "E_Havoc" ].
Example havoc_example1 : (HAVOC X) / empty_state || update empty_state X 0.
Proof.
apply E_Havoc. Qed.
Example havoc_example2 :
(SKIP;; HAVOC Z) / empty_state || update empty_state Z 42.
Proof.
apply E_Seq with empty_state.
apply E_Skip.
apply E_Havoc.
Qed.
Definition cequiv (c1 c2 : com) : Prop := forall st st' : state,
c1 / st || st' <-> c2 / st || st'.
Definition pXY :=
HAVOC X;; HAVOC Y.
Definition pYX :=
HAVOC Y;; HAVOC X.
Theorem update_swap: forall st X Y n n0,
X<>Y->update (update st X n) Y n0 = update (update st Y n0) X n.
Proof.
intros. apply functional_extensionality.
intros. simpl.
unfold update.
destruct (eq_id_dec Y x); try auto.
destruct (eq_id_dec X x); try auto; try subst.
unfold not in H. assert (x=x).
auto. apply H in H0. inversion H0.
Qed.
Theorem pXY_cequiv_pYX :
cequiv pXY pYX \/ ~cequiv pXY pYX.
Proof.
apply or_introl.
intros st st'; split; intros H;
inversion H; subst; inversion H2; subst;
inversion H5; subst;
destruct (eq_id_dec X Y) eqn:eqid;
inversion eqid; rewrite update_swap; auto.
apply E_Seq with (update st Y n0);
apply E_Havoc.
apply E_Seq with (update st X n0);
apply E_Havoc.
Qed.
Definition ptwice :=
HAVOC X;; HAVOC Y.
Definition pcopy :=
HAVOC X;; Y ::= AId X.
Theorem ptwice_cequiv_pcopy :
cequiv ptwice pcopy \/ ~cequiv ptwice pcopy.
Proof.
apply or_intror.
unfold not.
intro. unfold cequiv in H.
assert(ptwice / empty_state || update (update empty_state X 0) Y (S 0)
<-> pcopy / empty_state || update (update empty_state X 0) Y (S 0)).
apply H. clear H.
destruct (eq_id_dec X Y) eqn:eqid.
inversion eqid.
inversion H0 as [H1 H2].
clear H0.
assert(pcopy / empty_state || update (update empty_state X 0) Y 1).
apply H1. apply E_Seq with (update empty_state X 0);
apply E_Havoc.
clear H1. clear H2.
assert((HAVOC X) / empty_state || update empty_state X 0).
apply E_Havoc.
inversion H; subst. inversion H3; subst.
inversion H6; subst. simpl in H7.
destruct n0.
assert(update (update empty_state X 0) Y (update empty_state X 0 X) Y = update (update empty_state X 0) Y 1 Y).
rewrite H7. auto. rewrite update_eq in H1. rewrite update_eq in H1.
rewrite update_eq in H1. inversion H1.
assert(update (update empty_state X (S n0)) Y (update empty_state X (S n0) X) X = update (update empty_state X 0) Y 1 X).
rewrite H7. auto. rewrite update_neq in H1; auto. rewrite update_eq in H1.
rewrite update_neq in H1; auto. rewrite update_eq in H1.
inversion H1.
Qed.
Definition p1 : com :=
WHILE (BNot (BEq (AId X) (ANum 0))) DO
HAVOC Y;;
X ::= APlus (AId X) (ANum 1)
END.
Definition p2 : com :=
WHILE (BNot (BEq (AId X) (ANum 0))) DO
SKIP
END.
Theorem p1_p2_equiv : cequiv p1 p2.
Proof.
intros st st'; split; intros; unfold p2.
unfold p1 in H.
destruct (eq_id_dec X Y) eqn:eq; inversion eq; subst.
inversion H; subst.
apply E_WhileEnd. auto.
remember (WHILE BNot (BEq (AId X) (ANum 0))
DO HAVOC Y;; X ::= APlus (AId X) (ANum 1) END) as loopdef eqn:loop.
assert (False).
clear H3 H6 st'0.
induction H; try inversion loop; subst.
rewrite H in H2. inversion H2.
apply IHceval2; try auto.
clear loop IHceval1 IHceval2.
inversion H0; subst. inversion H5; subst.
inversion H8; subst. simpl.
rewrite update_eq. rewrite update_neq; auto.
simpl in H2.
destruct (st X).
inversion H2.
simpl. auto.
inversion H0.
unfold p1; unfold p2 in H.
remember (st X) as stx.
destruct stx.
inversion H; subst.
apply E_WhileEnd. auto.
simpl in H2. rewrite <- Heqstx in H2.
simpl in H2. inversion H2.
assert(False).
remember (WHILE BNot (BEq (AId X) (ANum 0)) DO SKIP END)
as loopdef eqn:loop.
induction H; subst; try inversion loop.
rewrite H1 in H. simpl in H. rewrite <- Heqstx in H.
simpl in H. inversion H.
apply IHceval2; try auto.
rewrite H4 in H0.
inversion H0. subst. auto.
inversion H0.
Qed.
Definition p3 : com :=
Z ::= ANum 1;;
WHILE (BNot (BEq (AId X) (ANum 0))) DO
HAVOC X;;
HAVOC Z
END.
Definition p4 : com :=
X ::= (ANum 0);;
Z ::= (ANum 1).
Theorem p3_p4_inequiv : ~ cequiv p3 p4.
Proof.
intro. unfold cequiv in H.
assert(p3/update empty_state X 1||update (update (update (update empty_state X 1) Z 1) X 0) Z 0 <->
p4/update empty_state X 1||update (update (update (update empty_state X 1) Z 1) X 0) Z 0).
apply H. inversion H0 as [H1 H2].
clear H H0 H2.
assert(p3 / update empty_state X 1 || update (update (update (update empty_state X 1) Z 1) X 0) Z 0).
apply E_Seq with (update (update empty_state X 1) Z 1).
apply E_Ass. auto.
apply E_WhileLoop with (update (update (update (update empty_state X 1) Z 1) X 0) Z 0).
simpl. auto.
apply E_Seq with (update (update (update empty_state X 1) Z 1) X 0);
apply E_Havoc.
apply E_WhileEnd. simpl. auto.
apply H1 in H.
inversion H; subst. inversion H3; subst; simpl in H3.
simpl in H6. inversion H6; subst; simpl in H7.
assert (update (update (update empty_state X 1) X 0) Z 1 Z=
update (update (update (update empty_state X 1) Z 1) X 0) Z 0 Z).
rewrite H7. auto.
rewrite update_eq in H0. rewrite update_eq in H0.
inversion H0.
Qed.
Definition p5 : com :=
WHILE (BNot (BEq (AId X) (ANum 1))) DO
HAVOC X
END.
Definition p6 : com :=
X ::= ANum 1.
Theorem p5_p6_equiv : cequiv p5 p6.
Proof.
intros st st'. unfold p5. unfold p6.
split. intros.
remember (WHILE BNot (BEq (AId X) (ANum 1))
DO HAVOC X END) as loopdef eqn:loop.
induction H; inversion loop; subst.
inversion H.
unfold negb in H1. destruct (beq_nat (st X) 1) eqn:stx.
assert(st = update st X 1).
apply functional_extensionality. intros.
replace 1 with (st X). symmetry.
apply update_same. auto.
destruct (st X). inversion stx. destruct n.
auto. inversion stx.
assert((X ::= ANum 1) / st || update st X 1 -> (X ::= ANum 1) / st || st).
rewrite <- H0. auto. apply H2. apply E_Ass. auto.
inversion H1.
assert((X ::= ANum 1) / st' || st'').
apply IHceval2. auto. clear IHceval1 IHceval2.
inversion H0; subst. inversion H2; subst. simpl.
assert(update (update st X n) X 1 = update st X 1).
apply functional_extensionality. intros.
destruct (eq_id_dec X x) eqn:eqid; subst.
apply update_eq.
rewrite update_neq; auto.
rewrite update_neq; auto.
rewrite update_neq; auto.
rewrite H3.
apply E_Ass.
auto.
intro. inversion H; subst. simpl in H.
remember (st X) as stx.
destruct stx. apply E_WhileLoop with (update st X 1).
simpl. rewrite <- Heqstx. auto.
apply E_Havoc.
apply E_WhileEnd. simpl. auto.
destruct stx. simpl. replace (update st X 1) with st.
apply E_WhileEnd. simpl. rewrite <- Heqstx. auto.
apply functional_extensionality. intros.
destruct (eq_id_dec X x) eqn:eqid; subst.
rewrite update_eq. auto.
rewrite update_neq; auto.
apply E_WhileLoop with (update st X 1).
simpl; rewrite <- Heqstx; auto.
apply E_Havoc.
apply E_WhileEnd. simpl. auto.
Qed.
End Himp.
Definition stequiv (st1 st2 : state) : Prop :=
forall (X:id), st1 X = st2 X.
Notation "st1 '~' st2" := (stequiv st1 st2) (at level 30).
Lemma stequiv_refl : forall (st : state),
st ~ st.
Proof.
intros. intro X. auto. Qed.
Lemma stequiv_sym : forall (st1 st2 : state),
st1 ~ st2 ->
st2 ~ st1.
Proof.
intros. intro X. symmetry. apply H. Qed.
Lemma stequiv_trans : forall (st1 st2 st3 : state),
st1 ~ st2 ->
st2 ~ st3 ->
st1 ~ st3.
Proof.
intros. intro X. rewrite H. apply H0. Qed.
Lemma stequiv_update : forall (st1 st2 : state),
st1 ~ st2 ->
forall (X:id) (n:nat),
update st1 X n ~ update st2 X n.
Proof.
intros. intros x.
destruct (eq_id_dec X x) eqn:eq.
subst. rewrite update_eq. rewrite update_eq. auto.
rewrite update_neq; auto. rewrite update_neq; auto.
Qed.
Lemma stequiv_aeval : forall (st1 st2 : state),
st1 ~ st2 ->
forall (a:aexp), aeval st1 a = aeval st2 a.
Proof.
intros.
induction a; simpl; auto.
Qed.
Lemma stequiv_beval : forall (st1 st2 : state),
st1 ~ st2 ->
forall (b:bexp), beval st1 b = beval st2 b.
Proof.
intros.
induction b; simpl; auto; try rewrite stequiv_aeval with (st2:=st2); auto;
try rewrite stequiv_aeval with (st1:=st1) (st2:=st2); auto.
rewrite IHb; auto.
rewrite IHb1. rewrite IHb2. auto.
Qed.
Lemma stequiv_ceval: forall (st1 st2 : state),
st1 ~ st2 ->
forall (c: com) (st1': state),
(c / st1 || st1') ->
exists st2' : state,
((c / st2 || st2') /\ st1' ~ st2').
Proof.
intros st1 st2 STEQV c st1' CEV1. generalize dependent st2.
induction CEV1; intros st2 STEQV.
Case "SKIP".
exists st2. split.
constructor.
assumption.
Case ":=".
exists (update st2 x n). split.
constructor. rewrite <- H. symmetry. apply stequiv_aeval.
assumption. apply stequiv_update. assumption.
Case ";".
destruct (IHCEV1_1 st2 STEQV) as [st2' [P1 EQV1]].
destruct (IHCEV1_2 st2' EQV1) as [st2'' [P2 EQV2]].
exists st2''. split.
apply E_Seq with st2'; assumption.
assumption.
Case "IfTrue".
destruct (IHCEV1 st2 STEQV) as [st2' [P EQV]].
exists st2'. split.
apply E_IfTrue. rewrite <- H. symmetry. apply stequiv_beval.
assumption. assumption. assumption.
Case "IfFalse".
destruct (IHCEV1 st2 STEQV) as [st2' [P EQV]].
exists st2'. split.
apply E_IfFalse. rewrite <- H. symmetry. apply stequiv_beval.
assumption. assumption. assumption.
Case "WhileEnd".
exists st2. split.
apply E_WhileEnd. rewrite <- H. symmetry. apply stequiv_beval.
assumption. assumption.
Case "WhileLoop".
destruct (IHCEV1_1 st2 STEQV) as [st2' [P1 EQV1]].
destruct (IHCEV1_2 st2' EQV1) as [st2'' [P2 EQV2]].
exists st2''. split.
apply E_WhileLoop with st2'. rewrite <- H. symmetry.
apply stequiv_beval. assumption. assumption. assumption.
assumption.
Qed.
Reserved Notation "c1 '/' st '||'' st'" (at level 40, st at level 39).
Inductive ceval' : com -> state -> state -> Prop :=
| E_equiv : forall c st st' st'',
c / st || st' ->
st' ~ st'' ->
c / st ||' st''
where "c1 '/' st '||'' st'" := (ceval' c1 st st').
Definition cequiv' (c1 c2 : com) : Prop :=
forall (st st' : state),
(c1 / st ||' st') <-> (c2 / st ||' st').
Lemma cequiv__cequiv' : forall (c1 c2: com),
cequiv c1 c2 -> cequiv' c1 c2.
Proof.
unfold cequiv, cequiv'; split; intros.
inversion H0 ; subst. apply E_equiv with st'0.
apply (H st st'0); assumption. assumption.
inversion H0 ; subst. apply E_equiv with st'0.
apply (H st st'0). assumption. assumption.
Qed.
Example identity_assignment' :
cequiv' SKIP (X ::= AId X).
Proof.
unfold cequiv'. intros. split; intros.
Case "->".
inversion H; subst; clear H. inversion H0; subst.
apply E_equiv with (update st'0 X (st'0 X)).
constructor. reflexivity. apply stequiv_trans with st'0.
unfold stequiv. intros. apply update_same.
reflexivity. assumption.
Case "<-".
inversion H; subst; clear H.
apply E_equiv with st'0; auto.
generalize H0.
apply identity_assignment.
Qed.
Theorem for_while_skip_equiv : forall b c2 c3 st st',
((FOR(FSKIP,b,c2) DO c3 END) /f st || st') <->
((WHILEF b DO c3 F; c2 END) /f st || st').
Proof.
split; intros.
remember (FOR (FSKIP, b, c2)DO c3 END) as floop.
induction H; try inversion Heqfloop; subst.
inversion H; subst.
apply F_WhileEnd; auto.
inversion H; subst.
apply F_WhileLoop with st''; auto.
remember (WHILEF b DO c3 F; c2 END) as loopdef eqn:loop.
induction H; try inversion loop; subst.
apply F_ForEnd; try constructor; auto.
apply F_ForLoop with st st'; try apply F_Skip; subst; auto.
Qed.
Theorem for_while_equiv : forall b c1 c2 c3 st st',
((FOR(c1,b,c2) DO c3 END) /f st || st') <->
((c1 F; WHILEF b DO c3 F; c2 END) /f st || st').
Proof.
split.
generalize dependent st'.
remember (FOR (c1, b, c2)DO c3 END) as floop.
intros.
induction H; try inversion Heqfloop.
apply F_Seq with st'; subst; auto.
apply F_WhileEnd; auto.
apply F_Seq with st'; subst; auto.
apply F_WhileLoop with st''; auto.
apply for_while_skip_equiv. auto.
intros. inversion H; subst.
remember (WHILEF b DO c3 F; c2 END) as floopdef eqn:loop.
induction H5; try inversion loop; subst.
apply F_ForEnd; auto.
apply F_ForLoop with st0 st'; try auto.
apply for_while_skip_equiv. auto.
Qed.
Theorem swap_noninterfering_assignments: forall l1 l2 a1 a2,
l1 <> l2 ->
var_not_used_in_aexp l1 a2 ->
var_not_used_in_aexp l2 a1 ->
cequiv
(l1 ::= a1;; l2 ::= a2)
(l2 ::= a2;; l1 ::= a1).
Proof.
intros.
assert(Hevaleq : forall st, update (update st l1 (aeval st a1)) l2
(aeval (update st l1 (aeval st a1)) a2) =
update (update st l2 (aeval st a2)) l1
(aeval (update st l2 (aeval st a2)) a1)).
intros. apply functional_extensionality.
intro.
destruct (eq_id_dec l1 x) eqn:id1.
rewrite update_neq; subst; auto.
rewrite update_eq. rewrite update_eq.
rewrite aeval_weakening; auto.
destruct (eq_id_dec l2 x) eqn:id2; subst.
rewrite update_eq. rewrite aeval_weakening; auto.
rewrite update_neq; auto. rewrite update_eq. auto.
repeat rewrite update_neq; auto.
split; intro;
inversion H2; subst; inversion H5; subst; inversion H8; subst.
rewrite Hevaleq. apply E_Seq with (update st l2 (aeval st a2));
apply E_Ass; auto.
rewrite <- Hevaleq. apply E_Seq with (update st l1 (aeval st a1));
apply E_Ass; auto.
Qed.
|
{"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/Equiv.v"}
|
(* DEC 2.0 language specification.
Paolo Torrini
Universite' de Lille - CRIStAL-CNRS
*)
Require Import List.
Require Import Equality.
Require Import Eqdep.
Require Import PeanoNat.
Require Import Omega.
Require Import ProofIrrelevance.
Require Import AuxLibI1.
Require Import TypSpecI1.
Require Import ModTypI1.
Require Import LangSpecI1.
Require Import StaticSemI1.
Require Import DynamicSemI1.
Require Import WeakenI1.
Require Import UniqueTypI1.
Require Import DerivDynI1.
Require Import TransPrelimI1.
Require Import TSoundnessI1.
Require Import SReducI1.
Require Import DetermI1.
Import ListNotations.
Module PreRefl (IdT: ModTyp) <: ModTyp.
Module DetermL := Determ IdT.
Export DetermL.
Definition Id := IdT.Id.
Definition IdEqDec := IdT.IdEqDec.
Definition IdEq := IdT.IdEq.
Definition W := IdT.W.
Definition BInit := IdT.BInit.
Definition WP := IdT.WP.
Open Scope type_scope.
(* extends the shallow environment *)
Lemma ext_senv (tenv : valTC)
(X : tlist2type (map sVTyp (map snd tenv))) (x: Id) (t: VTyp)
(sv : sVTyp t) :
valTC_Trans ((x, t) :: tenv).
unfold valTC_Trans.
simpl.
constructor.
exact sv.
exact X.
Defined.
(* extract values of x from senv *)
Lemma ExpDenotI_Var
(ftenv : funTC)
(tenv : valTC)
(x : Id)
(t : VTyp)
(i : IdTyping tenv x t) :
(* sfenv *) tlist2type (map snd (FunTC_ListTrans ftenv)) ->
(* senv *) valTC_Trans tenv -> MM WW (sVTyp t).
intros.
assert (sVTyp t).
eapply (extract_from_valTC_TransB tenv X0 x).
auto.
unfold MM.
intro X2.
exact (X1,X2).
Defined.
(* extract values of x from senv;
replaces ExpDenotI_Var *)
Lemma ExpDenI_Var
(tenv : valTC)
(x : Id)
(t : VTyp)
(i : IdTyping tenv x t) :
(* senv: *) valTC_Trans tenv ->
MM WW (sVTyp t).
intros.
assert (sVTyp t).
eapply (extract_from_valTC_TransB tenv X x).
auto.
unfold MM.
intro X1.
exact (X0,X1).
Defined.
Lemma ExpDenI2_Var
(tenv : valTC)
(x : Id)
(t : VTyp)
(i : IdTyping tenv x t) (n: nat) :
valTC_Trans tenv ->
W -> (sVTyp t * W) * (sigT (fun n0 => n0 <= n)).
intros.
assert (sVTyp t).
eapply (extract_from_valTC_TransB tenv X x).
auto.
split.
exact (X1,X0).
econstructor 1 with (x:=n).
auto.
Defined.
Lemma ExpTransAux1_Var
(x : Id)
(v : Value)
(t : VTyp) (mB: valueVTyp v = t)
(n0 : nat) (s0 : W) :
(sVTyp t * W) * (sigT (fun n => n <= n0)).
unfold valueVTyp in mB.
destruct v.
rewrite <- mB.
simpl.
destruct v.
split.
exact (v, s0).
econstructor 1 with (x:= n0).
auto.
Defined.
Lemma ExpTransAux2_Var
(tenv: valTC) (env: valEnv)
(m: EnvTyping env tenv)
(x : Id)
(t : VTyp)
(i : IdTyping tenv x t)
(n0 : nat) (s0 : W) :
(sVTyp t * W) * (sigT (fun n => n <= n0)).
eapply (ExpTransAux1_Var x
(ExtRelVal2A_1 valueVTyp tenv env x t m i)
t
(ExtRelVal2A_4 valueVTyp tenv env x t m i)
n0 s0).
Defined.
(*******************************************************************)
Definition ExpTrans1_def :=
fun (ftenv: funTC) (tenv: valTC) (e: Exp) (t: VTyp)
(k: ExpTyping ftenv tenv e t) =>
forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),
(valTC_Trans tenv -> MM WW (sVTyp t)).
Definition PrmsTrans1_def :=
fun (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp)
(k: PrmsTyping ftenv tenv ps pt) =>
forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),
(valTC_Trans tenv -> MM WW (PTyp_Trans pt)).
Definition Trans_ExpTyping_mut1 :=
ExpTyping_mut ExpTrans1_def PrmsTrans1_def.
Definition Trans_PrmsTyping_mut1 :=
PrmsTyping_mut ExpTrans1_def PrmsTrans1_def.
Lemma ExpDenotK_Var :
forall (ftenv : funTC) (tenv : valTC) (x : StaticSemL.Id)
(t : VTyp) (i : IdTyping tenv x t),
ExpTrans1_def ftenv tenv (Var x) t (Var_Typing ftenv tenv x t i).
unfold ExpTrans1_def.
intros.
eapply ExpDenI_Var.
exact i.
exact X.
Defined.
Program Fixpoint ExpTrans (ftenv: funTC) (tenv: valTC) (e: Exp) (t: VTyp)
(k: ExpTyping ftenv tenv e t) :
forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),
(valTC_Trans tenv -> MM WW (sVTyp t)) := _
with PrmsTrans (ftenv: funTC) (tenv: valTC) (ps: Prms) (pt: PTyp)
(k: PrmsTyping ftenv tenv ps pt) :
forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),
(valTC_Trans tenv -> MM WW (PTyp_Trans pt)) := _.
Next Obligation.
eapply Trans_ExpTyping_mut1.
- unfold ExpTrans1_def.
intros.
inversion v0; subst.
exact (ret (sValue v)).
- (* apply ExpTransVar. *)
unfold ExpTrans1_def.
intros.
eapply ExpDenI_Var.
exact i.
exact X.
- unfold ExpTrans1_def.
intros.
exact (bind (X sfenv X1) (fun _ => X0 sfenv X1)).
- unfold ExpTrans1_def.
intros.
specialize (X sfenv X1).
specialize (X0 sfenv).
inversion e; subst.
unfold valTC_Trans in X1.
unfold VTList_Trans in X1.
unfold MM.
unfold MM in X.
intro w0.
specialize (X w0).
destruct X as [sv1 w1].
specialize (X0 (ext_senv tenv X1 x t1 sv1)).
unfold MM in X0.
specialize (X0 w1).
exact X0.
- unfold ExpTrans1_def.
intros.
specialize (X sfenv).
inversion e1; subst.
clear H.
eapply extend_valTC_Trans with (env0:=env0) (tenv0:=tenv0) in X0.
eapply X.
exact X0.
exact e0.
- unfold ExpTrans1_def.
intros.
specialize (X sfenv X2).
specialize (X0 sfenv X2).
specialize (X1 sfenv X2).
intro w0.
specialize (X w0).
destruct X as [b w1].
inversion b; subst.
specialize (X0 w1).
exact X0.
specialize (X1 w1).
exact X1.
- unfold ExpTrans1_def, PrmsTrans1_def.
intros.
specialize (X0 sfenv X1).
unfold MM.
unfold MM in X0.
intro w0.
specialize (X0 w0).
destruct X0 as [nn w1].
destruct w1 as [s1 n1].
set (w2 := (s1, min nn n1)).
specialize (X sfenv X1).
assert (FTyp_Trans2 (FT pt t)).
eapply extract_from_funTC_Trans with
(sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).
exact (sfenv (snd w2)).
inversion i; subst.
reflexivity.
reflexivity.
unfold FTyp_Trans2 in X0.
unfold FType_mk2 in X0.
simpl in X0.
destruct pt.
unfold PTyp_Trans in X.
unfold VTList_Trans in X.
unfold PTyp_ListTrans in X0.
exact (bind X X0 w2).
- unfold ExpTrans1_def, PrmsTrans1_def.
intros.
unfold MM.
intro w0.
specialize (X sfenv X0).
assert (FTyp_Trans2 (FT pt t)).
eapply extract_from_funTC_Trans with
(sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).
exact (sfenv (snd w0)).
inversion i; subst.
reflexivity.
reflexivity.
unfold FTyp_Trans2 in X1.
unfold FType_mk2 in X1.
simpl in X1.
destruct pt.
unfold PTyp_Trans in X.
unfold VTList_Trans in X.
unfold PTyp_ListTrans in X1.
exact (bind X X1 w0).
- unfold ExpTrans1_def.
intros.
specialize (X sfenv X0).
unfold MM in *.
intro w0.
specialize (X w0).
destruct X as [v0 w1].
destruct w1 as [s1 n1].
destruct XF.
set (x_mod0 v0 s1) as p.
subst inpT0.
subst outT0.
exact (fst p, (snd p, n1)).
- unfold PrmsTrans1_def.
intros.
intro.
split.
constructor.
exact X0.
- unfold ExpTrans1_def, PrmsTrans1_def.
intros.
specialize (X sfenv X1).
specialize (X0 sfenv X1).
intro w0.
specialize (X w0).
destruct X as [v1 w1].
specialize (X0 w1).
destruct X0 as [vs w2].
split.
unfold PTyp_Trans in *.
constructor.
exact v1.
exact vs.
exact w2.
Defined.
Next Obligation.
eapply Trans_PrmsTyping_mut1.
- unfold ExpTrans1_def.
intros.
inversion v0; subst.
exact (ret (sValue v)).
- (* apply ExpTransVar. *)
unfold ExpTrans1_def.
intros.
eapply ExpDenI_Var.
exact i.
exact X.
- unfold ExpTrans1_def.
intros.
exact (bind (X sfenv X1) (fun _ => X0 sfenv X1)).
- unfold ExpTrans1_def.
intros.
specialize (X sfenv X1).
specialize (X0 sfenv).
inversion e; subst.
unfold valTC_Trans in X1.
unfold VTList_Trans in X1.
unfold MM.
unfold MM in X.
intro w0.
specialize (X w0).
destruct X as [sv1 w1].
specialize (X0 (ext_senv tenv X1 x t1 sv1)).
unfold MM in X0.
specialize (X0 w1).
exact X0.
- unfold ExpTrans1_def.
intros.
specialize (X sfenv).
inversion e1; subst.
clear H.
eapply extend_valTC_Trans with (env0:=env0) (tenv0:=tenv0) in X0.
eapply X.
exact X0.
exact e0.
- unfold ExpTrans1_def.
intros.
specialize (X sfenv X2).
specialize (X0 sfenv X2).
specialize (X1 sfenv X2).
intro w0.
specialize (X w0).
destruct X as [b w1].
inversion b; subst.
specialize (X0 w1).
exact X0.
specialize (X1 w1).
exact X1.
- unfold ExpTrans1_def, PrmsTrans1_def.
intros.
specialize (X0 sfenv X1).
unfold MM.
unfold MM in X0.
intro w0.
specialize (X0 w0).
destruct X0 as [nn w1].
destruct w1 as [s1 n1].
set (w2 := (s1, min nn n1)).
specialize (X sfenv X1).
assert (FTyp_Trans2 (FT pt t)).
eapply extract_from_funTC_Trans with
(sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).
exact (sfenv (snd w2)).
inversion i; subst.
reflexivity.
reflexivity.
unfold FTyp_Trans2 in X0.
unfold FType_mk2 in X0.
simpl in X0.
destruct pt.
unfold PTyp_Trans in X.
unfold VTList_Trans in X.
unfold PTyp_ListTrans in X0.
exact (bind X X0 w2).
- unfold ExpTrans1_def, PrmsTrans1_def.
intros.
unfold MM.
intro w0.
specialize (X sfenv X0).
assert (FTyp_Trans2 (FT pt t)).
eapply extract_from_funTC_Trans with
(sftenv:=(FunTC_ListTrans ftenv)) (ftenv:=ftenv) (x:=x).
exact (sfenv (snd w0)).
inversion i; subst.
reflexivity.
reflexivity.
unfold FTyp_Trans2 in X1.
unfold FType_mk2 in X1.
simpl in X1.
destruct pt.
unfold PTyp_Trans in X.
unfold VTList_Trans in X.
unfold PTyp_ListTrans in X1.
exact (bind X X1 w0).
- unfold ExpTrans1_def.
intros.
specialize (X sfenv X0).
unfold MM in *.
intro w0.
specialize (X w0).
destruct X as [v0 w1].
destruct w1 as [s1 n1].
destruct XF.
set (x_mod0 v0 s1) as p.
subst inpT0.
subst outT0.
exact (fst p, (snd p, n1)).
- unfold PrmsTrans1_def.
intros.
intro.
split.
constructor.
exact X0.
- unfold ExpTrans1_def, PrmsTrans1_def.
intros.
specialize (X sfenv X1).
specialize (X0 sfenv X1).
intro w0.
specialize (X w0).
destruct X as [v1 w1].
specialize (X0 w1).
destruct X0 as [vs w2].
split.
unfold PTyp_Trans in *.
constructor.
exact v1.
exact vs.
exact w2.
Defined.
(**********************************************************************)
(* translation of d-function base case *)
Program Definition preZero0 (f: Fun) :
(* FunWT1 ftenv f ->*) FunTyp_TRN f := _.
Next Obligation.
intros.
destruct f.
unfold FunTyp_TRN.
unfold FTyp_TRN2.
unfold FType_mk2.
simpl.
intros.
exact (ret (sValue v)).
Defined.
Definition preZero (f: Fun) : FunTyp_TRN f :=
match f as f0 return (FunTyp_TRN f0) with
| FC tenv v e =>
fun _ : tlist2type (map sVTyp (map snd tenv)) => ret (sValue v)
end.
(* translation of fenv base case *)
Program Definition ZeroTRN1 (fenv: funEnv) :
tlist2type (map snd (FunEnv_ListTrans fenv)) := _.
Next Obligation.
intro fenv.
induction fenv.
intros.
simpl.
exact tt.
intros.
destruct a.
simpl in *.
split.
eapply preZero.
exact IHfenv.
Defined.
Lemma FunEnv_Trans_lemma (fenv: funEnv) :
FunEnv_ListTrans fenv = FunTC_ListTrans (funEnv2funTC fenv).
unfold FunEnv_ListTrans.
unfold FunTC_ListTrans.
induction fenv.
simpl.
auto.
simpl in *.
rewrite IHfenv.
auto.
Defined.
(* translation of fenv base case *)
Program Definition ZeroTRN2 (fenv: funEnv) :
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := _.
Next Obligation.
intro fenv.
induction fenv.
intros.
simpl.
exact tt.
intros.
destruct a.
simpl in *.
split.
eapply preZero.
exact IHfenv.
Defined.
Program Definition ZeroTRN3 (fenv: funEnv) :
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := _.
Next Obligation.
intros.
rewrite <- FunEnv_Trans_lemma.
eapply ZeroTRN1.
Defined.
(*
NOTE: proved AFTER the translation lemma (ExpTrans).
In contrast, the extract_from_... lemmas are proven beforehand.
ZeroTRN1 used for the base case; then proved
tlist2type (map snd (FunEnv_ListTrans fenv)) =
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))
*)
Program Definition preSucc (fenv: funEnv)
(k: FEnvWT fenv) (x: Id) (f: Fun) :
findE fenv x = Some f ->
forall (sfenv: nat -> tlist2type
(map snd (FunTC_ListTrans (funEnv2funTC fenv)))),
FunTyp_TRN f := _.
Next Obligation.
intros.
set (tenv := funValTC f).
set (e := funSExp f).
set (t := funVTyp f).
set (ftenv := funEnv2funTC fenv).
assert (ExpTyping ftenv tenv e t) as k1.
unfold FEnvWT in k.
set (sftenv := FunTC_ListTrans ftenv).
assert (FEnvTyping fenv ftenv).
constructor.
specialize (k ftenv H0 x f H).
unfold FunWT in k.
destruct f.
subst e.
subst t.
subst tenv.
simpl in *.
exact k.
specialize (ExpTrans ftenv tenv e t k1 sfenv).
intro.
unfold FunTyp_TRN.
unfold FTyp_TRN2.
unfold FType_mk2.
unfold valTC_Trans in X.
unfold VTList_Trans in X.
destruct f.
subst tenv e t.
simpl in *.
unfold VTyp_Trans.
unfold TList_Type in X.
exact X.
Defined.
Program Definition preSucc1 (fenv: funEnv)
(k: FEnvWT fenv) :
forall (sfenv: nat -> tlist2type
(map snd (FunTC_ListTrans (funEnv2funTC fenv))))
(x: Id) (f: Fun),
findE fenv x = Some f ->
FunTyp_TRN f := _.
Next Obligation.
intros.
eapply (preSucc fenv k x f H sfenv).
Defined.
(*
If each function definition in fenv can be translated, then
each subset of fenv can be translated.
Here X stands for the call to preSucc.
Essential the use of noDup (used by in_find_lemma)
*)
Program Definition SuccTRN_step (fenv: funEnv) :
noDup fenv ->
(forall (x: Id) (f: Fun),
findE fenv x = Some f ->
FunTyp_TRN f) ->
forall (fenv1: funEnv),
(forall a, In a fenv1 -> In a fenv) ->
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv1))) := _.
Next Obligation.
intros fenv D X fenv1.
induction fenv1.
intros.
simpl in *.
exact tt.
intro H.
destruct a as [x f].
intros.
assert (forall a : LangSpecL.Id * Fun, In a fenv1 -> In a fenv).
{- intros.
specialize (H a).
simpl in H.
assert ((x, f) = a \/ In a fenv1).
right; exact H0.
eapply H in H1.
exact H1.
}
specialize (IHfenv1 H0).
simpl in *.
clear H0.
split.
specialize (H (x,f)).
assert (In (x, f) fenv).
eapply H.
left.
auto.
apply in_find_lemma in H0.
eapply X.
exact H0.
exact D.
eapply IHfenv1.
Defined.
Program Definition preSucc2 (fenv: funEnv)
(k: FEnvWT fenv) :
noDup fenv ->
forall (sfenv:
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))))
(fenv1: funEnv),
(forall a, In a fenv1 -> In a fenv) ->
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv1))) := _.
Next Obligation.
intros.
eapply (SuccTRN_step fenv H).
eapply (preSucc1 fenv k).
intro.
exact sfenv.
exact H0.
Defined.
Program Definition SuccTRN (fenv: funEnv)
(k: FEnvWT fenv) :
noDup fenv ->
forall (sfenv:
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))),
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := _.
Next Obligation.
intros.
eapply (preSucc2 fenv k H).
exact sfenv.
intros.
exact H0.
Defined.
Fixpoint FunEnvTRN (fenv: funEnv)
(k1: FEnvWT fenv) (k2: noDup fenv) (n: nat) :
tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) := match n with
| 0 => ZeroTRN3 fenv
| S m => SuccTRN fenv k1 k2
(FunEnvTRN fenv k1 k2 m)
end.
Definition ExpTrans2 (ftenv: funTC) (tenv: valTC)
(e: Exp) (t: VTyp)
(k: ExpTyping ftenv tenv e t) :
forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),
(valTC_Trans tenv) -> MM WW (sVTyp t) := fun sfenv =>
ExpTrans ftenv tenv e t k sfenv.
Definition PrmsTrans2 (ftenv: funTC) (tenv: valTC)
(ps: Prms) (pt: PTyp)
(k: PrmsTyping ftenv tenv ps pt) :
forall (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),
(valTC_Trans tenv) -> MM WW (PTyp_Trans pt) := fun sfenv =>
PrmsTrans ftenv tenv ps pt k sfenv.
Definition ExpEvalTRN (fenv: funEnv)
(k1: FEnvWT fenv) (k2: noDup fenv)
(env: valEnv) (e: Exp) (t: VTyp)
(k: ExpTyping (funEnv2funTC fenv) (valEnv2valTC env) e t) :
MM WW (sVTyp t) := fun w =>
let senv := ValEnvTRN env in
let sfenv := FunEnvTRN fenv k1 k2 in
ExpTrans2 (funEnv2funTC fenv) (valEnv2valTC env) e t k sfenv senv w.
Definition PrmsEvalTRN (fenv: funEnv)
(k1: FEnvWT fenv) (k2: noDup fenv)
(env: valEnv) (ps: Prms) (pt: PTyp)
(k: PrmsTyping (funEnv2funTC fenv) (valEnv2valTC env) ps pt) :
MM WW (PTyp_Trans pt) := fun w =>
let senv := ValEnvTRN env in
let sfenv := FunEnvTRN fenv k1 k2 in
PrmsTrans2 (funEnv2funTC fenv) (valEnv2valTC env) ps pt k sfenv senv w.
(**************************************************************************)
(**************************************************************************)
(* IMPORTANT *)
Lemma ExtRelVal2A_ok (env: valEnv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE (valEnv2valTC env) x = Some t)
(k2: findE env x = Some v) :
v = proj1_of_sigT2 (ExtRelVal2A valueVTyp (valEnv2valTC env) env x t
eq_refl k1).
induction env.
inversion k1.
destruct a.
simpl in k1, k2.
simpl.
unfold ExtRelVal2A.
unfold proj1_of_sigT2.
unfold sigT_of_sigT2.
simpl.
destruct (IdT.IdEqDec x i).
inversion k2; subst.
reflexivity.
specialize (IHenv k1 k2).
rewrite IHenv.
reflexivity.
Defined.
Lemma ExtRelVal2A2_ok (env: valEnv) (tenv: valTC)
(m: EnvTyping env tenv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE tenv x = Some t)
(k2: findE env x = Some v) :
v = proj1_of_sigT2 (ExtRelVal2A valueVTyp tenv env x t
m k1).
unfold EnvTyping in m.
unfold MatchEnvs in m.
inversion m; subst.
induction env.
inversion k2.
destruct a.
simpl in k1, k2.
simpl.
unfold ExtRelVal2A.
unfold proj1_of_sigT2.
unfold sigT_of_sigT2.
simpl.
destruct (IdT.IdEqDec x i).
inversion k2; subst.
reflexivity.
specialize (IHenv k1 k2).
rewrite IHenv.
reflexivity.
reflexivity.
Defined.
Lemma ExtRelVal2A_Typ_ok (env: valEnv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE (valEnv2valTC env) x = Some t)
(k2: findE env x = Some v) :
sVTyp (projT1
(proj1_of_sigT2
(ExtRelVal2A valueVTyp (valEnv2valTC env) env x t eq_refl k1))) =
(sVTyp (projT1 v)).
rewrite (ExtRelVal2A_ok env x t v k1 k2).
reflexivity.
Defined.
Lemma ExtRelVal2A_TypSym_ok (env: valEnv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE (valEnv2valTC env) x = Some t)
(k2: findE env x = Some v) :
(sVTyp (projT1 v)) =
sVTyp (projT1
(proj1_of_sigT2
(ExtRelVal2A valueVTyp (valEnv2valTC env) env x t eq_refl k1))).
symmetry.
eapply (ExtRelVal2A_Typ_ok env x t v k1 k2).
Defined.
Lemma ExtRelVal2A2_Typ_ok (env: valEnv) (tenv: valTC)
(m: EnvTyping env tenv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE tenv x = Some t)
(k2: findE env x = Some v) :
(sVTyp (projT1 v)) =
sVTyp (projT1
(proj1_of_sigT2
(ExtRelVal2A valueVTyp tenv env x t m k1))).
rewrite (ExtRelVal2A2_ok env tenv m x t v k1 k2).
reflexivity.
Defined.
Lemma ExtRelVal2A2_TypSym_ok (env: valEnv) (tenv: valTC)
(m: EnvTyping env tenv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE tenv x = Some t)
(k2: findE env x = Some v) :
sVTyp (projT1
(proj1_of_sigT2
(ExtRelVal2A valueVTyp tenv env x t m k1))) =
(sVTyp (projT1 v)).
rewrite (ExtRelVal2A2_ok env tenv m x t v k1 k2).
reflexivity.
Defined.
Lemma ExtRelVal_aux1 (env : list (LangSpecL.Id * Value))
(x : Id)
(t : VTyp)
(v : sVTyp t)
(k2 : findE env x = Some (existT ValueI t (Cst t v)))
(k1 : findE (valEnv2valTC env) x = Some t)
(H : existT ValueI t (Cst t v) =
(let (a, _, _) := ExtRelVal2B env x t k1 in a)) :
ExtRelVal2B_Typ_ok env x t (existT ValueI t (Cst t v)) k1 k2 =
eq_ind_r
(fun v0 : Value =>
sVTyp (projT1 v0) =
sVTyp (projT1 (proj1_of_sigT2 (ExtRelVal2B env x t k1)))) eq_refl
(eq_ind_r
(fun v0 : Value =>
v0 =
(let (a, _, _) :=
list_rect
(fun env0 : list (LangSpecL.Id * Value) =>
findE (valEnv2valTC env0) x = Some t ->
{v1 : Value & findE env0 x = Some v1 & projT1 v1 = t})
(fun H0 : None = Some t =>
False_rect {v1 : Value & None = Some v1 & projT1 v1 = t}
(eq_ind None
(fun e : option VTyp =>
match e with
| Some _ => False
| None => True
end) I (Some t) H0))
(fun (a : LangSpecL.Id * Value)
(env0 : list (LangSpecL.Id * Value))
(IHenv : findE (valEnv2valTC env0) x = Some t ->
{v1 : Value & findE env0 x = Some v1 &
projT1 v1 = t}) =>
let
(i, v1) as p
return
((if IdT.IdEqDec x (fst p)
then Some (valueVTyp (snd p))
else findE (valEnv2valTC env0) x) =
Some t ->
{v1 : Value &
(let (k', x0) := p in
if IdT.IdEqDec x k' then Some x0 else findE env0 x) =
Some v1 & projT1 v1 = t}) := a in
if IdT.IdEqDec x i as s
return
((if s
then Some (valueVTyp v1)
else findE (valEnv2valTC env0) x) =
Some t ->
{v2 : Value &
(if s then Some v1 else findE env0 x) = Some v2 &
projT1 v2 = t})
then
fun H0 : Some (valueVTyp v1) = Some t =>
existT2 (fun v2 : Value => Some v1 = Some v2)
(fun v2 : Value => projT1 v2 = t) v1 eq_refl
(f_equal
(fun e0 : option VTyp =>
match e0 with
| Some v2 => v2
| None => let (a0, _) := v1 in a0
end) H0)
else fun H0 : findE (valEnv2valTC env0) x = Some t => IHenv H0)
env k1 in
a)) eq_refl
(ExtRelVal2B_ok env x t (existT ValueI t (Cst t v)) k1 k2)).
unfold eq_ind_r.
unfold eq_ind.
unfold eq_sym at 1.
simpl.
eapply proof_irrelevance.
Defined.
(* DEPTYP main idea: replace the equality parameter, and work through
by simplifing the equality proof-term *)
Lemma ExtRelVal2B_ok2 (env: valEnv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE (valEnv2valTC env) x = Some t)
(k2: findE env x = Some v)
(te: (sVTyp (projT1 v)) = sVTyp (projT1
(proj1_of_sigT2 (ExtRelVal2B env x t k1))))
: sValue (proj1_of_sigT2 (ExtRelVal2B env x t k1)) =
match te with
eq_refl => sValue v
end.
replace te with (ExtRelVal2B_Typ_ok env x t v k1 k2).
Focus 2.
eapply proof_irrelevance.
clear te.
assert ( v = proj1_of_sigT2 (ExtRelVal2B env x t k1)).
eapply ExtRelVal2B_ok.
exact k2.
destruct v.
destruct v.
assert (x0 = t).
clear H.
eapply RelatedByEnv with (f:= valueVTyp) (env1:=env)
(v1:= (existT ValueI x0 (Cst x0 v))) in k1.
simpl in k1.
exact k1.
constructor.
exact k2.
inversion H0; subst.
clear H1.
unfold proj1_of_sigT2 in H.
simpl in H.
revert H.
generalize k1.
generalize (ExtRelVal2B env x t k1).
clear k1.
induction env.
inversion k2.
simpl in k2.
destruct a.
unfold ExtRelVal2B_Typ_ok.
simpl.
destruct (IdT.IdEqDec x i).
inversion e; subst.
clear H.
inversion k2; subst.
dependent destruction k2.
simpl in *.
intros.
unfold sValue.
unfold sValueI.
unfold proj1_of_sigT2.
unfold sigT_of_sigT2.
simpl.
reflexivity.
intros.
specialize (IHenv k2 X k1 H).
rewrite IHenv.
clear IHenv.
clear X.
clear n.
clear i.
clear v0.
assert (sValue (existT ValueI t (Cst t v)) = v) as E1.
unfold sValue.
unfold sValueI.
simpl.
reflexivity.
rewrite E1.
clear E1.
rewrite ExtRelVal_aux1.
reflexivity.
exact H.
Defined.
Lemma depeq_sym {T1 T2: Type} (te: T2 = T1) (x1: T1) (x2: T2)
(p: x1 = match te with eq_refl => x2 end) :
x2 = match (eq_sym te) with eq_refl => x1 end.
rewrite p.
unfold eq_sym.
dependent destruction te.
reflexivity.
Defined.
Lemma ExtRelVal2B_ok1 (env: valEnv)
(x: Id) (t: VTyp) (v: Value)
(k1: findE (valEnv2valTC env) x = Some t)
(k2: findE env x = Some v)
(te: sVTyp (projT1 (proj1_of_sigT2 (ExtRelVal2B env x t k1))) =
(sVTyp (projT1 v)))
: sValue v = match te with
eq_refl => sValue (proj1_of_sigT2 (ExtRelVal2B env x t k1))
end.
replace te with (eq_sym (ExtRelVal2B_Typ_ok env x t v k1 k2)).
Focus 2.
eapply proof_irrelevance.
eapply depeq_sym.
eapply ExtRelVal2B_ok2.
exact k2.
Defined.
End PreRefl.
|
{"author": "2xs", "repo": "dec", "sha": "79290ae2f92d437fe365a1b366a30e1eb2b83d19", "save_path": "github-repos/coq/2xs-dec", "path": "github-repos/coq/2xs-dec/dec-79290ae2f92d437fe365a1b366a30e1eb2b83d19/src/DEC2/PreReflI1.v"}
|
import os
import numpy as np
import cv2
import torch
from .models import load_model
from .utils import Window, draw_face
# global settings
EPS = 1e-5
minFace_ = 20 * 1.4
scale_ = 1.414
stride_ = 8
classThreshold_ = [0.37, 0.43, 0.97]
nmsThreshold_ = [0.8, 0.8, 0.3]
angleRange_ = 45
stable_ = 0
class Window2:
def __init__(self, x, y, w, h, angle, scale, conf):
self.x = x
self.y = y
self.w = w
self.h = h
self.angle = angle
self.scale = scale
self.conf = conf
def preprocess_img(img, dim=None):
if dim:
img = cv2.resize(img, (dim, dim), interpolation=cv2.INTER_NEAREST)
return img - np.array([104, 117, 123])
def resize_img(img, scale:float):
h, w = img.shape[:2]
h_, w_ = int(h / scale), int(w / scale)
img = img.astype(np.float32) # fix opencv type error
ret = cv2.resize(img, (w_, h_), interpolation=cv2.INTER_NEAREST)
return ret
def pad_img(img:np.array):
row = min(int(img.shape[0] * 0.2), 100)
col = min(int(img.shape[1] * 0.2), 100)
ret = cv2.copyMakeBorder(img, row, row, col, col, cv2.BORDER_CONSTANT)
return ret
def legal(x, y, img):
if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]:
return True
else:
return False
def inside(x, y, rect:Window2):
if rect.x <= x < (rect.x + rect.w) and rect.y <= y < (rect.y + rect.h):
return True
else:
return False
def smooth_angle(a, b):
if a > b:
a, b = b, a
diff = (b - a) % 360
if diff < 180:
return a + diff // 2
else:
return b + (360 - diff) // 2
# use global variable `prelist` to mimic static variable in C++
prelist = []
def smooth_window(winlist):
global prelist
for win in winlist:
for pwin in prelist:
if IoU(win, pwin) > 0.9:
win.conf = (win.conf + pwin.conf) / 2
win.x = pwin.x
win.y = pwin.y
win.w = pwin.w
win.h = pwin.h
win.angle = pwin.angle
elif IoU(win, pwin) > 0.6:
win.conf = (win.conf + pwin.conf) / 2
win.x = (win.x + pwin.x) // 2
win.y = (win.y + pwin.y) // 2
win.w = (win.w + pwin.w) // 2
win.h = (win.h + pwin.h) // 2
win.angle = smooth_angle(win.angle, pwin.angle)
prelist = winlist
return winlist
def IoU(w1:Window2, w2:Window2) -> float:
xOverlap = max(0, min(w1.x + w1.w - 1, w2.x + w2.w - 1) - max(w1.x, w2.x) + 1)
yOverlap = max(0, min(w1.y + w1.h - 1, w2.y + w2.h - 1) - max(w1.y, w2.y) + 1)
intersection = xOverlap * yOverlap
unio = w1.w * w1.h + w2.w * w2.h - intersection
return intersection / unio
def NMS(winlist, local:bool, threshold:float):
length = len(winlist)
if length == 0:
return winlist
winlist.sort(key=lambda x: x.conf, reverse=True)
flag = [0] * length
for i in range(length):
if flag[i]:
continue
for j in range(i+1, length):
if local and abs(winlist[i].scale - winlist[j].scale) > EPS:
continue
if IoU(winlist[i], winlist[j]) > threshold:
flag[j] = 1
ret = [winlist[i] for i in range(length) if not flag[i]]
return ret
def deleteFP(winlist):
length = len(winlist)
if length == 0:
return winlist
winlist.sort(key=lambda x: x.conf, reverse=True)
flag = [0] * length
for i in range(length):
if flag[i]:
continue
for j in range(i+1, length):
win = winlist[j]
if inside(win.x, win.y, winlist[i]) and inside(win.x + win.w - 1, win.y + win.h - 1, winlist[i]):
flag[j] = 1
ret = [winlist[i] for i in range(length) if not flag[i]]
return ret
# using if-else to mimic method overload in C++
def set_input(img):
if type(img) == list:
img = np.stack(img, axis=0)
else:
img = img[np.newaxis, :, :, :]
img = img.transpose((0, 3, 1, 2))
return torch.FloatTensor(img)
def trans_window(img, imgPad, winlist):
"""transfer Window2 to Window1 in winlist"""
row = (imgPad.shape[0] - img.shape[0]) // 2
col = (imgPad.shape[1] - img.shape[1]) // 2
ret = list()
for win in winlist:
if win.w > 0 and win.h > 0:
ret.append(Window(win.x-col, win.y-row, win.w, win.angle, win.conf))
return ret
def stage1(img, imgPad, net, thres):
row = (imgPad.shape[0] - img.shape[0]) // 2
col = (imgPad.shape[1] - img.shape[1]) // 2
winlist = []
netSize = 24
curScale = minFace_ / netSize
img_resized = resize_img(img, curScale)
while min(img_resized.shape[:2]) >= netSize:
img_resized = preprocess_img(img_resized)
# net forward
net_input = set_input(img_resized)
with torch.no_grad():
net.eval()
cls_prob, rotate, bbox = net(net_input)
w = netSize * curScale
for i in range(cls_prob.shape[2]): # cls_prob[2]->height
for j in range(cls_prob.shape[3]): # cls_prob[3]->width
if cls_prob[0, 1, i, j].item() > thres:
sn = bbox[0, 0, i, j].item()
xn = bbox[0, 1, i, j].item()
yn = bbox[0, 2, i, j].item()
rx = int(j * curScale * stride_ - 0.5 * sn * w + sn * xn * w + 0.5 * w) + col
ry = int(i * curScale * stride_ - 0.5 * sn * w + sn * yn * w + 0.5 * w) + row
rw = int(w * sn)
if legal(rx, ry, imgPad) and legal(rx + rw - 1, ry + rw -1, imgPad):
if rotate[0, 1, i, j].item() > 0.5:
winlist.append(Window2(rx, ry, rw, rw, 0, curScale, cls_prob[0, 1, i, j].item()))
else:
winlist.append(Window2(rx, ry, rw, rw, 180, curScale, cls_prob[0, 1, i, j].item()))
img_resized = resize_img(img_resized, scale_)
curScale = img.shape[0] / img_resized.shape[0]
return winlist
def stage2(img, img180, net, thres, dim, winlist):
length = len(winlist)
if length == 0:
return winlist
datalist = []
height = img.shape[0]
for win in winlist:
if abs(win.angle) < EPS:
datalist.append(preprocess_img(img[win.y:win.y+win.h, win.x:win.x+win.w, :], dim))
else:
y2 = win.y + win.h -1
y = height - 1 - y2
datalist.append(preprocess_img(img180[y:y+win.h, win.x:win.x+win.w, :], dim))
# net forward
net_input = set_input(datalist)
with torch.no_grad():
net.eval()
cls_prob, rotate, bbox = net(net_input)
ret = []
for i in range(length):
if cls_prob[i, 1].item() > thres:
sn = bbox[i, 0].item()
xn = bbox[i, 1].item()
yn = bbox[i, 2].item()
cropX = winlist[i].x
cropY = winlist[i].y
cropW = winlist[i].w
if abs(winlist[i].angle) > EPS:
cropY = height - 1 - (cropY + cropW - 1)
w = int(sn * cropW)
x = int(cropX - 0.5 * sn * cropW + cropW * sn * xn + 0.5 * cropW)
y = int(cropY - 0.5 * sn * cropW + cropW * sn * yn + 0.5 * cropW)
maxRotateScore = 0
maxRotateIndex = 0
for j in range(3):
if rotate[i, j].item() > maxRotateScore:
maxRotateScore = rotate[i, j].item()
maxRotateIndex = j
if legal(x, y, img) and legal(x+w-1, y+w-1, img):
angle = 0
if abs(winlist[i].angle) < EPS:
if maxRotateIndex == 0:
angle = 90
elif maxRotateIndex == 1:
angle = 0
else:
angle = -90
ret.append(Window2(x, y, w, w, angle, winlist[i].scale, cls_prob[i, 1].item()))
else:
if maxRotateIndex == 0:
angle = 90
elif maxRotateIndex == 1:
angle = 180
else:
angle = -90
ret.append(Window2(x, height-1-(y+w-1), w, w, angle, winlist[i].scale, cls_prob[i, 1].item()))
return ret
def stage3(imgPad, img180, img90, imgNeg90, net, thres, dim, winlist):
length = len(winlist)
if length == 0:
return winlist
datalist = []
height, width = imgPad.shape[:2]
for win in winlist:
if abs(win.angle) < EPS:
datalist.append(preprocess_img(imgPad[win.y:win.y+win.h, win.x:win.x+win.w, :], dim))
elif abs(win.angle - 90) < EPS:
datalist.append(preprocess_img(img90[win.x:win.x+win.w, win.y:win.y+win.h, :], dim))
elif abs(win.angle + 90) < EPS:
x = win.y
y = width - 1 - (win.x + win.w -1)
datalist.append(preprocess_img(imgNeg90[y:y+win.h, x:x+win.w, :], dim))
else:
y2 = win.y + win.h - 1
y = height - 1 - y2
datalist.append(preprocess_img(img180[y:y+win.h, win.x:win.x+win.w], dim))
# network forward
net_input = set_input(datalist)
with torch.no_grad():
net.eval()
cls_prob, rotate, bbox = net(net_input)
ret = []
for i in range(length):
if cls_prob[i, 1].item() > thres:
sn = bbox[i, 0].item()
xn = bbox[i, 1].item()
yn = bbox[i, 2].item()
cropX = winlist[i].x
cropY = winlist[i].y
cropW = winlist[i].w
img_tmp = imgPad
if abs(winlist[i].angle - 180) < EPS:
cropY = height - 1 - (cropY + cropW -1)
img_tmp = img180
elif abs(winlist[i].angle - 90) < EPS:
cropX, cropY = cropY, cropX
img_tmp = img90
elif abs(winlist[i].angle + 90) < EPS:
cropX = winlist[i].y
cropY = width -1 - (winlist[i].x + winlist[i].w - 1)
img_tmp = imgNeg90
w = int(sn * cropW)
x = int(cropX - 0.5 * sn * cropW + cropW * sn * xn + 0.5 * cropW)
y = int(cropY - 0.5 * sn * cropW + cropW * sn * yn + 0.5 * cropW)
angle = angleRange_ * rotate[i, 0].item()
if legal(x, y, img_tmp) and legal(x+w-1, y+w-1, img_tmp):
if abs(winlist[i].angle) < EPS:
ret.append(Window2(x, y, w, w, angle, winlist[i].scale, cls_prob[i, 1].item()))
elif abs(winlist[i].angle - 180) < EPS:
ret.append(Window2(x, height-1-(y+w-1), w, w, 180-angle, winlist[i].scale, cls_prob[i, 1].item()))
elif abs(winlist[i].angle - 90) < EPS:
ret.append(Window2(y, x, w, w, 90-angle, winlist[i].scale, cls_prob[i, 1].item()))
else:
ret.append(Window2(width-y-w, x, w, w, -90+angle, winlist[i].scale, cls_prob[i, 1].item()))
return ret
def detect(img, imgPad, nets):
img180 = cv2.flip(imgPad, 0)
img90 = cv2.transpose(imgPad)
imgNeg90 = cv2.flip(img90, 0)
winlist = stage1(img, imgPad, nets[0], classThreshold_[0])
winlist = NMS(winlist, True, nmsThreshold_[0])
winlist = stage2(imgPad, img180, nets[1], classThreshold_[1], 24, winlist)
winlist = NMS(winlist, True, nmsThreshold_[1])
winlist = stage3(imgPad, img180, img90, imgNeg90, nets[2], classThreshold_[2], 48, winlist)
winlist = NMS(winlist, False, nmsThreshold_[2])
winlist = deleteFP(winlist)
return winlist
def pcn_detect(img, nets):
imgPad = pad_img(img)
winlist = detect(img, imgPad, nets)
if stable_:
winlist = smooth_window(winlist)
return trans_window(img, imgPad, winlist)
if __name__ == '__main__':
# usage settings
import sys
if len(sys.argv) != 2:
print("Usage: python3 pcn.py path/to/img")
sys.exit()
else:
imgpath = sys.argv[1]
# network detection
nets = load_model()
img = cv2.imread(imgpath)
faces = pcn_detect(img, nets)
# draw image
for face in faces:
draw_face(img, face)
# show image
cv2.imshow("pytorch-PCN", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save image
name = os.path.basename(imgpath)
cv2.imwrite('result/ret_{}'.format(name), img)
|
{"hexsha": "866879882e8b02e47e7d7bcf43912a4fce5b9ca1", "size": 12463, "ext": "py", "lang": "Python", "max_stars_repo_path": "pcn/pcn.py", "max_stars_repo_name": "quickgrid/pytorch-PCN", "max_stars_repo_head_hexsha": "6c6b15867b09a92eb1035e05c364b8710d7d49e3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 109, "max_stars_repo_stars_event_min_datetime": "2019-02-22T07:49:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T07:28:51.000Z", "max_issues_repo_path": "pcn/pcn.py", "max_issues_repo_name": "quickgrid/pytorch-PCN", "max_issues_repo_head_hexsha": "6c6b15867b09a92eb1035e05c364b8710d7d49e3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-02-24T17:14:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T16:54:57.000Z", "max_forks_repo_path": "pcn/pcn.py", "max_forks_repo_name": "quickgrid/pytorch-PCN", "max_forks_repo_head_hexsha": "6c6b15867b09a92eb1035e05c364b8710d7d49e3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 36, "max_forks_repo_forks_event_min_datetime": "2019-02-24T06:14:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T12:12:07.000Z", "avg_line_length": 35.1070422535, "max_line_length": 118, "alphanum_fraction": 0.5189761695, "include": true, "reason": "import numpy", "num_tokens": 3779}
|
import unittest
import pytest
import numpy as np
from yaonet.tensor import Tensor
from yaonet.basic_functions import matmul
class TestTensorAdd(unittest.TestCase):
def test_tensor_reshape(self):
# t1 is (1, 2)
t1 = Tensor([[1, 2]], requires_grad=True)
# t2 is a (2, 2)
t2 = Tensor([[10, 10], [20, 10]], requires_grad=True)
# (1, 2)
t3 = t1 @ t2
assert t3.data.tolist() == [[50, 30]]
grad = Tensor([[-1, -2]])
t3.backward(grad)
assert t1.grad.tolist() == [[-30, -40]]
# t1 is (1, 2)
t1 = Tensor([[1, 2]], requires_grad=True)
# t2 is a (2, 2)
t2 = Tensor([[10, 10], [20, 10]], requires_grad=True)
# (2, 1)
t4 = matmul(t2, t1.reshape(2, 1))
assert t4.data.tolist() == [[30], [40]]
grad = Tensor([[-1], [-2]])
t4.backward(grad)
assert t1.grad.reshape(2 ,1).tolist() == [[-50], [-30]]
|
{"hexsha": "4c1bc76a75e3c996ab103e7108f0d24cfbf8b2b1", "size": 958, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/test_tensor_reshape.py", "max_stars_repo_name": "Zzoay/yaonet_py", "max_stars_repo_head_hexsha": "79367d6f65ddcfb94c261393e8b9a46775346dbe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-12-19T14:08:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T05:50:13.000Z", "max_issues_repo_path": "tests/test_tensor_reshape.py", "max_issues_repo_name": "Zzoay/yaonet_py", "max_issues_repo_head_hexsha": "79367d6f65ddcfb94c261393e8b9a46775346dbe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_tensor_reshape.py", "max_forks_repo_name": "Zzoay/yaonet_py", "max_forks_repo_head_hexsha": "79367d6f65ddcfb94c261393e8b9a46775346dbe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8095238095, "max_line_length": 63, "alphanum_fraction": 0.5135699374, "include": true, "reason": "import numpy", "num_tokens": 303}
|
import torch
from torchvision import datasets, transforms
import argparse
import numpy as np
from PIL import Image
import json
def argparse_train():
parser = argparse.ArgumentParser()
parser.add_argument("data_directory", help="set directory to get the data from")
parser.add_argument("--save_dir", help="set directory to save checkpoints", default = "./")
parser.add_argument("--arch", help="choose model architecture", default="densenet121")
parser.add_argument("--prob_dropout",type=float, help="choose dropout probability in hidden layer", default=0.3)
parser.add_argument("--learning_rate",type=float , help="choose learning rate", default=0.001)
parser.add_argument("--hidden_units", type=int, help="choose hidden units", default=512)
parser.add_argument("--epochs", type=int, help="choose epochs", default=10)
parser.add_argument('--gpu', action='store_true', default=False, dest='gpu', help='set gpu-training to True')
results = parser.parse_args()
print('data_directory = {!r}'.format(results.data_directory))
print('save_dir = {!r}'.format(results.save_dir))
print('arch = {!r}'.format(results.arch))
print('prob_dropout = {!r}'.format(results.prob_dropout))
print('learning_rate = {!r}'.format(results.learning_rate))
print('hidden_units = {!r}'.format(results.hidden_units))
print('epochs = {!r}'.format(results.epochs))
print('gpu_training = {!r}'.format(results.gpu))
return results
def argparse_predict():
parser = argparse.ArgumentParser()
parser.add_argument("image_path", help="set path to image for prediction")
parser.add_argument("checkpoint", help="set checkpoint to load the model from")
parser.add_argument("--top_k", type=int, help="return top K most likely classes", default=5)
parser.add_argument("--category_names", help="use a mapping of categories to real names", default=None)
parser.add_argument('--gpu', action='store_true', default=False, dest='gpu', help='set gpu-training to True')
results = parser.parse_args()
print('image_path = {!r}'.format(results.image_path))
print('checkpoint = {!r}'.format(results.checkpoint))
print('top_k = {!r}'.format(results.top_k))
print('category_names = {!r}'.format(results.category_names))
print('gpu_training = {!r}'.format(results.gpu))
return results
def load_data(data_directory):
train_dir = data_directory + '/train'
valid_dir = data_directory + '/valid'
test_dir = data_directory + '/test'
# Define transforms for the training, validation, and testing sets
data_transforms = {'train': transforms.Compose([transforms.Resize((250,250)),
transforms.RandomCrop((224,224)),
transforms.RandomRotation(20),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),
'valid': transforms.Compose([transforms.Resize((224,224)),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),
'test': transforms.Compose([transforms.Resize((224,224)),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),
}
# Load the datasets with ImageFolder
image_datasets = {'train': datasets.ImageFolder(train_dir, transform = data_transforms['train']),
'valid': datasets.ImageFolder(train_dir, transform = data_transforms['valid']),
'test': datasets.ImageFolder(train_dir, transform = data_transforms['test'])
}
# Using the image datasets and the trainforms, define the dataloaders
dataloaders = {'train': torch.utils.data.DataLoader(image_datasets['train'], batch_size = 64, shuffle=True),
'valid': torch.utils.data.DataLoader(image_datasets['valid'], batch_size = 64, shuffle=True),
'test': torch.utils.data.DataLoader(image_datasets['test'], batch_size = 64, shuffle=True),
}
return image_datasets, dataloaders
def preprocess_image(image_path):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# Load image
image = Image.open(image_path)
# scale image
size = 256, 256
image.thumbnail(size)
# center crop
width, height = image.size # Get dimensions
new_width = 224
new_height = 224
left = (width - new_width)/2
top = (height - new_height)/2
right = (width + new_width)/2
bottom = (height + new_height)/2
image = image.crop((left, top, right, bottom))
np_image = np.array(image)
# Normalize
means = np.array([0.485, 0.456, 0.406])
stdev = np.array([0.229, 0.224, 0.225])
np_image = (np_image/255 - means)/stdev
image_transposed = np_image.transpose(2,0,1)
return image_transposed
def import_mapping(category_names):
with open(category_names, 'r') as f:
cat_to_name = json.load(f)
return cat_to_name
|
{"hexsha": "187309ad0b3f17d5ce515e971a8047608248727f", "size": 5564, "ext": "py", "lang": "Python", "max_stars_repo_path": "utility.py", "max_stars_repo_name": "Wolfgang90/ds_p2_image_classifier", "max_stars_repo_head_hexsha": "2f4416bb20f5a8bec084a5f07406a6622f3239f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utility.py", "max_issues_repo_name": "Wolfgang90/ds_p2_image_classifier", "max_issues_repo_head_hexsha": "2f4416bb20f5a8bec084a5f07406a6622f3239f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utility.py", "max_forks_repo_name": "Wolfgang90/ds_p2_image_classifier", "max_forks_repo_head_hexsha": "2f4416bb20f5a8bec084a5f07406a6622f3239f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2357723577, "max_line_length": 120, "alphanum_fraction": 0.6161035226, "include": true, "reason": "import numpy", "num_tokens": 1255}
|
\section{Motivation}
A typical customer, buying in a normal clothing storage, often has to deal with a great variety of apparel he can choose from.
The range of clothing he can choose from is even greater, when he uses online-shopping - either on dedicated clothing-shops such as \href{https:\\www.zalando.de}{Zalando} or big shops with an even wider scope of products.
The number of choices a customer can make regarding clothing is almost unlimited.
And anywhere, where the count of choices one can take is to high to grasp, it comes in handy to have something that helps making decisions.\\
One of these tools are so called recommendation systems. The concept of those will be explained in detail later.
\paragraph{Choice overload}
Due to the nearly unlimited number of choices one can make, regarding the variety of products, many customers have trouble finding the products they like best.
This problem is commonly known as "choice overload".\citep[p. 454]{stanton:12}
One domain the problem has been noticed is the clothing industry.
The reason for choice overload range from the massive amount of clothing one can choose from to some social aspects.
There are many possible reasons why customer struggle with decision-making\citep[p. 454]{stanton:12} - however, for this project the scope is limited to possible approaches which solve the problem.
\paragraph{The recommendation system}
One of the projects goals is to implement a fully functional recommendation system.
The core component of the system is the algorithm that generates suggestions.
For this specific project Rocchio's relevance feedback algorithm will be used.
The algorithm will work on product-data taken from an online-shop in order to simulate the real world as good as possible.
A benefit of using apparel as product is the already mentioned huge amount of data one can use.
Zalando, a German online shop specialised on clothing for instance, offers about 150,000 products from 1,500 different brands.\citep{visser:14}
Nevertheless the algorithm and all components which do preliminary work have to be capable of operating on any data that can be shaped into a proper form.
%algorithmus klappt eigentlich immer.
%aber kleidungsindustrie ist attraktiv
%zalandoo anzahl der kleidungsstuecke
%amazon...
%...
|
{"hexsha": "8529e23de586cd6bbd57b2df29712bc9e5fdabb9", "size": 2293, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "interim-report/inc/motivation/motivation.tex", "max_stars_repo_name": "dustywind/bachelor-thesis", "max_stars_repo_head_hexsha": "be06aaeb1b4d73f727a19029a3416a9b8043194d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "interim-report/inc/motivation/motivation.tex", "max_issues_repo_name": "dustywind/bachelor-thesis", "max_issues_repo_head_hexsha": "be06aaeb1b4d73f727a19029a3416a9b8043194d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "interim-report/inc/motivation/motivation.tex", "max_forks_repo_name": "dustywind/bachelor-thesis", "max_forks_repo_head_hexsha": "be06aaeb1b4d73f727a19029a3416a9b8043194d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.6944444444, "max_line_length": 221, "alphanum_fraction": 0.8046227649, "num_tokens": 480}
|
INTEGER MEDISC,SODISC,NDISC,APDISC,MLDISC,MEDIA,SOMA,N,APROV,
* MELHOR,ALUNO,NOTA,UE,US
CHARACTER TURMA*1
DATA UE,US,SODISC,NDISC,APDISC,MLDISC/5,6,3*0,-1/
10 CONTINUE
SOMA = 0
N = 0
APROV = 0
MELHOR = -1
20 CONTINUE
READ(UE,21) TURMA,ALUNO,NOTA
21 FORMAT(A1,I1,I3)
IF (ALUNO.EQ.0) GO TO 30
N = N + 1
IF (NOTA.GE.60) THEN
APROV = APROV + 1
END IF
IF (NOTA.GT.MELHOR) THEN
MELHOR = NOTA
END IF
SOMA = SOMA + NOTA
GO TO 20
30 CONTINUE
MEDIA = SOMA/N
WRITE(US,32) TURMA,APROV,MEDIA,MELHOR
32 FORMAT(5X,'TURMA ',A1,5X,'APROVADOS = ',I3,5X,'MEDIA = ',I3,5X,
* 'MELHOR NOTA = ',I3,/)
SODISC = SODISC + SOMA
NDISC = NDISC + N
APDISC = APDISC + APROV
IF (MELHOR.GT.NDISC) THEN
MLDISC = MELHOR
END IF
IF (TURMA.NE.'R') GO TO 10
MEDISC = SODISC/NDISC
WRITE(US,34) APDISC,MEDISC,MLDISC
34 FORMAT(5X,'APROVADOS NA DISCIPLINA = ',I3,5X,'MEDIA NA DISCIPINA'
* ' = ',I3/5X,'MELHOR NOTA NA DISCIPLINA = ',I3)
STOP
END
|
{"hexsha": "e766e7521137599d5b03e05a7173ad5e7c9783c7", "size": 1007, "ext": "for", "lang": "FORTRAN", "max_stars_repo_path": "codes/120809/teste.for", "max_stars_repo_name": "danielsanfr/fortran-study", "max_stars_repo_head_hexsha": "101ff0aa552f40542b5bc3e90ee0265f9a74eb48", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/120809/teste.for", "max_issues_repo_name": "danielsanfr/fortran-study", "max_issues_repo_head_hexsha": "101ff0aa552f40542b5bc3e90ee0265f9a74eb48", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/120809/teste.for", "max_forks_repo_name": "danielsanfr/fortran-study", "max_forks_repo_head_hexsha": "101ff0aa552f40542b5bc3e90ee0265f9a74eb48", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.175, "max_line_length": 69, "alphanum_fraction": 0.6216484608, "num_tokens": 515}
|
# deps.jl is created at the end of a successful build, so rm
# to ensure that failed builds are missing this file.
if isfile("deps.jl")
rm("deps.jl")
end
include("build_petscs.jl")
|
{"hexsha": "21247c85ba1999e6a9102b66c6694b6a80e6eec4", "size": 183, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "deps/build.jl", "max_stars_repo_name": "gridap/PETSc.jl", "max_stars_repo_head_hexsha": "734dd02defddfffd79656ad48596bc82d14a219c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/build.jl", "max_issues_repo_name": "gridap/PETSc.jl", "max_issues_repo_head_hexsha": "734dd02defddfffd79656ad48596bc82d14a219c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/build.jl", "max_forks_repo_name": "gridap/PETSc.jl", "max_forks_repo_head_hexsha": "734dd02defddfffd79656ad48596bc82d14a219c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1428571429, "max_line_length": 60, "alphanum_fraction": 0.7267759563, "num_tokens": 54}
|
[STATEMENT]
lemma list_before_trans[trans]: "distinct l \<Longrightarrow> trans (list_before_rel l)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. distinct l \<Longrightarrow> trans (list_before_rel l)
[PROOF STEP]
by (clarsimp simp: trans_def list_before_rel_alt) (metis index_nth_id less_trans)
|
{"llama_tokens": 107, "file": "Prpu_Maxflow_Graph_Topological_Ordering", "length": 1}
|
import numpy as np
import pandas as pd
import pybaseball as bb
from pybaseball import statcast
from pybaseball import batting_leaders
from pybaseball import batting_stats_range
from pybaseball import pitching_leaders
from pybaseball import pitching_stats_range
print('Dates must be entered as Year-Month-Day')
x = input('Enter First Date:')
y = input('Enter Second Date:')
print('H = Hits', 'HR = Home Runs', 'AVG = Batting Average', 'SLG = Sluggling %', 'OPS = On Base + SLG' )
z = input('Enter requested Stat:')
data = batting_stats_range(x, y)
sorted_d1 = data.sort_values(by=z, ascending=False)
#sorted_hr = sorted_d1('Name', 'HR')
sorted_d1.head(5)
|
{"hexsha": "e2168e14a395754c083cbd741f4e5a36d943c403", "size": 658, "ext": "py", "lang": "Python", "max_stars_repo_path": "Example hitting.py", "max_stars_repo_name": "ksu-is/Sports-Heat-Chart", "max_stars_repo_head_hexsha": "5d4eb4aad60ff99ff46cfe0c846fe462c7885684", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Example hitting.py", "max_issues_repo_name": "ksu-is/Sports-Heat-Chart", "max_issues_repo_head_hexsha": "5d4eb4aad60ff99ff46cfe0c846fe462c7885684", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example hitting.py", "max_forks_repo_name": "ksu-is/Sports-Heat-Chart", "max_forks_repo_head_hexsha": "5d4eb4aad60ff99ff46cfe0c846fe462c7885684", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3333333333, "max_line_length": 105, "alphanum_fraction": 0.7537993921, "include": true, "reason": "import numpy", "num_tokens": 179}
|
[STATEMENT]
lemma short_cut'[simp,code_unfold]: "(\<eight> \<doteq> \<six>) = false"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<eight> \<doteq> \<six>) = false
[PROOF STEP]
apply(rule ext)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>x. (\<eight> \<doteq> \<six>) x = false x
[PROOF STEP]
apply(simp add: StrictRefEq\<^sub>I\<^sub>n\<^sub>t\<^sub>e\<^sub>g\<^sub>e\<^sub>r StrongEq_def OclInt8_def OclInt6_def
true_def false_def invalid_def bot_option_def)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
|
{"llama_tokens": 244, "file": "Featherweight_OCL_UML_Library", "length": 3}
|
# Author: Seongchun Yang
# Affiliation: Kyoto University
# ======================================================================
# 1. (IMPORTANT:CITATION ALERT)
# As close of an exact implementation of doi: 10.1109/ICIECS.2009.5365064 (Zhang et al., IEEE, 2009).
# 2.
# Reason behind the name 'forgetting scale' parameter is the author's motivation behind this implemnetation,
# which is that nonlinearity cause errors (untracked values) that accumulate over time in the filter [1].
# This is said to be compensated by the every increasing 'd' parameter calculated at every iteration
# which makes the current estimate of error dominate the overall evaluation of Q and R as time passes.
# [1]
# Technically, this isn't a unique problem to just nonlinear filters. Even canonical KFs may suffer the
# same fate if the dynamics aren't well captured through the transition function (fx) and the observation
# function (hx). As such, a fading memory filter exists which increases the predictive covariance slightly
# to mitigate the effect of the past in the filter at every iteration.
import numpy as np
from numpy import dot
from copy import copy, deepcopy
class AdaptiveUnscentedKalmanFilter:
'''
Adaptive Unscented Kalman Filter, as told by Zhang et al. (DOI:10.1109/ICIECS.2009.5365064).
Parameters
----------
kwargs : dict
+ b : float (0<b<1)
forgetting scale
'''
def __init__(self, **kwargs):
self.n = kwargs['n']
self.b = kwargs['b']
def adapt_noise(self, i, x, **kwargs):
'''
As is evident, both Q and R adjustments are made using innovation.
The formulation below makes it so that we can't sufficiently guarantee that this will be PD.
Further adaption in future for this is required for stability.
'''
self.d = (1-self.b)/(1-self.b**(i+2))
self._adaptive_Q()
self._adaptive_R()
def _adaptive_R(self):
self.R = self.R - self.d * (
np.outer(
self.innovation,
self.innovation
) - self.Pxx_c_p
)
def _adaptive_Q(self):
self.Q = self.Q + self.d * (
np.outer(
dot(self.K, self.innovation),
dot(self.K, self.innovation)
) + self.P - self.Pzz_c_p
)
def correct_update(self, x, **kwargs):
'''
(Optional)
The paper doesn't necessarily elaborate on how one should integrate the updated Q and R.
Here, a simple script which reuses the previously computed sigma points are presented here
for reference. This allows the Q and R to update the current time estimates in sync.
Note that the exact implementation may differ depending on the particulars of your filter
and what the author expected. Here, UKF used allows the noise covariances to be added to the
computed cross-covariance. Hence, simple replacement was deemd fit.
'''
# recompute mean and variance per updated Q
self.z_c_c, self.Pzz_c_c = self.UT(
sigmas = self.sigmas_f,
Wm = self.Wm,
Wc = self.Wc,
noise_cov = self.Q
)
# recompute mean and variance per updated R
self.x_c_c, self.Pxx_c_c = self.UT(
sigmas = self.sigmas_h_c_p,
Wm = self.Wm,
Wc = self.Wc,
noise_cov = self.R
)
self.IPxx_c_c = np.linalg.inv(self.Pxx_c_c)
# recompute cross-covariance of the state and the measurements
self.Pzx_c_c =self.cross_variance(
z = self.z_c_c,
x = self.x_c_c,
sigmas_f = self.sigmas_f,
sigmas_h = self.sigmas_h_c_p
)
self.K = dot(self.Pzx_c_c, self.IPxx_c_c)
self.innovation = np.subtract(x,self.x_c_c)
# update
self.z = self.z_c_c + dot(self.K, self.innovation)
self.P = self.Pzz_c_c - dot(self.K, dot(self.Pxx_c_c, self.K.T))
# purpose of computing likelihood
self.S = self.Pxx_c_c
def post_update(self, **kwargs):
# distinction of being a posterior
self.z_c_c = np.copy(self.z)
self.Pzz_c_c = np.copy(self.P)
self.compute_log_likelihood(self.innovation,self.S)
|
{"hexsha": "0a4b2248ed85704b3c06e8fd46dc039cdcc1c942", "size": 4331, "ext": "py", "lang": "Python", "max_stars_repo_path": "KF/Zhang_AUKF.py", "max_stars_repo_name": "SeongchunYang/KF", "max_stars_repo_head_hexsha": "af3ea7a66623879794779c42157294f630add735", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KF/Zhang_AUKF.py", "max_issues_repo_name": "SeongchunYang/KF", "max_issues_repo_head_hexsha": "af3ea7a66623879794779c42157294f630add735", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KF/Zhang_AUKF.py", "max_forks_repo_name": "SeongchunYang/KF", "max_forks_repo_head_hexsha": "af3ea7a66623879794779c42157294f630add735", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3727272727, "max_line_length": 108, "alphanum_fraction": 0.6162549065, "include": true, "reason": "import numpy,from numpy", "num_tokens": 1040}
|
import sys
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra
def main():
n, m = map(int, sys.stdin.readline().split())
can_speak = [[] for _ in range(m + 1)]
for i in range(n):
*languages, = map(int, sys.stdin.readline().split())
for l in languages[1:]:
can_speak[l].append(i)
G = [[0] * n for _ in range(n)]
for language in can_speak:
for j in range(len(language) - 1):
G[language[j]][language[j+1]] = 1
G[language[j+1]][language[j]] = 1
shortest_path = dijkstra(csgraph=csr_matrix(G), directed=False, indices=0)
if np.any(shortest_path == np.inf):
ans = 'NO'
else:
ans = 'YES'
print(ans)
if __name__ == '__main__':
main()
|
{"hexsha": "72ac67c6563b05af2d8082fd5e395391d6d463c8", "size": 826, "ext": "py", "lang": "Python", "max_stars_repo_path": "jp.atcoder/cf16-final/codefestival_2016_final_c/8722733.py", "max_stars_repo_name": "kagemeka/atcoder-submissions", "max_stars_repo_head_hexsha": "91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-09T03:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T03:06:25.000Z", "max_issues_repo_path": "jp.atcoder/cf16-final/codefestival_2016_final_c/8722733.py", "max_issues_repo_name": "kagemeka/atcoder-submissions", "max_issues_repo_head_hexsha": "91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-05T22:53:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T01:29:30.000Z", "max_forks_repo_path": "jp.atcoder/cf16-final/codefestival_2016_final_c/8722733.py", "max_forks_repo_name": "kagemeka/atcoder-submissions", "max_forks_repo_head_hexsha": "91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0303030303, "max_line_length": 79, "alphanum_fraction": 0.5593220339, "include": true, "reason": "import numpy,from scipy", "num_tokens": 223}
|
#!/usr/bin/env python3
import warnings
import numpy as np
from .utils import eis
from .utils import num
def compute(windata, wl0, wl_width):
''' Compute synthetic emission for a given AIA band using EIS data.
Parameters
==========
windata : idl.IDLStructure
Windata structure containing the wavelength windows necessary to compute
the AIA emission.
wl0 : float
The central wavelength of the integration domain, in Ångström.
wl_width : float
The width wavelength of the integration domain, in Ångström.
'''
slot = windata.hdr.slit_id[0].decode() in ('40"', '266"')
if slot:
# slot windata don't have a .missing tag
windata.missing = -100
windata.exposure_time = np.array([float(et)
for et in windata.exposure_time])
exposure_time = windata.exposure_time
t_ref = num.parse_date(windata.hdr['date_obs'][0])
t_abs = num.parse_date(windata.time_ccsds)
windata.time = num.total_seconds(t_abs - t_ref)
else:
exposure_time = windata.exposure_time.reshape(-1, 1)
intensity = windata.int.copy()
missing_places = (intensity == windata.missing)
intensity[missing_places] = np.nan
intensity /= exposure_time
if not slot:
wvl_min = wl0 - wl_width
wvl_max = wl0 + wl_width
i_min = np.argmin(np.abs(windata.wvl - wvl_min))
i_max = np.argmin(np.abs(windata.wvl - wvl_max))
intensity = intensity[:, :, i_min:i_max+1]
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=RuntimeWarning)
intensity = np.nanmean(intensity, axis=-1)
pointing = eis.EISPointing.from_windata(windata, use_wvl=False)
data = eis.EISData(intensity, pointing)
return data
|
{"hexsha": "433d89694ba818d56b9da26698501b7833c1a03e", "size": 1808, "ext": "py", "lang": "Python", "max_stars_repo_path": "eis_pointing/eis_aia_emission.py", "max_stars_repo_name": "gpelouze/eis_pointing", "max_stars_repo_head_hexsha": "2ee714a2295bafae3492ab956792535336dd2a81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-01T09:35:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T15:39:40.000Z", "max_issues_repo_path": "eis_pointing/eis_aia_emission.py", "max_issues_repo_name": "gpelouze/eis_pointing", "max_issues_repo_head_hexsha": "2ee714a2295bafae3492ab956792535336dd2a81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eis_pointing/eis_aia_emission.py", "max_forks_repo_name": "gpelouze/eis_pointing", "max_forks_repo_head_hexsha": "2ee714a2295bafae3492ab956792535336dd2a81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8727272727, "max_line_length": 80, "alphanum_fraction": 0.655420354, "include": true, "reason": "import numpy", "num_tokens": 466}
|
\section{Order statistics}
|
{"hexsha": "eada27cb0170b283cac9ddcff3824c7ffb52086d", "size": 29, "ext": "tex", "lang": "TeX", "max_stars_repo_path": "src/pug/theory/probability/orderStatistics/01-00-Order.tex", "max_stars_repo_name": "adamdboult/nodeHomePage", "max_stars_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pug/theory/probability/orderStatistics/01-00-Order.tex", "max_issues_repo_name": "adamdboult/nodeHomePage", "max_issues_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-03-03T12:36:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T22:16:09.000Z", "max_forks_repo_path": "src/pug/theory/probability/orderStatistics/01-00-Order.tex", "max_forks_repo_name": "adamdboult/nodeHomePage", "max_forks_repo_head_hexsha": "266bfc6865bb8f6b1530499dde3aa6206bb09b93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 7.25, "max_line_length": 26, "alphanum_fraction": 0.7586206897, "num_tokens": 7}
|
from astropy.table import Table
from yoshi.yoshi import run_one_yoshi
def main():
import argparse
parser = argparse.ArgumentParser(description="yoshi")
parser.add_argument('jobreq', type=str)
parser.add_argument('out', type=str)
opt = parser.parse_args()
obsjobs = Table.read(opt.jobreq, format='ascii')
obsjob = obsjobs[0]
rec = dict(zip(obsjob.colnames, obsjob))
results = []
for roll in range(0, 30):
req = rec.copy()
req['roll_targ'] = roll
report = run_one_yoshi(**req)
results.append(report)
Table(results).write(opt.out, format='ascii', overwrite=True)
if __name__ == '__main__':
main()
|
{"hexsha": "dd1783ea68665b07ea93edb50e8592df55e36b74", "size": 678, "ext": "py", "lang": "Python", "max_stars_repo_path": "run_example.py", "max_stars_repo_name": "sot/yoshi", "max_stars_repo_head_hexsha": "15550f2620ceb8e5e813df5761b9d3e6e86d68e4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "run_example.py", "max_issues_repo_name": "sot/yoshi", "max_issues_repo_head_hexsha": "15550f2620ceb8e5e813df5761b9d3e6e86d68e4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-18T15:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-28T14:56:57.000Z", "max_forks_repo_path": "run_example.py", "max_forks_repo_name": "sot/yoshi", "max_forks_repo_head_hexsha": "15550f2620ceb8e5e813df5761b9d3e6e86d68e4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.12, "max_line_length": 65, "alphanum_fraction": 0.6533923304, "include": true, "reason": "from astropy", "num_tokens": 171}
|
import matplotlib.pyplot as plt
import numpy as np
from numpy import fft, rot90, multiply
from PIL import Image
img = np.asarray(Image.open("school_of_fish.png").convert("L"))
school_of_fish = np.zeros((img.shape[0], img.shape[1]))
for i in range(img.shape[0]):
for j in range(img.shape[1]):
school_of_fish[i, j] = img[i, j][0] # getting R channel
school_of_fish = fft.fft2(school_of_fish)
# plot absolutes
absolute_matrix = np.log10(np.abs(school_of_fish)).astype(np.float64) # log scale, since without it the image will be entirely black
plt.imshow(absolute_matrix, cmap="gray")
plt.show()
# plot phases
phase_matrix = np.angle(school_of_fish)
plt.imshow(phase_matrix, cmap="gray")
plt.show()
fish = np.asarray(Image.open("fish.png").convert("L"))
fish_x = fish.shape[0]
fish_y = fish.shape[1]
w, h = school_of_fish.shape
fish = fft.fft2(rot90(fish, 2), s=(w, h))
absolute_correlations = abs(fft.ifft2(multiply(school_of_fish, fish)))
max_correlation = np.amax(absolute_correlations)
new_img = np.array(Image.open("school_of_fish.png").convert("RGB"))
for i in range(absolute_correlations.shape[0]):
for j in range(absolute_correlations.shape[1]):
if absolute_correlations[i, j] >= 0.5 * max_correlation:
new_img[i, j][0] = 200
result = Image.fromarray(new_img)
result.save("new_school_of_fish.jpg")
|
{"hexsha": "d7ab7d7d5d7e91d48a5520d1c8ec5f5632554101", "size": 1352, "ext": "py", "lang": "Python", "max_stars_repo_path": "lab9_FFT_applications/task_1/fish.py", "max_stars_repo_name": "j-adamczyk/Numerical-Algorithms", "max_stars_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-16T11:23:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-16T21:04:01.000Z", "max_issues_repo_path": "lab9_FFT_applications/task_1/fish.py", "max_issues_repo_name": "j-adamczyk/Numerical-Algorithms", "max_issues_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab9_FFT_applications/task_1/fish.py", "max_forks_repo_name": "j-adamczyk/Numerical-Algorithms", "max_forks_repo_head_hexsha": "47cfa8154bab448d1bf87b892d83e45c68dd2e2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0444444444, "max_line_length": 133, "alphanum_fraction": 0.7226331361, "include": true, "reason": "import numpy,from numpy", "num_tokens": 380}
|
subroutine ewweighted
c******************************************************************************
c This routine computes a weighted mean EW for one line from a set
c of models
c******************************************************************************
implicit real*8 (a-h,o-z)
include 'Atmos.com'
include 'Linex.com'
include 'Multimod.com'
c*****start the computations for a line
if (dabs(rwlgerror) .lt. 0.01) write (nf7out,1001)
ewweighttot = 0.
weighttot = 0
modcount = 0
iatom = int(atom1(lim1)+0.0001)
xngf = dlog10(xabund(iatom)*gf(lim1)) + deltangf
c*****for each model, interpolate in the curve-of-growth to get an EW_calc
c for the assumed abundance
do mmod=1,modtot
ncurvetot = nmodcurve(mmod,lim1)
do icurve=3,ncurvetot-2
if (gfmodtab(mmod,lim1,icurve) .gt. xngf) then
ic = icurve - 1
pp = (xngf-gfmodtab(mmod,lim1,ic))/0.15
rw = rwmodtab(mmod,lim1,ic-1)*(-pp)*(pp-1.)*(pp-2.)/6. +
. rwmodtab(mmod,lim1,ic)*(pp*pp-1.)*(pp-2.)/2. +
. rwmodtab(mmod,lim1,ic+1)*(-pp)*(pp+1.)*(pp-2.)/2. +
. rwmodtab(mmod,lim1,ic+2)*pp*(pp*pp-1.)/6.
ew = 10**rw*wave1(lim1)
go to 10
endif
enddo
c*****add this EW to the total, weighting it by flux*radius^2*relcount
10 ewweight = ew*weightmod(mmod,lim1)
weighttot = weighttot + weightmod(mmod,lim1)
ewweighttot = ewweighttot + ewweight
if (dabs(rwlgerror) .lt. 0.01)
. write (nf7out,1005) fmodinput(mmod),
. fmodoutput(mmod), radius(mmod), relcount(mmod),
. fluxmod(mmod,lim1), weightmod(mmod,lim1),
. 1000.*ew, 1000.*ewweight
enddo
c*****write out the mean EW
ewmod(lim1) = ewweighttot/weighttot
write (nf7out,1006) 1000.*ewmod(lim1),
. dlog10(xabund(iatom))+deltangf+12.
return
c*****format statements
1001 format ('MODFILE', 5x, 'COGOUT', 9x, 'RADIUS', 3x, '*COUNT',
. 5x, 'FLUX', 3x, 'WEIGHT', 5x, 'EW', ' EWWEIGHT')
1005 format (2a12, 1pe9.2, e9.2, e9.2, e9.2, 0pf7.1, 1pe9.2)
1006 format ('EWmean, Abundance =', f8.1, f8.2)
end
|
{"hexsha": "c6240b03cf67910cfec5dc53131bbd7d09a11a18", "size": 2326, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "MoogSource/Ewweighted.f", "max_stars_repo_name": "soylentdeen/MoogPy", "max_stars_repo_head_hexsha": "9485a7e302ef4d4339013f27672d1d5e7059a41f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-08-21T17:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T15:55:35.000Z", "max_issues_repo_path": "MoogSource/Ewweighted.f", "max_issues_repo_name": "soylentdeen/MoogPy", "max_issues_repo_head_hexsha": "9485a7e302ef4d4339013f27672d1d5e7059a41f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MoogSource/Ewweighted.f", "max_forks_repo_name": "soylentdeen/MoogPy", "max_forks_repo_head_hexsha": "9485a7e302ef4d4339013f27672d1d5e7059a41f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-03-28T09:39:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-20T07:47:39.000Z", "avg_line_length": 29.075, "max_line_length": 79, "alphanum_fraction": 0.5154772141, "num_tokens": 796}
|
using Printf
using Plots
using ProgressMeter
function animate(input, traj, filename; size = [800,400], fps :: Int64 = 10, last=0, dpi=150)
ENV["GKSwstype"]="nul"
U = traj.U
S = traj.S
D = traj.D
I = traj.I
snenc = @sprintf("%5.2f",sum(traj.nenc)/traj.nsteps)
if last < 1
last = traj.nsteps
end
# for subplot 1
lims=[-input.side/2,input.side/2]
# for subplot 2
time = traj.time
xmin = 0.
xmax = time[last]
ymin = 0.
ymax = 1.
p = Progress(last,1)
anim = @animate for i in 1:last
x = traj.atoms[i].x[:,1];
y = traj.atoms[i].x[:,2];
c = Vector{String}(undef,traj.n)
for j in 1:traj.n
if traj.atoms[i].status[j] == 0
c[j] = "blue"
elseif traj.atoms[i].status[j] == 1
c[j] = "red"
elseif traj.atoms[i].status[j] == 2
c[j] = "white"
elseif traj.atoms[i].status[j] == 3
c[j] = "green"
end
end
plot(size=size,layout=(1,2),framestyle=:box,dpi=dpi)
plot!(xlabel=@sprintf("Time: %4i",time[i]),subplot=1)
scatter!(x,y,label="",color=c,xlim=lims,ylim=lims,subplot=1,markersize=2,xticks=:none,yticks=:none)
#plot!(title=@sprintf("Tempo: %4i",i),subplot=2)
plot!(time[1:i],S[1:i],subplot=2,linewidth=2,label="",color="red")
plot!(time[1:i],U[1:i],subplot=2,linewidth=2,label="",color="blue")
plot!(time[1:i],D[1:i],subplot=2,linewidth=2,label="",color="black")
plot!(time[1:i],I[1:i],subplot=2,linewidth=2,label="",color="darkgreen")
plot!(xlim=[0,xmax],ylim=[ymin,ymax],subplot=2)
plot!(xlabel="Time",ylabel="Fraction of population",subplot=2)
fontsize=8
plot!(rectangle( 0, 0.37*xmax, 0.815*ymax, 1.02*ymax), opacity=0.9,label="",color=:white,subplot=2)
x = 0.05*(xmax-xmin)+xmin
d = 0.05*ymax ; y = [ ymax + d ]
annotate!(x,yd!(y,d),text("Susceptible: $(@sprintf("%4.2f%%",100*U[i]))",:left,fontsize,:serif,:blue),subplot=2)
annotate!(x,yd!(y,d),text("Sick: $(@sprintf("%4.2f%%",100*S[i]))",:left,fontsize,:serif,:red),subplot=2)
annotate!(x,yd!(y,d),text("Dead: $(@sprintf("%4.2f%%",100*D[i]))",:left,fontsize,:serif,:black),subplot=2)
annotate!(x,yd!(y,d),text("Immune: $(@sprintf("%4.2f%%",100*I[i]))",:left,fontsize,:serif,:darkgreen),subplot=2)
plot!(rectangle( 0.53*xmax, 1.00*xmax, 0.810*ymax, 1.02*ymax), opacity=0.9,label="",color=:white,subplot=2)
x = 0.98*(xmax-xmin)+xmin
d = 0.05*ymax ; y = [ ymax + d ]
annotate!(x,yd!(y,d),text("\"Temperature\": $(input.kavg_target)",:right,fontsize,:serif,:black),subplot=2)
annotate!(x,yd!(y,d),text("New encounters/step: $snenc",:right,fontsize,:serif,:black),subplot=2)
annotate!(x,yd!(y,d),text("Cross-section: $(input.xsec)",:right,fontsize,:serif,:black),subplot=2)
annotate!(x,yd!(y,d),text("P(contamination): $(input.pcont)",:right,fontsize,:serif,:black),subplot=2)
next!(p)
end
gif(anim, filename, fps = fps)
end
|
{"hexsha": "498b1d9f435292a969e41744a258df2c66a1ed5c", "size": 2928, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/animate.jl", "max_stars_repo_name": "m3g/kinetics", "max_stars_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-27T19:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T09:24:24.000Z", "max_issues_repo_path": "src/animate.jl", "max_issues_repo_name": "m3g/kinetics", "max_issues_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/animate.jl", "max_forks_repo_name": "m3g/kinetics", "max_forks_repo_head_hexsha": "f84fbd7120d8848b1bbfe5c9ec936fd2690e3e8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-28T17:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-28T17:20:58.000Z", "avg_line_length": 33.2727272727, "max_line_length": 116, "alphanum_fraction": 0.600068306, "num_tokens": 1076}
|
import os
import sys
import tarfile
import collections
import torch.utils.data as data
import shutil
import numpy as np
import random
from PIL import Image
from torchvision.datasets.utils import download_url, check_integrity
def isic_cmap(N=256, normalized=False):
def bitget(byteval, idx):
return ((byteval & (1 << idx)) != 0)
dtype = 'float32' if normalized else 'uint8'
cmap = np.zeros((N, 3), dtype=dtype)
for i in range(N):
r = g = b = 0
c = i
for j in range(8):
r = r | (bitget(c, 0) << 7-j)
g = g | (bitget(c, 1) << 7-j)
b = b | (bitget(c, 2) << 7-j)
c = c >> 3
cmap[i] = np.array([r, g, b])
cmap = cmap/255 if normalized else cmap
return cmap
class ISIC(data.Dataset):
cmap = isic_cmap()
def __init__(self, root, image_set='train', augmentation_prob = 0.2, transform=None):
self.root = root
self.GT_paths = root[:-1]+'_GT/'
self.image_paths = list(map(lambda x: os.path.join(root, x), os.listdir(root)))
self.image_set = image_set
self.transform = transform
self.augmentation_prob = augmentation_prob
self.RotationDegree = [0,90,180,270]
print("# of {} samples: {}".format(self.image_set, len(self.image_paths)))
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is the image segmentation.
"""
image_path = self.image_paths[index]
filename = image_path.split('_')[-1][:-len(".jpg")]
GT_path = self.GT_paths + 'ISIC_' + filename + '_segmentation.png'
img = Image.open(image_path).convert('RGB')
target = Image.open(GT_path)
target = Image.fromarray(np.asarray(target)/255)
if self.transform is not None:
img, target = self.transform(img, target)
return img, target
def __len__(self):
return len(self.image_paths)
@classmethod
def decode_target(cls, target):
"""decode semantic mask to RGB image"""
return cls.cmap[target]
def download_extract(url, root, filename, md5):
download_url(url, root, filename, md5)
with tarfile.open(os.path.join(root, filename), "r") as tar:
tar.extractall(path=root)
|
{"hexsha": "8eb6d63e6aebb118e8142bac616fe4474d8a9d96", "size": 2347, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/semantic_segmentation/deeplabv3plus/datasets/isic.py", "max_stars_repo_name": "mazeiomli/ARMA-Networks", "max_stars_repo_head_hexsha": "a7932abad7c4022311c0ec5263a302ab1cc6a354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/semantic_segmentation/deeplabv3plus/datasets/isic.py", "max_issues_repo_name": "mazeiomli/ARMA-Networks", "max_issues_repo_head_hexsha": "a7932abad7c4022311c0ec5263a302ab1cc6a354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/semantic_segmentation/deeplabv3plus/datasets/isic.py", "max_forks_repo_name": "mazeiomli/ARMA-Networks", "max_forks_repo_head_hexsha": "a7932abad7c4022311c0ec5263a302ab1cc6a354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-17T23:08:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T23:08:12.000Z", "avg_line_length": 28.6219512195, "max_line_length": 89, "alphanum_fraction": 0.5990626331, "include": true, "reason": "import numpy", "num_tokens": 606}
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 15:15:50 2020
@author: Patrick
"""
"""Implementation of Fast Orthogonal Search"""
#==============================================
#nonlinear_data_generation.py
#==============================================
import numpy as np
from matplotlib import pyplot as plt
from FOS import FOS
def Nonlinear_Generation(mu, sigma, x, y, P, case_index, noise):
# case 1:
if case_index ==1:
[a0, a1, a2, a3, a4, a5, a6] = [0.05, 0.4, 0.1, -0.2, -0.1, 0.33, 0.0] # 2nd order
# case 2:
elif case_index ==2:
[a0, a1, a2, a3, a4, a5, a6] = [0.01, 0.2, 0.3, -0.1, 0.05, 0.2, 0.0] # 2nd order
# case 3:
else:
[a0, a1, a2, a3, a4, a5, a6] = [0.1, 0.1, 0.5, -0.3, 0.22, -0.4, 0.1] # 3rd order
for n in range(2, len(y)):
y[n] = a0 + a1*y[n-1]+ a2*x[n-1]+ a3*x[n]*x[n-2]+ a4*y[n-1]*y[n-2]
+a5*x[n-2]*y[n-2]+ a6*x[n-1]*x[n-2]*y[n-2]
yn = y + P*np.var(y)* np.expand_dims(np.random.normal(mu, sigma,len(x)), axis=1)
if noise==True:
y = yn
else:
y = y
return y
|
{"hexsha": "cd92d9a7e42eb0898694db304eea9d1925010974", "size": 1098, "ext": "py", "lang": "Python", "max_stars_repo_path": "code/nonlinear_data_generation.py", "max_stars_repo_name": "guangyizhangbci/Implementation-of-Fast-Orthogonal-Search", "max_stars_repo_head_hexsha": "17feb7569d1ab345c3cd234d572506959b9e70c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2022-01-29T07:09:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T22:06:40.000Z", "max_issues_repo_path": "code/nonlinear_data_generation.py", "max_issues_repo_name": "guangyizhangbci/Implementation-of-Fast-Orthogonal-Search", "max_issues_repo_head_hexsha": "17feb7569d1ab345c3cd234d572506959b9e70c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/nonlinear_data_generation.py", "max_forks_repo_name": "guangyizhangbci/Implementation-of-Fast-Orthogonal-Search", "max_forks_repo_head_hexsha": "17feb7569d1ab345c3cd234d572506959b9e70c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1428571429, "max_line_length": 93, "alphanum_fraction": 0.4790528233, "include": true, "reason": "import numpy", "num_tokens": 459}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import hashlib
import shutil
import numpy as np
import tensorflow as tf
from tf_datasets.core.download import download_http, extract_gzip
from tf_datasets.core.base_dataset import BaseDataset
from tf_datasets.core.dataset_utils import create_image_example
from tf_datasets.core.dataset_utils import create_dataset_split
from tf_datasets.core.dataset_utils import ImageCoder
slim = tf.contrib.slim
class pascal_voc_2017(BaseDataset):
class_names = [
'zero',
'one',
'two',
'three',
'four',
'five',
'size',
'seven',
'eight',
'nine',
]
filenames = ['VOCtest_06-Nov-2007',
'VOCtrainval_06-Nov-2007',
'VOCdevkit_08-Jun-2007']
def __init__(self, dataset_dir):
super().__init__(dataset_dir, self.class_names, zero_based_labels=True)
self.dataset_name = 'mnist'
self.download_dir = os.path.join(self.dataset_dir, 'download')
self._coder = ImageCoder()
def download(self):
try:
os.makedirs(self.download_dir)
except FileExistsError:
pass
data_url = 'http://yann.lecun.com/exdb/mnist/'
for filename in self.filenames:
output_path = os.path.join(self.download_dir, filename)
if not os.path.exists(output_path):
download_http(data_url + filename, output_path)
def extract(self):
for filename in self.filenames:
output_path = os.path.join(self.download_dir, filename[:-3])
if not os.path.exists(output_path):
extract_gzip(os.path.join(self.download_dir,
filename), self.download_dir)
def convert(self):
splits = self._get_data_points()
split_names = ['train', 'validation']
for split, split_name in zip(splits, split_names):
create_dataset_split('mnist',
self.dataset_dir,
split_name,
split,
self._convert_to_example)
self.write_label_file()
def cleanup(self):
shutil.rmtree(self.download_dir)
def _get_data_points(self):
def _get_data_points_from_mnist_files(image_file, label_file,
num_data_points):
with open(os.path.join(self.download_dir, label_file), 'rb') as f:
f.read(8)
buf = f.read(1 * num_data_points)
labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
with open(os.path.join(self.download_dir, image_file), 'rb') as f:
f.read(16)
buf = f.read(self.image_size * self.image_size *
num_data_points * self.image_channel)
images = np.frombuffer(buf, dtype=np.uint8)
images = images.reshape(
num_data_points,
self.image_size,
self.image_size,
self.image_channel
)
assert labels.shape[0] == images.shape[0]
data_points = []
for i in range(images.shape[0]):
data_points.append((labels[i], images[i]))
return data_points
training = _get_data_points_from_mnist_files(
'train-images-idx3-ubyte',
'train-labels-idx1-ubyte',
self.num_training)
validation = _get_data_points_from_mnist_files(
't10k-images-idx3-ubyte',
't10k-labels-idx1-ubyte',
self.num_validation)
return training, validation
def _convert_to_example(self, data_point):
label, image = data_point
encoded = self._coder.encode_png(image)
image_format = 'png'
height, width, channels = (
self.image_size,
self.image_size,
self.image_channel
)
class_name = self.labels_to_class_names[label]
key = hashlib.sha256(encoded).hexdigest()
return create_image_example(height,
width,
channels,
key,
encoded,
image_format,
class_name,
label)
def load(self, split_name, reader=None):
# TODO(tmattio): Implement the load methods
pass
|
{"hexsha": "b88ca70536d6f8a52de28d4836bcafe92b5c0a0c", "size": 4287, "ext": "py", "lang": "Python", "max_stars_repo_path": "tf_datasets/datasets_old/pascal_voc_2007.py", "max_stars_repo_name": "tmattio/tf_datasets", "max_stars_repo_head_hexsha": "03a11554355f3b7dc9acb3b01e7c98daca463bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-09-15T07:25:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T14:40:19.000Z", "max_issues_repo_path": "tf_datasets/datasets_old/pascal_voc_2007.py", "max_issues_repo_name": "tmattio/tf_datasets", "max_issues_repo_head_hexsha": "03a11554355f3b7dc9acb3b01e7c98daca463bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tf_datasets/datasets_old/pascal_voc_2007.py", "max_forks_repo_name": "tmattio/tf_datasets", "max_forks_repo_head_hexsha": "03a11554355f3b7dc9acb3b01e7c98daca463bfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7708333333, "max_line_length": 75, "alphanum_fraction": 0.6127828318, "include": true, "reason": "import numpy", "num_tokens": 930}
|
"""
Draw Figures - Chapter 5
This script generates all of the figures that appear in Chapter 5 of the textbook.
Ported from MATLAB Code
Nicholas O'Donoughue
25 March 2021
"""
import utils
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from examples import chapter5
def make_all_figures(close_figs=False):
"""
Call all the figure generators for this chapter
:close_figs: Boolean flag. If true, will close all figures after generating them; for batch scripting.
Default=False
:return: List of figure handles
"""
# Initializes colorSet - Mx3 RGB vector for successive plot lines
colors = plt.get_cmap("tab10")
# Reset the random number generator, to ensure reproducability
rng = np.random.default_rng(0)
# Find the output directory
prefix = utils.init_output_dir('chapter5')
# Activate seaborn for prettier plots
sns.set()
# Generate all figures
fig4 = make_figure_4(prefix, rng, colors)
fig6 = make_figure_6(prefix, rng, colors)
fig7 = make_figure_7(prefix, rng, colors)
figs = [fig4, fig6, fig7]
if close_figs:
for fig in figs:
plt.close(fig)
return None
else:
plt.show()
return figs
def make_figure_4(prefix=None, rng=None, colors=None):
"""
Figure 4 - Example 5.1 - Superhet Performance
Ported from MATLAB Code
Nicholas O'Donoughue
25 March 2021
:param prefix: output directory to place generated figure
:param rng: random number generator
:param colors: colormap for plots
:return: figure handle
"""
if rng is None:
rng = np.random.default_rng(0)
if colors is None:
colors = plt.get_cmap('tab10')
fig4 = chapter5.example1()
# Save figure
if prefix is not None:
plt.savefig(prefix + 'fig4.svg')
plt.savefig(prefix + 'fig4.png')
return fig4
def make_figure_6(prefix=None, rng=None, colors=None):
"""
Figure 6 - Example 5.2 - FMCW Radar
Ported from MATLAB Code
Nicholas O'Donoughue
25 March 2021
:param prefix: output directory to place generated figure
:param rng: random number generator
:param colors: colormap for plots
:return: figure handle
"""
if rng is None:
rng = np.random.default_rng(0)
if colors is None:
colors = plt.get_cmap('tab10')
fig6 = chapter5.example2()
# Save figure
if prefix is not None:
plt.savefig(prefix + 'fig6.svg')
plt.savefig(prefix + 'fig6.png')
return fig6
def make_figure_7(prefix=None, rng=None, colors=None):
"""
Figure 7 - Example 5.3 - Pulsed Radar
Ported from MATLAB Code
Nicholas O'Donoughue
25 March 2021
:param prefix: output directory to place generated figure
:param rng: random number generator
:param colors: colormap for plots
:return: figure handle
"""
if rng is None:
rng = np.random.default_rng(0)
if colors is None:
colors = plt.get_cmap('tab10')
fig7 = chapter5.example3()
# Save figure
if prefix is not None:
plt.savefig(prefix + 'fig7.svg')
plt.savefig(prefix + 'fig7.png')
return fig7
|
{"hexsha": "03a8b8f37846a6da9072046a4f408d93689eb1b0", "size": 3245, "ext": "py", "lang": "Python", "max_stars_repo_path": "make_figures/chapter5.py", "max_stars_repo_name": "nodonoughue/emitter-detection-python", "max_stars_repo_head_hexsha": "ebff19acebcc1edfd941280e05f8ddf2ff20c974", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "make_figures/chapter5.py", "max_issues_repo_name": "nodonoughue/emitter-detection-python", "max_issues_repo_head_hexsha": "ebff19acebcc1edfd941280e05f8ddf2ff20c974", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "make_figures/chapter5.py", "max_forks_repo_name": "nodonoughue/emitter-detection-python", "max_forks_repo_head_hexsha": "ebff19acebcc1edfd941280e05f8ddf2ff20c974", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7785234899, "max_line_length": 107, "alphanum_fraction": 0.6508474576, "include": true, "reason": "import numpy", "num_tokens": 830}
|
#!/usr/bin/r
suppressMessages(library(Rcpp))
suppressMessages(library(inline))
foo <- '
int i, j, na, nb, nab;
double *xa, *xb, *xab;
SEXP ab;
PROTECT(a = AS_NUMERIC(a));
PROTECT(b = AS_NUMERIC(b));
na = LENGTH(a); nb = LENGTH(b); nab = na + nb - 1;
PROTECT(ab = NEW_NUMERIC(nab));
xa = NUMERIC_POINTER(a); xb = NUMERIC_POINTER(b);
xab = NUMERIC_POINTER(ab);
for(i = 0; i < nab; i++) xab[i] = 0.0;
for(i = 0; i < na; i++)
for(j = 0; j < nb; j++) xab[i + j] += xa[i] * xb[j];
UNPROTECT(3);
return(ab);
'
funx <- cfunction(signature(a="numeric",b="numeric"), foo, Rcpp=FALSE, verbose=FALSE)
funx(a=1:20, b=2:11)
|
{"hexsha": "8a4083833792dbee55163fbb7b3b50e27049f84b", "size": 646, "ext": "r", "lang": "R", "max_stars_repo_path": "packrat/lib/x86_64-w64-mingw32/3.2.1/Rcpp/examples/RcppInline/RcppSimpleExample.r", "max_stars_repo_name": "Fredin/El-Habla-de-Monterrey", "max_stars_repo_head_hexsha": "dd3333663bf5f66a751033166137109f03b39ac7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18, "max_stars_repo_stars_event_min_datetime": "2019-05-31T14:18:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T11:30:32.000Z", "max_issues_repo_path": "packrat/lib/x86_64-w64-mingw32/3.2.1/Rcpp/examples/RcppInline/RcppSimpleExample.r", "max_issues_repo_name": "Fredin/El-Habla-de-Monterrey", "max_issues_repo_head_hexsha": "dd3333663bf5f66a751033166137109f03b39ac7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-05-31T14:19:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T16:09:52.000Z", "max_forks_repo_path": "packrat/lib/x86_64-w64-mingw32/3.2.1/Rcpp/examples/RcppInline/RcppSimpleExample.r", "max_forks_repo_name": "Fredin/El-Habla-de-Monterrey", "max_forks_repo_head_hexsha": "dd3333663bf5f66a751033166137109f03b39ac7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-05-29T12:44:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T17:16:24.000Z", "avg_line_length": 23.0714285714, "max_line_length": 85, "alphanum_fraction": 0.5835913313, "num_tokens": 233}
|
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from scipy import optimize
from sklearn.utils.class_weight import compute_class_weight
from sklearn.preprocessing import LabelEncoder
from scipy import optimize
def make_class_with_unscored_labels(labels, unscored_labels_df):
df_labels = pd.DataFrame(labels)
for i in range(len(unscored_labels_df.iloc[0:,1])):
df_labels.replace(to_replace=str(unscored_labels_df.iloc[i,1]), inplace=True ,value="unscored class", regex=True)
return df_labels
def plot_classes(classes,y,scored_labels_df, plt_name="my_plot"):
for j in range(len(classes)):
for i in range(len(scored_labels_df.iloc[:,1])):
if (str(scored_labels_df.iloc[:,1][i]) == classes[j]):
classes[j] = scored_labels_df.iloc[:,0][i]
plt.figure(figsize=(30,20))
plt.bar(x=classes,height=y.sum(axis=0))
plt.title("Distribution of Diagnosis", color = "black")
plt.tick_params(axis="both", colors = "black")
plt.xlabel("Diagnosis", color = "black", fontsize=30)
plt.ylabel("Count", color = "black",fontsize=30)
plt.xticks(rotation=90, fontsize=20)
plt.yticks(fontsize = 20)
plt.savefig("Results/ECG_results/" + plt_name + ".png",dpi=100)
plt.show()
def train_test_split_unbalanced_data(X,y,samples_pr_class):
test_index = []
for i in range(len(y.T)):
test_index.append(np.random.choice(np.where(y.T[i] == 1)[0],size = samples_pr_class, replace=False))
test_index = np.unique(np.array(test_index).ravel())
X_train = X.drop(X.iloc[test_index].index)
y_train = np.delete(y,test_index,axis=0)
X_test = X.iloc[test_index]
y_test = y[test_index]
return X_train,y_train,X_test,y_test
def NN_ECG(input_shape,output_shape,n_units = 100):
input_layer = tf.keras.layers.Input(shape=(input_shape))
mod1 = tf.keras.layers.Dense(units=n_units, activation=tf.keras.layers.PReLU() , kernel_initializer='normal')(input_layer)
mod1 = tf.keras.layers.Dense(units=n_units, activation=tf.keras.layers.LeakyReLU(), kernel_initializer='normal')(mod1)
mod1 = tf.keras.layers.Dense(units=n_units, activation="relu" , kernel_initializer='normal')(mod1)
output_layer = tf.keras.layers.Dense(output_shape, activation="sigmoid" , kernel_initializer='normal')(mod1)
model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(loss=tf.losses.BinaryCrossentropy(), optimizer=optimizer, metrics=[tf.metrics.CategoricalAccuracy()])
return model
def compute_beta_measures(labels, outputs, beta):
num_recordings, num_classes = np.shape(labels)
A = compute_confusion_matrices(labels, outputs, normalize=True)
f_beta_measure = np.zeros(num_classes)
g_beta_measure = np.zeros(num_classes)
for k in range(num_classes):
tp, fp, fn, tn = A[k, 1, 1], A[k, 1, 0], A[k, 0, 1], A[k, 0, 0]
if (1+beta**2)*tp + fp + beta**2*fn:
f_beta_measure[k] = float((1+beta**2)*tp) / float((1+beta**2)*tp + fp + beta**2*fn)
else:
f_beta_measure[k] = float('nan')
if tp + fp + beta*fn:
g_beta_measure[k] = float(tp) / float(tp + fp + beta*fn)
else:
g_beta_measure[k] = float('nan')
macro_f_beta_measure = np.nanmean(f_beta_measure)
macro_g_beta_measure = np.nanmean(g_beta_measure)
return macro_f_beta_measure, macro_g_beta_measure
def compute_modified_confusion_matrix(labels, outputs):
# Compute a binary multi-class, multi-label confusion matrix, where the rows
# are the labels and the columns are the outputs.
num_recordings, num_classes = np.shape(labels)
A = np.zeros((num_classes, num_classes))
# Iterate over all of the recordings.
for i in range(num_recordings):
# Calculate the number of positive labels and/or outputs.
normalization = float(max(np.sum(np.any((labels[i, :], outputs[i, :]), axis=0)), 1))
# Iterate over all of the classes.
for j in range(num_classes):
# Assign full and/or partial credit for each positive class.
if labels[i, j]:
for k in range(num_classes):
if outputs[i, k]:
A[j, k] += 1.0/normalization
return A
def compute_confusion_matrices(labels, outputs, normalize=False):
# Compute a binary confusion matrix for each class k:
#
# [TN_k FN_k]
# [FP_k TP_k]
#
# If the normalize variable is set to true, then normalize the contributions
# to the confusion matrix by the number of labels per recording.
num_recordings, num_classes = np.shape(labels)
if not normalize:
A = np.zeros((num_classes, 2, 2))
for i in range(num_recordings):
for j in range(num_classes):
if labels[i, j]==1 and outputs[i, j]==1: # TP
A[j, 1, 1] += 1
elif labels[i, j]==0 and outputs[i, j]==1: # FP
A[j, 1, 0] += 1
elif labels[i, j]==1 and outputs[i, j]==0: # FN
A[j, 0, 1] += 1
elif labels[i, j]==0 and outputs[i, j]==0: # TN
A[j, 0, 0] += 1
else: # This condition should not happen.
raise ValueError('Error in computing the confusion matrix.')
else:
A = np.zeros((num_classes, 2, 2))
for i in range(num_recordings):
normalization = float(max(np.sum(labels[i, :]), 1))
for j in range(num_classes):
if labels[i, j]==1 and outputs[i, j]==1: # TP
A[j, 1, 1] += 1.0/normalization
elif labels[i, j]==0 and outputs[i, j]==1: # FP
A[j, 1, 0] += 1.0/normalization
elif labels[i, j]==1 and outputs[i, j]==0: # FN
A[j, 0, 1] += 1.0/normalization
elif labels[i, j]==0 and outputs[i, j]==0: # TN
A[j, 0, 0] += 1.0/normalization
else: # This condition should not happen.
raise ValueError('Error in computing the confusion matrix.')
return A
def get_new_labels(y):
y_new = LabelEncoder().fit_transform([''.join(str(l)) for l in y])
return y_new
|
{"hexsha": "5425e269113b300dc5ffbfcb80574c1607ed0081", "size": 6332, "ext": "py", "lang": "Python", "max_stars_repo_path": "Scripts/ECG_processing.py", "max_stars_repo_name": "Bsingstad/FYS-STK4155-oblig2", "max_stars_repo_head_hexsha": "81a587e3a64dd8f7ff1ca5868c09db2d4dccf896", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scripts/ECG_processing.py", "max_issues_repo_name": "Bsingstad/FYS-STK4155-oblig2", "max_issues_repo_head_hexsha": "81a587e3a64dd8f7ff1ca5868c09db2d4dccf896", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-13T22:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-13T22:16:54.000Z", "max_forks_repo_path": "Scripts/ECG_processing.py", "max_forks_repo_name": "Bsingstad/FYS-STK4155-oblig2", "max_forks_repo_head_hexsha": "81a587e3a64dd8f7ff1ca5868c09db2d4dccf896", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3291925466, "max_line_length": 126, "alphanum_fraction": 0.6296588756, "include": true, "reason": "import numpy,from scipy", "num_tokens": 1627}
|
import nlcontrol.systems as nlSystems
import numpy as np
from simupy.systems import DynamicalSystem, SystemFromCallable
def append(*signals):
"""
Append a N_i-channel signals to a sum(N_i, i)-channel signal. Add as many signals as needed. The order of appearance determines the index of the output.
Parameters:
-----------
signals: nlcontrol.signals object
the signals that need to be appended to a new signal.
Returns:
--------
A SystemBase object with parameters:
states : NoneType
None
inputs : NoneType
None
sys : SystemFromCallable object
with a function 'callable' returning a numpy array in function of time t, 0 inputs, and dim outputs.
Examples:
---------
* Append steps and sinusoids into one system:
>>> step1_sig = step(step_times=[2.5, 3.5], begin_values=[1.8, 0.5], end_values=[-1.2, 2.1])
>>> step2_sig = step(step_times=0.2, begin_values=-2.3, end_values=0.8)
>>> sin_sig = sinusoid(amplitude=2.3, frequency=1.5, phase_shift=-0.3)
>>> appended_signal = append(step1_sig, sin_sig, step2_sig)
>>> appended_signal.simulation(5, plot=True)
"""
if len(signals) == 1:
error_text = '[signals.append] You need at least two signals to append.'
raise AssertionError(error_text)
dim = 0
for i in range(len(signals)):
signal = signals[i].system
dim += signal.dim_output
if not isinstance(signal, DynamicalSystem):
error_text = '[signals.append] Only append signal objects.'
raise AssertionError(error_text)
def callable(t, *args):
values = np.array([])
for signal in signals:
values = np.append(values, signal.system.output_equation_function(t))
return values
system = SystemFromCallable(callable, 0, dim)
return nlSystems.SystemBase(states=None, inputs=None, sys=system)
def add(signal1, signal2):
"""
Add the channels of signal1 to the channels of signal2. Be aware that the dimensions of the outputs of both signals should be the same.
y1 = [y1_1, y1_2, ..., y1_n]
y2 = [y2_1, y2_2, ..., y2_n]
y = y1 + y2 = [y1_1 + y2_1, y1_2 + y2_2, ..., y1_n + y2_n]
Parameters:
-----------
signal1: nlcontrol.signals object
the first signal that will be added.
signal2: nlcontrol.signals object
the second signal that will be added.
Returns:
--------
A SystemBase object with parameters:
states : NoneType
None
inputs : NoneType
None
sys : SystemFromCallable object
with a function 'callable' returning a numpy array in function of time t, 0 inputs, and dim outputs.
Examples:
---------
* Create two sinusoids, the average value has to change after 1.5 and 3.5s respectively:
>>> sin_sig = sinusoid(2)
>>> step_sig = step(step_times=[1.5, 3.5])
>>> added_signal = add(sin_sig, step_sig)
>>> added_signal.simulation(5, plot=True)
"""
if not isinstance(signal1.system, DynamicalSystem):
error_text = '[signals.add] signal1 should be a nlcontrol.signals object.'
raise AssertionError(error_text)
if not isinstance(signal2.system, DynamicalSystem):
error_text = '[signals.add] signal2 should be a nlcontrol.signals object.'
raise AssertionError(error_text)
if signal1.system.dim_output != signal2.system.dim_output:
error_text = '[signals.add] The output dimension of signal1 and signal2 should be equal.'
raise AssertionError(error_text)
else:
dim = signal1.system.dim_output
def callable(t, *args):
return np.array([s1 + s2 for s1, s2 \
in zip(signal1.system.output_equation_function(t), signal2.system.output_equation_function(t))])
system = SystemFromCallable(callable, 0, dim)
return nlSystems.SystemBase(states=None, inputs=None, sys=system)
|
{"hexsha": "26f6d83ba26fee97e72db771fad735900e451223", "size": 4126, "ext": "py", "lang": "Python", "max_stars_repo_path": "nlcontrol/signals/signal_tools.py", "max_stars_repo_name": "LodeLand/nlcontrol", "max_stars_repo_head_hexsha": "9de5cc34cbc4835fc32e8b9c20ef3ea9da509fd9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-30T11:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T15:24:18.000Z", "max_issues_repo_path": "nlcontrol/signals/signal_tools.py", "max_issues_repo_name": "LodeLand/nlcontrol", "max_issues_repo_head_hexsha": "9de5cc34cbc4835fc32e8b9c20ef3ea9da509fd9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-10-02T09:17:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:49:14.000Z", "max_forks_repo_path": "nlcontrol/signals/signal_tools.py", "max_forks_repo_name": "LodeLand/nlcontrol", "max_forks_repo_head_hexsha": "9de5cc34cbc4835fc32e8b9c20ef3ea9da509fd9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-06-07T23:53:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T15:17:49.000Z", "avg_line_length": 40.0582524272, "max_line_length": 156, "alphanum_fraction": 0.6253029569, "include": true, "reason": "import numpy", "num_tokens": 988}
|
import numpy as np
import cv2
input = cv2.imread('input/strawberry.jpg')
height, width = input_image.shape[:2]
x_gauss = cv2.getGaussianKernel(width,250)
y_gauss = cv2.getGaussianKernel(height,200)
kernel = x_gauss * y_gauss.T
mask = kernel * 255 / np.linalg.norm(kernel)
output[:,:,0] = input[:,:,0] * mask
output[:,:,1] = input[:,:,1] * mask
output[:,:,2] = input[:,:,2] * mask
cv2.imshow('vignette', output)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
{"hexsha": "abb4ba64e345114c0b5be170656a0f297a42cd96", "size": 511, "ext": "py", "lang": "Python", "max_stars_repo_path": "Vignette_filter.py", "max_stars_repo_name": "OhmVikrant/Vignette-Filter-using-OpenCV", "max_stars_repo_head_hexsha": "4ffe8ad956370721cea9b648765e22d6ae56cdcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-09-05T19:03:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T19:08:56.000Z", "max_issues_repo_path": "Vignette_filter.py", "max_issues_repo_name": "OhmVikrant/Vignette-Filter-using-OpenCV", "max_issues_repo_head_hexsha": "4ffe8ad956370721cea9b648765e22d6ae56cdcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vignette_filter.py", "max_forks_repo_name": "OhmVikrant/Vignette-Filter-using-OpenCV", "max_forks_repo_head_hexsha": "4ffe8ad956370721cea9b648765e22d6ae56cdcc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.44, "max_line_length": 47, "alphanum_fraction": 0.6105675147, "include": true, "reason": "import numpy", "num_tokens": 151}
|
From mathcomp Require Import all_ssreflect.
Section Rename.
Definition upren r x :=
if x is x.+1 then (r x).+1 else 0.
Definition upnren r n := iter n upren r.
Corollary upnrenS r n x : upren (upnren r n) x = upnren (upren r) n x.
Proof. by rewrite /upnren -iterSr. Qed.
Lemma upnren_unfold r n : forall x,
upnren r n x = if x < n then x else n + r (x - n).
Proof.
induction n => [ ? | [ | ? ] ] //=.
- by rewrite subn0.
- by rewrite IHn (fun_if succn).
Qed.
Lemma eq_upren r r' : forall x,
(0 < x -> r x.-1 = r' x.-1) ->
upren r x = upren r' x.
Proof. by rewrite /upren => [ [ | ? /= -> ] ]. Qed.
Lemma eq_upnren r r' n x :
(n <= x -> r (x - n) = r' (x - n)) ->
upnren r n x = upnren r' n x.
Proof.
rewrite !upnren_unfold.
by case: (leqP n x) => [ ? -> | ].
Qed.
Lemma upren_id : forall x, upren id x = x.
Proof. by move => [ | ? ]. Qed.
Lemma upnren_id n : forall x, upnren id n x = x.
Proof.
induction n => ? //=.
by rewrite (eq_upren _ id _ (fun _ => IHn _)) upren_id.
Qed.
Lemma upren_comp r r' :
upren (r \o r') =1 upren r \o upren r'.
Proof. by move => [ | ? ]. Qed.
Lemma upnren_comp n : forall r r',
upnren (r \o r') n =1 upnren r n \o upnren r' n.
Proof.
induction n => ? ? ? //=.
by rewrite (eq_upren _ _ _ (fun _ => IHn _ _ _)) upren_comp.
Qed.
Class Rename (term : Set) :=
{ Var : nat -> term;
rename : (nat -> nat) -> term -> term;
rename_Var : forall r x, rename r (Var x) = Var (r x);
eq_rename : forall t r r', (forall x, r x = r' x) -> rename r t = rename r' t }.
Class RenameLemmas (term : Set) {RenameTerm : Rename term} :=
{ rename_id : forall t, rename id t = t;
rename_rename_comp : forall t r r', rename r (rename r' t) = rename (r \o r') t }.
Context {term : Set} {RenameTerm : Rename term}.
Lemma rename_id_upren t :
rename id t = t ->
rename (upren id) t = t.
Proof. by rewrite (eq_rename _ _ _ upren_id). Qed.
Lemma rename_id_upnren t
(_ : rename id t = t) n :
rename (upnren id n) t = t.
Proof. by rewrite (eq_rename _ _ _ (upnren_id _)). Qed.
Lemma rename_rename_comp_upren t
(_ : forall r r', rename r (rename r' t) = rename (r \o r') t) r r' :
rename (upren r) (rename (upren r') t) = rename (upren (r \o r')) t.
Proof. by rewrite (eq_rename _ _ _ (upren_comp _ _)). Qed.
Lemma rename_rename_comp_upnren t
(_ : forall r r', rename r (rename r' t) = rename (r \o r') t) r r' n :
rename (upnren r n) (rename (upnren r' n) t) = rename (upnren (r \o r') n) t.
Proof. by rewrite (eq_rename _ _ _ (upnren_comp _ _ _)). Qed.
End Rename.
Section Subst.
Context {term : Set} {RenameTerm : Rename term} {RenameLemmaTerm : RenameLemmas term}.
Definition up s x :=
if x is x.+1 then rename succn (s x) else Var 0.
Definition upn s n := iter n up s.
Corollary upnS s n x : up (upn s n) x = upn (up s) n x.
Proof. by rewrite /upn -iterSr. Qed.
Lemma upn_unfold s n : forall x,
upn s n x = if x < n then Var x else rename (addn n) (s (x - n)).
Proof.
induction n => [ ? | [ | ? ] ] //=.
- by rewrite subn0 (eq_rename _ _ id) ?rename_id.
- rewrite ltnS subSS IHn (fun_if (rename succn)) rename_Var rename_rename_comp.
congr (if _ then _ else _).
Qed.
Lemma eq_up s s' : forall x,
(0 < x -> s x.-1 = s' x.-1) ->
up s x = up s' x.
Proof. by move => [ | ? /= -> ]. Qed.
Lemma eq_upn s s' n x :
(n <= x -> s (x - n) = s' (x - n)) ->
upn s n x = upn s' n x.
Proof. rewrite !upn_unfold. by case: (leqP n x) => [ ? -> | ]. Qed.
Lemma up_Var : forall x, up Var x = Var x.
Proof. move => [ | ? ] //=. by rewrite rename_Var. Qed.
Lemma upn_Var n : forall x, upn Var n x = Var x.
Proof.
induction n => ? //=.
by rewrite (eq_up _ Var _ (fun _ => IHn _)) up_Var.
Qed.
Lemma up_upren r : Var \o upren r =1 up (Var \o r).
Proof. move => [ | ? ] //=. by rewrite rename_Var. Qed.
Lemma upn_upnren r n : Var \o upnren r n =1 upn (Var \o r) n.
Proof.
induction n => ? //=.
by rewrite -(eq_up _ _ _ (fun _ => IHn _)) -up_upren.
Qed.
Lemma up_upren_comp s r :
up (s \o r) =1 up s \o upren r.
Proof. by move => [ | ? ]. Qed.
Lemma upn_upnren_comp s r n :
upn (s \o r) n =1 upn s n \o upnren r n.
Proof.
induction n => ? //=.
by rewrite (eq_up _ _ _ (fun _ => IHn _)) up_upren_comp.
Qed.
Lemma upren_up_comp r s :
up (rename r \o s) =1 rename (upren r) \o up s.
Proof.
move => [ | ? ] /=.
- by rewrite rename_Var.
- rewrite !rename_rename_comp.
exact: eq_rename.
Qed.
Lemma upnren_upn_comp r s n :
upn (rename r \o s) n =1 rename (upnren r n) \o upn s n.
Proof.
induction n => ? //=.
by rewrite (eq_up _ _ _ (fun _ => IHn _)) upren_up_comp.
Qed.
Class Subst :=
{ subst : (nat -> term) -> term -> term;
subst_Var : forall s x, subst s (Var x) = s x;
eq_subst : forall t s s', (forall x, s x = s' x) -> subst s t = subst s' t }.
Context {SubstTerm : Subst}.
Lemma rename_subst_up t
(_ : forall r, rename r t = subst (Var \o r) t) r :
rename (upren r) t = subst (up (Var \o r)) t.
Proof. by rewrite -(eq_subst _ _ _ (up_upren _)). Qed.
Lemma rename_subst_upn t
(_ : forall r, rename r t = subst (Var \o r) t) r n :
rename (upnren r n) t = subst (upn (Var \o r) n) t.
Proof. by rewrite -(eq_subst _ _ _ (upn_upnren _ _)). Qed.
Lemma subst_id_up t
(_ : subst Var t = t) :
subst (up Var) t = t.
Proof. by rewrite (eq_subst _ _ _ up_Var). Qed.
Lemma subst_id_upn t
(_ : subst Var t = t) n :
subst (upn Var n) t = t.
Proof. by rewrite (eq_subst _ _ _ (upn_Var _)). Qed.
Lemma subst_rename_comp_up t
(_ : forall r s, subst s (rename r t) = subst (s \o r) t) r s :
subst (up s) (rename (upren r) t) = subst (up (s \o r)) t.
Proof. by rewrite (eq_subst _ _ _ (up_upren_comp _ _)). Qed.
Lemma subst_rename_comp_upn t
(_ : forall r s, subst s (rename r t) = subst (s \o r) t) r s n :
subst (upn s n) (rename (upnren r n) t) = subst (upn (s \o r) n) t.
Proof. by rewrite (eq_subst _ _ _ (upn_upnren_comp _ _ _)). Qed.
Lemma rename_subst_comp_up t
(_ : forall r s, rename r (subst s t) = subst (rename r \o s) t) r s :
rename (upren r) (subst (up s) t) = subst (up (rename r \o s)) t.
Proof. by rewrite (eq_subst _ _ _ (upren_up_comp _ _)). Qed.
Lemma rename_subst_comp_upn t
(_ : forall r s, rename r (subst s t) = subst (rename r \o s) t) r s n :
rename (upnren r n) (subst (upn s n) t) = subst (upn (rename r \o s) n) t.
Proof. by rewrite (eq_subst _ _ _ (upnren_upn_comp _ _ _)). Qed.
Class SubstLemmas :=
{ subst_id t : subst Var t = t;
rename_subst t : forall r, rename r t = subst (Var \o r) t;
subst_rename_comp : forall t r s, subst s (rename r t) = subst (s \o r) t;
rename_subst_comp : forall t r s, rename r (subst s t) = subst (rename r \o s) t }.
Context {SubstLemmasTerm : SubstLemmas}.
Lemma up_up_comp s s' :
up (subst s \o s') =1 subst (up s) \o up s'.
Proof.
move => [ | ? ] /=.
- by rewrite subst_Var.
- rewrite rename_subst_comp subst_rename_comp.
exact: eq_subst.
Qed.
Lemma upn_upn_comp s s' n :
upn (subst s \o s') n =1 subst (upn s n) \o upn s' n.
Proof.
induction n => ? //=.
by rewrite (eq_up _ _ _ (fun _ => IHn _)) up_up_comp.
Qed.
Lemma subst_subst_comp_up t
(_ : forall s s', subst s (subst s' t) = subst (subst s \o s') t) s s' :
subst (up s) (subst (up s') t) = subst (up (subst s \o s')) t.
Proof. by rewrite (eq_subst _ _ _ (up_up_comp _ _)). Qed.
Lemma subst_subst_comp_upn t
(_ : forall s s', subst s (subst s' t) = subst (subst s \o s') t) s s' n :
subst (upn s n) (subst (upn s' n) t) = subst (upn (subst s \o s') n) t.
Proof. by rewrite (eq_subst _ _ _ (upn_upn_comp _ _ _)). Qed.
Class SubstLemmas' :=
{ subst_subst_comp : forall t s s', subst s (subst s' t) = subst (subst s \o s') t }.
End Subst.
Arguments Subst term {RenameTerm}.
Arguments SubstLemmas term {RenameTerm SubstTerm}.
Arguments SubstLemmas' term {RenameTerm SubstTerm}.
Definition scons {A} (a : A) s x :=
if x is x.+1 then s x else a.
Definition scat {A} l := (foldr (@scons A))^~l.
Lemma nth_scat {A} l s : forall x, @scat A l s x = nth (s (x - size l)) l x.
Proof.
induction l => [ ? | [ | ? ] ] //=.
- by rewrite subn0 nth_nil.
- by rewrite subSS.
Qed.
|
{"author": "aplas19-13", "repo": "cbn", "sha": "c284d3042433e444b24de25d8769397039bdafe3", "save_path": "github-repos/coq/aplas19-13-cbn", "path": "github-repos/coq/aplas19-13-cbn/cbn-c284d3042433e444b24de25d8769397039bdafe3/Util.v"}
|
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# Use this script for ground truth integrals of the vanilla BQ Gaussian process.
from typing import List, Tuple
import GPy
import numpy as np
from emukit.model_wrappers.gpy_quadrature_wrappers import BaseGaussianProcessGPy, RBFGPy
from emukit.quadrature.kernels.quadrature_rbf import QuadratureRBFLebesgueMeasure
from emukit.quadrature.methods import VanillaBayesianQuadrature
def _sample_uniform(num_samples: int, bounds: List[Tuple[float, float]]):
D = len(bounds)
samples = np.reshape(np.random.rand(num_samples * D), [num_samples, D])
samples_shifted = np.zeros(samples.shape)
for d in range(D):
samples_shifted[:, d] = samples[:, d] * (bounds[d][1] - bounds[d][0]) + bounds[d][0]
return samples_shifted
def integral_mean_uniform(num_samples: int, model: VanillaBayesianQuadrature):
bounds = model.integral_bounds.bounds
samples = _sample_uniform(num_samples, bounds)
gp_mean_at_samples, _ = model.predict(samples)
differences = np.array([x[1] - x[0] for x in bounds])
volume = np.prod(differences)
return np.mean(gp_mean_at_samples) * volume
def integral_var_uniform(num_samples: int, model: VanillaBayesianQuadrature):
bounds = model.integral_bounds.bounds
samples = _sample_uniform(num_samples, bounds)
_, gp_cov_at_samples = model.predict_with_full_covariance(samples)
differences = np.array([x[1] - x[0] for x in bounds])
volume = np.prod(differences)
return np.sum(gp_cov_at_samples) * (volume / num_samples) ** 2
if __name__ == "__main__":
np.random.seed(0)
METHOD = "Vanilla BQ"
X = np.array([[-1, 1], [0, 0], [-2, 0.1]])
Y = np.array([[1], [2], [3]])
D = X.shape[1]
integral_bounds = [(-1, 2), (-3, 3)]
gpy_model = GPy.models.GPRegression(X=X, Y=Y, kernel=GPy.kern.RBF(input_dim=D))
qrbf = QuadratureRBFLebesgueMeasure(RBFGPy(gpy_model.kern), integral_bounds=integral_bounds)
model = BaseGaussianProcessGPy(kern=qrbf, gpy_model=gpy_model)
vanilla_bq = VanillaBayesianQuadrature(base_gp=model, X=X, Y=Y)
print()
print("method: {}".format(METHOD))
print("no dimensions: {}".format(D))
print()
# === mean =============================================================
num_runs = 100
num_samples = 1e6
num_std = 3
mZ_SAMPLES = np.zeros(num_runs)
mZ, _ = vanilla_bq.integrate()
for i in range(num_runs):
num_samples = int(num_samples)
mZ_samples = integral_mean_uniform(num_samples, vanilla_bq)
mZ_SAMPLES[i] = mZ_samples
print("=== mean =======================================================")
print("no samples per integral: {:.1E}".format(num_samples))
print("number of integrals: {}".format(num_runs))
print("number of standard deviations: {}".format(num_std))
print([mZ_SAMPLES.mean() - num_std * mZ_SAMPLES.std(), mZ_SAMPLES.mean() + num_std * mZ_SAMPLES.std()])
print()
# === variance ==========================================================
num_runs = 100
num_samples = int(5 * 1e3)
num_std = 3
vZ_SAMPLES = np.zeros(num_runs)
_, vZ = vanilla_bq.integrate()
for i in range(num_runs):
vZ_samples = integral_var_uniform(num_samples, vanilla_bq)
vZ_SAMPLES[i] = vZ_samples
print("=== mean =======================================================")
print("no samples per integral: {:.1E}".format(num_samples))
print("number of integrals: {}".format(num_runs))
print("number of standard deviations: {}".format(num_std))
print([vZ_SAMPLES.mean() - num_std * vZ_SAMPLES.std(), vZ_SAMPLES.mean() + num_std * vZ_SAMPLES.std()])
print()
|
{"hexsha": "442286bd7391c7f5c32722a22e6594e6a6f97fb1", "size": 3759, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/emukit/quadrature/ground_truth_integrals_vanilla_bq.py", "max_stars_repo_name": "lfabris-mhpc/emukit", "max_stars_repo_head_hexsha": "ccb07f6bed0e9ae41dbeefdb3ad2ab247d3991e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/emukit/quadrature/ground_truth_integrals_vanilla_bq.py", "max_issues_repo_name": "lfabris-mhpc/emukit", "max_issues_repo_head_hexsha": "ccb07f6bed0e9ae41dbeefdb3ad2ab247d3991e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/emukit/quadrature/ground_truth_integrals_vanilla_bq.py", "max_forks_repo_name": "lfabris-mhpc/emukit", "max_forks_repo_head_hexsha": "ccb07f6bed0e9ae41dbeefdb3ad2ab247d3991e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1442307692, "max_line_length": 107, "alphanum_fraction": 0.6448523543, "include": true, "reason": "import numpy", "num_tokens": 981}
|
import numpy as np
import pyworld as pw
import soundfile as sf
import tensorflow as tf
from analyzer import SPEAKERS, pw2wav, read, read_whole_features
args = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string(
'train_file_pattern',
'./dataset/vcc2016/bin/Training Set/*/*.bin',
'training dir (to *.bin)')
def main():
tf.gfile.MkDir('./etc')
# ==== Save max and min value ====
x = read_whole_features(args.train_file_pattern)
x_all = list()
y_all = list()
f0_all = list()
sv = tf.train.Supervisor()
with sv.managed_session() as sess:
while True:
try:
features = sess.run(x)
print('Processing {}'.format(features['filename']))
x_all.append(features['sp'])
y_all.append(features['speaker'])
f0_all.append(features['f0'])
finally:
pass
x_all = np.concatenate(x_all, axis=0)
y_all = np.concatenate(y_all, axis=0)
f0_all = np.concatenate(f0_all, axis=0)
# ==== F0 stats ====
for s in SPEAKERS:
print('Speaker {}'.format(s), flush=True)
f0 = f0_all[SPEAKERS.index(s) == y_all]
print(' len: {}'.format(len(f0)))
f0 = f0[f0 > 2.]
f0 = np.log(f0)
mu, std = f0.mean(), f0.std()
# Save as `float32`
with open('./etc/{}.npf'.format(s), 'wb') as fp:
fp.write(np.asarray([mu, std]).tostring())
# ==== Min/Max value ====
# mu = x_all.mean(0)
# std = x_all.std(0)
q005 = np.percentile(x_all, 0.5, axis=0)
q995 = np.percentile(x_all, 99.5, axis=0)
# Save as `float32`
with open('./etc/xmin.npf', 'wb') as fp:
fp.write(q005.tostring())
with open('./etc/xmax.npf', 'wb') as fp:
fp.write(q995.tostring())
def test():
# ==== Test: batch mixer (conclusion: capacity should be larger to make sure good mixing) ====
x, y = read('./dataset/vcc2016/bin/*/*/1*001.bin', 32, min_after_dequeue=1024, capacity=2048)
sv = tf.train.Supervisor()
with sv.managed_session() as sess:
for _ in range(200):
x_, y_ = sess.run([x, y])
print(y_)
# ===== Read binary ====
features = read_whole_features('./dataset/vcc2016/bin/Training Set/SF1/*001.bin')
sv = tf.train.Supervisor()
with sv.managed_session() as sess:
features = sess.run(features)
y = pw2wav(features)
sf.write('test1.wav', y, 16000) # TODO fs should be specified externally.
# ==== Direct read =====
f = './dataset/vcc2016/bin/Training Set/SF1/100001.bin'
features = np.fromfile(f, np.float32)
features = np.reshape(features, [-1, 513*2 + 1 + 1 + 1]) # f0, en, spk
y = pw2wav(features)
sf.write('test2.wav', y, 16000)
if __name__ == '__main__':
main()
|
{"hexsha": "9d39a63b964a1b98ff6fd09258e6c0c557b48c16", "size": 2822, "ext": "py", "lang": "Python", "max_stars_repo_path": "build.py", "max_stars_repo_name": "entn-at/vae-npvc", "max_stars_repo_head_hexsha": "94a83b33bf17593aa402cb38408fdfad1339a120", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 146, "max_stars_repo_stars_event_min_datetime": "2017-06-07T09:47:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:04:57.000Z", "max_issues_repo_path": "build.py", "max_issues_repo_name": "entn-at/vae-npvc", "max_issues_repo_head_hexsha": "94a83b33bf17593aa402cb38408fdfad1339a120", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2017-11-17T12:18:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T12:55:03.000Z", "max_forks_repo_path": "build.py", "max_forks_repo_name": "entn-at/vae-npvc", "max_forks_repo_head_hexsha": "94a83b33bf17593aa402cb38408fdfad1339a120", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 43, "max_forks_repo_forks_event_min_datetime": "2017-08-24T12:25:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T21:31:01.000Z", "avg_line_length": 27.9405940594, "max_line_length": 98, "alphanum_fraction": 0.571934798, "include": true, "reason": "import numpy", "num_tokens": 806}
|
include("Density.jl")
function calc_design_matrix(umbrella_centers, data, sigma)
design_matrix = zeros(Float64, length(umbrella_centers) * length(data[1]), length(umbrella_centers))
for i = 1:length(umbrella_centers)
for j = 1:length(data[i])
for k = 1:length(umbrella_centers)
diff = get_gaussian(data[i][j], umbrella_centers[k], sigma) - get_gaussian(umbrella_centers[i], umbrella_centers[k], sigma)
design_matrix[j + length(data[i]) * (i - 1), k] = diff
end
end
end
return design_matrix
end
|
{"hexsha": "8c944efb8ccfa92a33061278aa68aafa4a38c6a0", "size": 587, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "notebook/DesignMatrix.jl", "max_stars_repo_name": "yutakasi634/MDToolbox.jl", "max_stars_repo_head_hexsha": "4a61ec671910d3fe25d86818a85e7929209d065d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebook/DesignMatrix.jl", "max_issues_repo_name": "yutakasi634/MDToolbox.jl", "max_issues_repo_head_hexsha": "4a61ec671910d3fe25d86818a85e7929209d065d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebook/DesignMatrix.jl", "max_forks_repo_name": "yutakasi634/MDToolbox.jl", "max_forks_repo_head_hexsha": "4a61ec671910d3fe25d86818a85e7929209d065d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1333333333, "max_line_length": 139, "alphanum_fraction": 0.6388415673, "num_tokens": 148}
|
# # Instrument Line Shapes
# Using packages:
using Plots
using Plots.PlotMeasures
# This needs to be installed from https://github.com/RadiativeTransfer/RadiativeTransfer.jl
using RadiativeTransfer.Absorption
using InstrumentOperator
# ## Load HITRAN data and CO2 cross sections
hitran_data = read_hitran(artifact("CO2"), mol=2, iso=1, ν_min=6000, ν_max=6400)
line_co2 = make_hitran_model(hitran_data, Voigt(), architecture=CPU())
# ## Compute a high resolution transmission spectrum
Δν = 0.0025
ν_min = 6320;
ν_max = 6355;
ν = ν_min:Δν:ν_max;
# CO₂ cross section at 800hPa and 296K:
σ_co2 = absorption_cross_section(line_co2, ν, 800.0, 296.0);
# Transmission through a typical atmosphere (8e21 molec/cm²)
T = exp.(-8e21*σ_co2);
# plot high resolution transmission
plot(ν, T, lw=2, label="High resolution", top_margin = 10mm, bottom_margin = 10mm, left_margin = 5mm, right_margin = 5mm)
# Define the instrument kernel grid
x = -8:Δν:8;
# ## Create a kernel at a center wavenumber of 6300cm⁻¹
# Use FTS with 5cm MOPD, FOV of 7.9mrad, no assymetry:
FTS = FTSInstrument(5.0, 7.9e-3, 0.0)
FTSkernel = create_instrument_kernel(FTS, x,6300.0)
margin = 5.0
sampling = 0.01
FTS_instr = FixedKernelInstrument(FTSkernel, collect(ν_min+margin:sampling:ν_max-margin))
# ## Convolve with instrument kernel
T_conv = conv_spectra(FTS_instr, ν, T);
# overplot convolved transmission:
plot!(FTS_instr.ν_out, T_conv, label="Convolved")
|
{"hexsha": "020620a675d4eca2c09be1705b10fd62cbaff603", "size": 1428, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "docs/src/pages/tutorials/CrossSection_convolution.jl", "max_stars_repo_name": "RemoteSensingTools/InstrumentOperator.jl", "max_stars_repo_head_hexsha": "9ed373f7707f1bf93800956c1359b4425190202b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-24T18:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T18:50:50.000Z", "max_issues_repo_path": "docs/src/pages/tutorials/CrossSection_convolution.jl", "max_issues_repo_name": "RemoteSensingTools/InstrumentOperator.jl", "max_issues_repo_head_hexsha": "9ed373f7707f1bf93800956c1359b4425190202b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-09-27T22:04:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:34:43.000Z", "max_forks_repo_path": "docs/src/pages/tutorials/CrossSection_convolution.jl", "max_forks_repo_name": "RemoteSensingTools/InstrumentOperator.jl", "max_forks_repo_head_hexsha": "9ed373f7707f1bf93800956c1359b4425190202b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-23T23:21:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T23:21:41.000Z", "avg_line_length": 34.8292682927, "max_line_length": 122, "alphanum_fraction": 0.7556022409, "num_tokens": 476}
|
import copy
import json
import os
import uuid
from inspect import signature
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from retrying import retry
import dask
import dask.dataframe as dd
from dask import delayed
from dask.dataframe.core import get_parallel_type
from dask.dataframe.partitionquantiles import partition_quantiles
from dask.dataframe.extensions import make_array_nonempty
try:
from dask.dataframe.dispatch import make_meta_dispatch
from dask.dataframe.backends import meta_nonempty
except ImportError:
from dask.dataframe.utils import make_meta as make_meta_dispatch, meta_nonempty
from .geodataframe import GeoDataFrame
from .geometry.base import GeometryDtype, _BaseCoordinateIndexer
from .geoseries import GeoSeries
from .spatialindex import HilbertRtree
class DaskGeoSeries(dd.Series):
def __init__(self, dsk, name, meta, divisions, *args, **kwargs):
super().__init__(dsk, name, meta, divisions)
# Init backing properties
self._partition_bounds = None
self._partition_sindex = None
@property
def bounds(self):
return self.map_partitions(lambda s: s.bounds)
@property
def total_bounds(self):
partition_bounds = self.partition_bounds
return (
np.nanmin(partition_bounds['x0']),
np.nanmin(partition_bounds['y0']),
np.nanmax(partition_bounds['x1']),
np.nanmax(partition_bounds['y1']),
)
@property
def partition_bounds(self):
if self._partition_bounds is None:
self._partition_bounds = self.map_partitions(
lambda s: pd.DataFrame(
[s.total_bounds], columns=['x0', 'y0', 'x1', 'y1']
)
).compute().reset_index(drop=True)
self._partition_bounds.index.name = 'partition'
return self._partition_bounds
@property
def area(self):
return self.map_partitions(lambda s: s.area)
@property
def length(self):
return self.map_partitions(lambda s: s.length)
@property
def partition_sindex(self):
if self._partition_sindex is None:
self._partition_sindex = HilbertRtree(self.partition_bounds.values)
return self._partition_sindex
@property
def cx(self):
return _DaskCoordinateIndexer(self, self.partition_sindex)
@property
def cx_partitions(self):
return _DaskPartitionCoordinateIndexer(self, self.partition_sindex)
def build_sindex(self, **kwargs):
def build_sindex(series, **kwargs):
series.build_sindex(**kwargs)
return series
return self.map_partitions(build_sindex, **kwargs, meta=self._meta)
def intersects_bounds(self, bounds):
return self.map_partitions(lambda s: s.intersects_bounds(bounds))
# Override some standard Dask Series methods to propagate extra properties
def _propagate_props_to_series(self, new_series):
new_series._partition_bounds = self._partition_bounds
new_series._partition_sindex = self._partition_sindex
return new_series
def persist(self, **kwargs):
return self._propagate_props_to_series(
super().persist(**kwargs)
)
@make_meta_dispatch.register(GeoSeries)
def make_meta_series(s, index=None):
result = s.head(0)
if index is not None:
result = result.reindex(index[:0])
return result
@meta_nonempty.register(GeoSeries)
def meta_nonempty_series(s, index=None):
return GeoSeries(make_array_nonempty(s.dtype), index=index)
@get_parallel_type.register(GeoSeries)
def get_parallel_type_dataframe(df):
return DaskGeoSeries
class DaskGeoDataFrame(dd.DataFrame):
def __init__(self, dsk, name, meta, divisions):
super().__init__(dsk, name, meta, divisions)
self._partition_sindex = {}
self._partition_bounds = {}
def to_parquet(self, fname, compression="snappy", filesystem=None, **kwargs):
from .io import to_parquet_dask
to_parquet_dask(
self, fname, compression=compression, filesystem=filesystem, **kwargs
)
@property
def geometry(self):
# Use self._meta.geometry.name rather than self._meta._geometry so that an
# informative error message is raised if there is no valid geometry column
return self[self._meta.geometry.name]
def set_geometry(self, geometry):
if geometry != self._meta._geometry:
return self.map_partitions(lambda df: df.set_geometry(geometry))
else:
return self
@property
def partition_sindex(self):
geometry_name = self._meta.geometry.name
if geometry_name not in self._partition_sindex:
# Apply partition_bounds to geometry Series before creating the spatial
# index. This removes the need to scan partitions to compute bounds
geometry = self.geometry
if geometry_name in self._partition_bounds:
geometry._partition_bounds = self._partition_bounds[geometry_name]
self._partition_sindex[geometry.name] = geometry.partition_sindex
self._partition_bounds[geometry_name] = geometry.partition_bounds
return self._partition_sindex[geometry_name]
@property
def cx(self):
return _DaskCoordinateIndexer(self, self.partition_sindex)
@property
def cx_partitions(self):
return _DaskPartitionCoordinateIndexer(self, self.partition_sindex)
def pack_partitions(self, npartitions=None, p=15, shuffle='tasks'):
"""
Repartition and reorder dataframe spatially along a Hilbert space filling curve
Args:
npartitions: Number of output partitions. Defaults to the larger of 8 and
the length of the dataframe divided by 2**23.
p: Hilbert curve p parameter
shuffle: Dask shuffle method, either "disk" or "tasks"
Returns:
Spatially partitioned DaskGeoDataFrame
"""
# Compute number of output partitions
npartitions = self._compute_packing_npartitions(npartitions)
# Add hilbert_distance column
ddf = self._with_hilbert_distance_column(p)
# Set index to distance. This will trigger an expensive shuffle
# sort operation
ddf = ddf.set_index('hilbert_distance', npartitions=npartitions, shuffle=shuffle)
if ddf.npartitions != npartitions:
# set_index doesn't change the number of partitions if the partitions
# happen to be already sorted
ddf = ddf.repartition(npartitions=npartitions)
return ddf
def pack_partitions_to_parquet(
self,
path,
filesystem=None,
npartitions=None,
p=15,
compression="snappy",
tempdir_format=None,
_retry_args=None,
storage_options=None,
engine_kwargs=None,
overwrite=False,
):
"""
Repartition and reorder dataframe spatially along a Hilbert space filling curve
and write to parquet dataset at the provided path.
This is equivalent to ddf.pack_partitions(...).to_parquet(...) but with lower
memory and disk usage requirements.
Args:
path: Output parquet dataset path
filesystem: Optional fsspec filesystem. If not provided, filesystem type
is inferred from path
npartitions: Number of output partitions. Defaults to the larger of 8 and
the length of the dataframe divided by 2**23.
p: Hilbert curve p parameter
compression: Compression algorithm for parquet file
tempdir_format: format string used to generate the filesystem path where
temporary files should be stored for each output partition. String
must contain a '{partition}' replacement field which will be formatted
using the output partition number as an integer. The string may
optionally contain a '{uuid}' replacement field which will be formatted
using a randomly generated UUID string. If None (the default),
temporary files are stored inside the output path.
These directories are deleted as soon as possible during the execution
of the function.
storage_options: Key/value pairs to be passed on to the file-system backend, if any.
engine_kwargs: pyarrow.parquet engine-related keyword arguments.
Returns:
DaskGeoDataFrame backed by newly written parquet dataset
"""
from .io import read_parquet, read_parquet_dask
from .io.utils import validate_coerce_filesystem
engine_kwargs = engine_kwargs or {}
# Get fsspec filesystem object
filesystem = validate_coerce_filesystem(path, filesystem, storage_options)
# Decorator for operations that should be retried
if _retry_args is None:
_retry_args = dict(
wait_exponential_multiplier=100,
wait_exponential_max=120000,
stop_max_attempt_number=24,
)
retryit = retry(**_retry_args)
@retryit
def rm_retry(file_path):
filesystem.invalidate_cache()
if filesystem.exists(file_path):
filesystem.rm(file_path, recursive=True)
if filesystem.exists(file_path):
# Make sure we keep retrying until file does not exist
raise ValueError("Deletion of {path} not yet complete".format(
path=file_path
))
@retryit
def mkdirs_retry(dir_path):
filesystem.makedirs(dir_path, exist_ok=True)
# For filesystems that provide a "refresh" argument, set it to True
if 'refresh' in signature(filesystem.ls).parameters:
ls_kwargs = {'refresh': True}
else:
ls_kwargs = {}
@retryit
def ls_retry(dir_path):
filesystem.invalidate_cache()
return filesystem.ls(dir_path, **ls_kwargs)
@retryit
def move_retry(p1, p2):
if filesystem.exists(p1):
filesystem.move(p1, p2)
# Compute tempdir_format string
dataset_uuid = str(uuid.uuid4())
if tempdir_format is None:
tempdir_format = os.path.join(path, "part.{partition}.parquet")
elif not isinstance(tempdir_format, str) or "{partition" not in tempdir_format:
raise ValueError(
"tempdir_format must be a string containing a {{partition}} "
"replacement field\n"
" Received: {tempdir_format}".format(
tempdir_format=repr(tempdir_format)
)
)
# Compute number of output partitions
npartitions = self._compute_packing_npartitions(npartitions)
out_partitions = list(range(npartitions))
# Add hilbert_distance column
ddf = self._with_hilbert_distance_column(p)
# Compute output hilbert_distance divisions
quantiles = partition_quantiles(
ddf.hilbert_distance, npartitions
).compute().values
# Add _partition column containing output partition number of each row
ddf = ddf.map_partitions(
lambda df: df.assign(
_partition=np.digitize(df.hilbert_distance, quantiles[1:], right=True))
)
# Compute part paths
parts_tmp_paths = [
tempdir_format.format(partition=out_partition, uuid=dataset_uuid)
for out_partition in out_partitions
]
part_output_paths = [
os.path.join(path, "part.%d.parquet" % out_partition)
for out_partition in out_partitions
]
# Initialize output partition directory structure
filesystem.invalidate_cache()
if overwrite:
rm_retry(path)
for out_partition in out_partitions:
part_dir = os.path.join(path, "part.%d.parquet" % out_partition)
mkdirs_retry(part_dir)
tmp_part_dir = tempdir_format.format(partition=out_partition, uuid=dataset_uuid)
mkdirs_retry(tmp_part_dir)
# Shuffle and write a parquet dataset for each output partition
@retryit
def write_partition(df_part, part_path):
with filesystem.open(part_path, "wb") as f:
df_part.to_parquet(
f,
compression=compression,
index=True,
**engine_kwargs,
)
def process_partition(df, i):
subpart_paths = {}
for out_partition, df_part in df.groupby('_partition'):
part_path = os.path.join(
tempdir_format.format(partition=out_partition, uuid=dataset_uuid),
'part.%d.parquet' % i,
)
df_part = (
df_part
.drop('_partition', axis=1)
.set_index('hilbert_distance', drop=True)
)
write_partition(df_part, part_path)
subpart_paths[out_partition] = part_path
return subpart_paths
part_path_infos = dask.compute(*[
dask.delayed(process_partition, pure=False)(df, i)
for i, df in enumerate(ddf.to_delayed())
])
# Build dict from part number to list of subpart paths
part_num_to_subparts = {}
for part_path_info in part_path_infos:
for part_num, subpath in part_path_info.items():
subpaths = part_num_to_subparts.get(part_num, [])
subpaths.append(subpath)
part_num_to_subparts[part_num] = subpaths
# Concat parquet dataset per partition into parquet file per partition
@retryit
def write_concatted_part(part_df, part_output_path, md_list):
with filesystem.open(part_output_path, 'wb') as f:
pq.write_table(
pa.Table.from_pandas(part_df),
f, compression=compression, metadata_collector=md_list
)
@retryit
def read_parquet_retry(parts_tmp_path, subpart_paths, part_output_path):
if filesystem.isfile(part_output_path) and not filesystem.isdir(parts_tmp_path):
# Handle rare case where the task was resubmitted and the work has
# already been done. This shouldn't happen with pure=False, but it
# seems like it does very rarely.
return read_parquet(
part_output_path,
filesystem=filesystem,
storage_options=storage_options,
**engine_kwargs,
)
ls_res = sorted(filesystem.ls(parts_tmp_path, **ls_kwargs))
subpart_paths_stripped = sorted([filesystem._strip_protocol(_) for _ in subpart_paths])
if subpart_paths_stripped != ls_res:
missing = set(subpart_paths) - set(ls_res)
extras = set(ls_res) - set(subpart_paths)
raise ValueError(
"Filesystem not yet consistent\n"
" Expected len: {expected}\n"
" Found len: {received}\n"
" Missing: {missing}\n"
" Extras: {extras}".format(
expected=len(subpart_paths),
received=len(ls_res),
missing=list(missing),
extras=list(extras)
)
)
return read_parquet(
parts_tmp_path,
filesystem=filesystem,
storage_options=storage_options,
**engine_kwargs,
)
def concat_parts(parts_tmp_path, subpart_paths, part_output_path):
filesystem.invalidate_cache()
# Load directory of parquet parts for this partition into a
# single GeoDataFrame
if not subpart_paths:
# Empty partition
rm_retry(parts_tmp_path)
return None
else:
part_df = read_parquet_retry(parts_tmp_path, subpart_paths, part_output_path)
# Compute total_bounds for all geometry columns in part_df
total_bounds = {}
for series_name in part_df.columns:
series = part_df[series_name]
if isinstance(series.dtype, GeometryDtype):
total_bounds[series_name] = series.total_bounds
# Delete directory of parquet parts for partition
rm_retry(parts_tmp_path)
rm_retry(part_output_path)
# Sort by part_df by hilbert_distance index
part_df.sort_index(inplace=True)
# Write part_df as a single parquet file, collecting metadata for later use
# constructing the full dataset _metadata file.
md_list = []
filesystem.invalidate_cache()
write_concatted_part(part_df, part_output_path, md_list)
# Return metadata and total_bounds for part
return {"meta": md_list[0], "total_bounds": total_bounds}
write_info = dask.compute(*[
dask.delayed(concat_parts, pure=False)(
parts_tmp_paths[out_partition],
part_num_to_subparts.get(out_partition, []),
part_output_paths[out_partition]
)
for out_partition in out_partitions
])
# Handle empty partitions.
input_paths, write_info = zip(*[
(pp, wi) for (pp, wi) in zip(part_output_paths, write_info) if wi is not None
])
output_paths = part_output_paths[:len(input_paths)]
for p1, p2 in zip(input_paths, output_paths):
if p1 != p2:
move_retry(p1, p2)
# Write _metadata
meta = write_info[0]['meta']
for i in range(1, len(write_info)):
meta.append_row_groups(write_info[i]["meta"])
@retryit
def write_metadata_file():
with filesystem.open(os.path.join(path, "_metadata"), 'wb') as f:
meta.write_metadata_file(f)
write_metadata_file()
# Collect total_bounds per partition for all geometry columns
all_bounds = {}
for info in write_info:
for col, bounds in info.get('total_bounds', {}).items():
bounds_list = all_bounds.get(col, [])
bounds_list.append(
pd.Series(bounds, index=['x0', 'y0', 'x1', 'y1'])
)
all_bounds[col] = bounds_list
# Build spatial metadata for parquet dataset
partition_bounds = {}
for col, bounds in all_bounds.items():
partition_bounds[col] = pd.DataFrame(all_bounds[col]).to_dict()
spatial_metadata = {'partition_bounds': partition_bounds}
b_spatial_metadata = json.dumps(spatial_metadata).encode('utf')
# Write _common_metadata
@retryit
def write_commonmetadata_file():
with filesystem.open(os.path.join(path, "part.0.parquet")) as f:
pf = pq.ParquetFile(f)
all_metadata = copy.copy(pf.metadata.metadata)
all_metadata[b'spatialpandas'] = b_spatial_metadata
new_schema = pf.schema.to_arrow_schema().with_metadata(all_metadata)
with filesystem.open(os.path.join(path, "_common_metadata"), 'wb') as f:
pq.write_metadata(new_schema, f)
write_commonmetadata_file()
return read_parquet_dask(
path,
filesystem=filesystem,
storage_options=storage_options,
engine_kwargs=engine_kwargs,
)
def _compute_packing_npartitions(self, npartitions):
if npartitions is None:
# Make partitions of ~8 million rows with a minimum of 8
# partitions
nrows = len(self)
npartitions = max(nrows // 2 ** 23, 8)
return npartitions
def _with_hilbert_distance_column(self, p):
# Get geometry column
geometry = self.geometry
# Compute distance of points along the Hilbert-curve
total_bounds = geometry.total_bounds
ddf = self.assign(hilbert_distance=geometry.map_partitions(
lambda s: s.hilbert_distance(total_bounds=total_bounds, p=p))
)
return ddf
# Override some standard Dask Dataframe methods to propagate extra properties
def _propagate_props_to_dataframe(self, new_frame):
new_frame._partition_sindex = self._partition_sindex
new_frame._partition_bounds = self._partition_bounds
return new_frame
def _propagate_props_to_series(self, new_series):
if new_series.name in self._partition_bounds:
new_series._partition_bounds = self._partition_bounds[new_series.name]
if new_series.name in self._partition_sindex:
new_series._partition_sindex = self._partition_sindex[new_series.name]
return new_series
def build_sindex(self, **kwargs):
def build_sindex(df, **kwargs):
df.build_sindex(**kwargs)
return df
return self.map_partitions(build_sindex, **kwargs, meta=self._meta)
def persist(self, **kwargs):
return self._propagate_props_to_dataframe(
super().persist(**kwargs)
)
def __getitem__(self, key):
result = super().__getitem__(key)
if np.isscalar(key) or isinstance(key, (tuple, str)):
# New series of single column, partition props apply if we have them
self._propagate_props_to_series(result)
elif isinstance(key, (np.ndarray, list)):
# New dataframe with same length and same partitions as self so partition
# properties still apply
self._propagate_props_to_dataframe(result)
return result
@make_meta_dispatch.register(GeoDataFrame)
def make_meta_dataframe(df, index=None):
result = df.head(0)
if index is not None:
result = result.reindex(index[:0])
return result
@meta_nonempty.register(GeoDataFrame)
def meta_nonempty_dataframe(df, index=None):
return GeoDataFrame(meta_nonempty(pd.DataFrame(df.head(0))))
@get_parallel_type.register(GeoDataFrame)
def get_parallel_type_series(s):
return DaskGeoDataFrame
class _DaskCoordinateIndexer(_BaseCoordinateIndexer):
def __init__(self, obj, sindex):
super().__init__(sindex)
self._obj = obj
def _perform_get_item(self, covers_inds, overlaps_inds, x0, x1, y0, y1):
covers_inds = set(covers_inds)
overlaps_inds = set(overlaps_inds)
all_partition_inds = sorted(covers_inds.union(overlaps_inds))
if len(all_partition_inds) == 0:
# No partitions intersect with query region, return empty result
return dd.from_pandas(self._obj._meta, npartitions=1)
@delayed
def cx_fn(df):
return df.cx[x0:x1, y0:y1]
ddf = self._obj.partitions[all_partition_inds]
delayed_dfs = []
for partition_ind, delayed_df in zip(all_partition_inds, ddf.to_delayed()):
if partition_ind in overlaps_inds:
delayed_dfs.append(
cx_fn(delayed_df)
)
else:
delayed_dfs.append(delayed_df)
return dd.from_delayed(delayed_dfs, meta=ddf._meta, divisions=ddf.divisions)
class _DaskPartitionCoordinateIndexer(_BaseCoordinateIndexer):
def __init__(self, obj, sindex):
super().__init__(sindex)
self._obj = obj
def _perform_get_item(self, covers_inds, overlaps_inds, x0, x1, y0, y1):
covers_inds = set(covers_inds)
overlaps_inds = set(overlaps_inds)
all_partition_inds = sorted(covers_inds.union(overlaps_inds))
if len(all_partition_inds) == 0:
# No partitions intersect with query region, return empty result
return dd.from_pandas(self._obj._meta, npartitions=1)
return self._obj.partitions[all_partition_inds]
|
{"hexsha": "53d50a0a3fe107c862e66a5d02497ebb88899f8f", "size": 24478, "ext": "py", "lang": "Python", "max_stars_repo_path": "spatialpandas/dask.py", "max_stars_repo_name": "ianthomas23/spatialpandas", "max_stars_repo_head_hexsha": "b6809e79f615e0be6fda6845b9725b5f87529c56", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207, "max_stars_repo_stars_event_min_datetime": "2019-11-29T04:50:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:31:55.000Z", "max_issues_repo_path": "spatialpandas/dask.py", "max_issues_repo_name": "ianthomas23/spatialpandas", "max_issues_repo_head_hexsha": "b6809e79f615e0be6fda6845b9725b5f87529c56", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 55, "max_issues_repo_issues_event_min_datetime": "2019-12-02T13:33:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T18:16:06.000Z", "max_forks_repo_path": "spatialpandas/dask.py", "max_forks_repo_name": "ianthomas23/spatialpandas", "max_forks_repo_head_hexsha": "b6809e79f615e0be6fda6845b9725b5f87529c56", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-11-29T16:07:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:54:20.000Z", "avg_line_length": 37.4854517611, "max_line_length": 99, "alphanum_fraction": 0.6284418662, "include": true, "reason": "import numpy", "num_tokens": 5075}
|
import time
import sqlite3
import pandas as pd
import numpy as np
import scipy as sp
from scipy import stats
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
'''
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import (RandomTreesEmbedding, RandomForestClassifier, GradientBoostingClassifier)
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve
from sklearn.pipeline import make_pipeline
'''
traindataframes = []
testDataFrame = []
max = 20
#def predict_next_day():
#return 0
def denormalize_features(features):
frames = []
for i,r in enumerate(traindataframes):
denormalized_features = []
price_col = r['Current_price']
price_col = price_col[0:max]
change_col = r['Today_price']
change_col = change_col[0:max]
#parse data and remove + sign
for j in change_col:
if '+' in j:
t = j.replace('+','')
change_col = change_col.replace(str(j),t)
for j in change_col:
change_col = change_col.replace(str(j),float(j))
for j,element in enumerate(price_col):
initial_price = element - change_col[j]
#closing_price = element
#normalized = ((closing_price/initial_price)-1)
closing_price = (features[i][j] + 1) * initial_price
denormalized_features.append(closing_price)
frames.append(denormalized_features)
features = pd.DataFrame(frames).transpose()
return features
def gradient_descent():
global traindataframes
global testDataFrame
prediction_frame = testDataFrame[0]
prediction_frame = prediction_frame['Current_price']
prediction_frame = prediction_frame[0:max]
#this takes the closing price and the initial price Current_price = initial today price is the change is price
#that day. So we take closing minus today change to get initial
#we then normalize this data
frames = []
for i in traindataframes:
normalized_features = []
price_col = i['Current_price']
price_col = price_col[0:max]
change_col = i['Today_price']
change_col = change_col[0:max]
#parse data and remove + sign
for j in change_col:
if '+' in j:
t = j.replace('+','')
change_col = change_col.replace(str(j),t)
for j in change_col:
change_col = change_col.replace(str(j),float(j))
#part that gets the initial and closing
for j,element in enumerate(price_col):
initial_price = element - change_col[j]
closing_price = element
normalized = ((closing_price/initial_price)-1)
normalized_features.append(normalized)
frames.append(normalized_features)
#get features
features = pd.DataFrame(frames).transpose()
features_array = np.array(features)
#same as above we ar normalizing the values
frames = []
normalized_features = []
prediction_frame_change = testDataFrame[0]
prediction_frame_change = prediction_frame_change['Today_price']
prediction_frame_change = prediction_frame_change[0:max]
#parse data and remove + sign
for i in prediction_frame_change:
if '+' in i:
t = i.replace('+','')
prediction_frame_change = prediction_frame_change.replace(str(i),t)
for i in prediction_frame_change:
prediction_frame_change = prediction_frame_change.replace(str(i),float(i))
#part that gets the initial and closing
for i,element in enumerate(prediction_frame):
initial_price = element - prediction_frame_change[i]
closing_price = element
normalized = ((closing_price/initial_price)-1)
'''
print('closing_price: ' + str(closing_price))
#print('todays_change: ' + str())
print('normalized_price: ' + str(normalized))
denormalized = (normalized + 1) * initial_price
print('denormalized_price: ' + str(denormalized))
'''
normalized_features.append(normalized)
for i in normalized_features:
frames.append(i)
#get values
values_array = np.array(frames)
m = len(values_array)
alpha = 0.01
num_iterations = 2000000
theta_descent = np.zeros(len(features.columns))
cost_history = []
#actual gradient descent part
for i in range(num_iterations):
predicted_value = np.dot(features_array, theta_descent)
theta_descent = theta_descent + alpha/m * np.dot(values_array - predicted_value, features_array)
sum_of_square_errors = np.square(np.dot(features_array, theta_descent) - values_array).sum()
cost = sum_of_square_errors / (2 * m)
cost_history.append(cost)
#this causes lag
if(i % 1000 == 0):
print('Epoch: ' + str(i/1000) + ' : ' + 'Cost: ' + str(cost_history[i]))
#all output and debugging
cost_history = pd.Series(cost_history)
predictions = np.dot(features_array, theta_descent).transpose()
print('============================================')
print('Cost History: ', cost_history)
print('Theta Descent: ',theta_descent)
print('Alpha: ', alpha)
print('Iterations: ',num_iterations)
data_predictions = np.sum((values_array - predictions)**2)
mean = np.mean(values_array)
sq_mean = np.sum((values_array - mean)**2)
if(sq_mean == 0):
sq_mean = sq_mean + 0.0000001
r = 1 - data_predictions / sq_mean
print('R: ', r)
#denormalize data
features = denormalize_features(features)
#features = np.array(features)
#features = features[0]
predictions = np.dot(features, theta_descent)
print('Predictions: ',predictions)
print('============================================')
day_before = features.transpose()
day_before = day_before[-1:]
day_before = day_before.transpose()
fig, ax = plt.subplots()
ax.plot(prediction_frame,'o',markersize = 1, color = 'green', label = 'Actual Price')
ax.plot(predictions,'o',markersize = 1, color = 'blue', label = 'Predicted Price')
ax.plot(day_before,'o',markersize = 1, color = 'red', label = 'Price Previously')
plt.legend()
fig2, ax2 = plt.subplots()
ax2.plot(cost_history,'o',markersize = 1, color = 'blue')
plt.show()
def get_Data():
global traindataframes
global testDataFrame
tables = []
con = sqlite3.connect("GE_Data.db")
cur = con.cursor()
table = cur.execute("select name from sqlite_master where type = 'table'")
for i in table.fetchall():
tables.append(i[0])
for i in tables[:-1]:
# print('DFs: ' + str(i))
q = "select * from " + i + " ORDER BY Id"
traindataframes.append(pd.read_sql(q,con))
for i in tables[-1:]:
# print('TestDF: ' + str(i))
q = "select * from " + i + " ORDER BY Id"
testDataFrame.append(pd.read_sql(q,con))
cur.close()
con.close()
get_Data()
gradient_descent()
#predict()
|
{"hexsha": "ed071631d9c43c142778bbfe7b489b56b4e65225", "size": 6636, "ext": "py", "lang": "Python", "max_stars_repo_path": "predictionTesting/predict2.py", "max_stars_repo_name": "Silenc3IsGold3n/RS3GEPredictionModel", "max_stars_repo_head_hexsha": "d7b5e7bd701dd35912b22e0bc315441289ff9861", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predictionTesting/predict2.py", "max_issues_repo_name": "Silenc3IsGold3n/RS3GEPredictionModel", "max_issues_repo_head_hexsha": "d7b5e7bd701dd35912b22e0bc315441289ff9861", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predictionTesting/predict2.py", "max_forks_repo_name": "Silenc3IsGold3n/RS3GEPredictionModel", "max_forks_repo_head_hexsha": "d7b5e7bd701dd35912b22e0bc315441289ff9861", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-29T17:35:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-29T17:35:35.000Z", "avg_line_length": 31.7511961722, "max_line_length": 112, "alphanum_fraction": 0.6957504521, "include": true, "reason": "import numpy,import scipy,from scipy", "num_tokens": 1665}
|
module TestClockResolution
import Benchmarks
using Base.Test
using Compat
res = Benchmarks.estimate_clock_resolution(1)
@test isa(res, UInt)
@test 1 <= res <= 10_000
res_2 = Benchmarks.estimate_clock_resolution()
@test res_2 <= res
end
|
{"hexsha": "e25cba14a22aeba2a0f007c2a1a788615811faee", "size": 272, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/01_clock_resolution.jl", "max_stars_repo_name": "johnmyleswhite/Benchmarks.jl", "max_stars_repo_head_hexsha": "0cb8340ce5af3e175c86154cd6202843a4960adf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56, "max_stars_repo_stars_event_min_datetime": "2015-06-16T06:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-31T01:37:44.000Z", "max_issues_repo_path": "test/01_clock_resolution.jl", "max_issues_repo_name": "johnmyleswhite/Benchmarks.jl", "max_issues_repo_head_hexsha": "0cb8340ce5af3e175c86154cd6202843a4960adf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43, "max_issues_repo_issues_event_min_datetime": "2015-06-16T18:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T13:12:16.000Z", "max_forks_repo_path": "test/01_clock_resolution.jl", "max_forks_repo_name": "johnmyleswhite/Benchmarks.jl", "max_forks_repo_head_hexsha": "0cb8340ce5af3e175c86154cd6202843a4960adf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2015-06-21T02:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T17:22:23.000Z", "avg_line_length": 18.1333333333, "max_line_length": 50, "alphanum_fraction": 0.6875, "num_tokens": 76}
|
Elliot is an Undergraduate Students undergraduate at UC Davis. He is majors majoring in Chemical Engineering and Materials Science Materials Science & Engineering.
Please send lucrative job opportunities & fan mail to MailTo(egszkup AT gmail DOT com)
Elliot is like TNT...he knows Drama!
Elliot is my special friend Users/JessicaElb Jessica
20070516 18:16:56 nbsp Good looking out on the cleanup of that mystery photo, the name was failing me at the time, but I knew it was that new complex. Users/StevenDaubert
20080725 23:30:45 nbsp Can you link the Yoav Helfman page that you created from somewhere? It would also be great if you could flesh it out a little bit as it doesnt have much to it other than the photo at the moment. Users/JasonAller
|
{"hexsha": "4a0587023465e8f9f55c14b79ff869cd9b54fd99", "size": 757, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "lab/davisWiki/ElliotSzkup.f", "max_stars_repo_name": "voflo/Search", "max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab/davisWiki/ElliotSzkup.f", "max_issues_repo_name": "voflo/Search", "max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab/davisWiki/ElliotSzkup.f", "max_forks_repo_name": "voflo/Search", "max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4666666667, "max_line_length": 234, "alphanum_fraction": 0.7939233818, "num_tokens": 185}
|
import numpy as np
import ttarray as tt
from ... import check_dense,random_array
from ... import DENSE_SHAPE
import pytest
SLICE_PROTOTYPE=tt.ones_slice((2,2,3),int,((2,),),2)
import functools
def _product(seq):
return functools.reduce(lambda x,y:x*y, seq,1)
def _calc_chi(cluster,lefti=1,righti=1):
left,right=[lefti],[righti]
for c in cluster:
left.append(left[-1]*_product(c))
for c in cluster[::-1]:
right.append(right[-1]*_product(c))
return tuple(min(l,r) for l,r in zip(left[1:-1],right[1:-1][::-1]))
def test_ttarray_frombuffer(seed_rng):
for shape,cls in DENSE_SHAPE.items():
if len(shape)!=1:
continue
cluster=cls[0]
chi=_calc_chi(cluster)
npar=random_array(shape,dtype=np.float32)
buf=npar.tobytes()
ar=tt.frombuffer(buf,dtype=np.float32)
ar2=np.frombuffer(buf,dtype=np.float32,like=ar)
check_dense(ar,npar,cluster,chi,tt.TensorTrainArray)
check_dense(ar2,npar,cluster,chi,tt.TensorTrainArray)
for cluster in cls:
chi=_calc_chi(cluster)
ar=tt.frombuffer(buf,dtype=np.float32,cluster=cluster)
check_dense(ar,npar,cluster,chi,tt.TensorTrainArray)
def test_ttarray_fromiter(seed_rng):
for shape,cls in DENSE_SHAPE.items():
if len(shape)!=1:
continue
cluster=cls[0]
chi=_calc_chi(cluster)
npar=random_array(shape,dtype=np.int32)
ar=tt.fromiter(iter(npar),dtype=np.int32)
ar2=np.fromiter(iter(npar),dtype=np.int32,like=ar)
check_dense(ar,npar,cluster,chi,tt.TensorTrainArray)
check_dense(ar2,npar,cluster,chi,tt.TensorTrainArray)
for cluster in cls:
chi=_calc_chi(cluster)
ar=tt.fromiter(iter(npar),dtype=np.int32,cluster=cluster)
check_dense(ar,npar,cluster,chi,tt.TensorTrainArray)
def test_ttslice_frombuffer():
with pytest.raises(TypeError):
np.frombuffer(None,like=SLICE_PROTOTYPE)
def test_ttslice_fromiter():
with pytest.raises(TypeError):
np.fromiter([1,2,3,4],dtype=int,like=SLICE_PROTOTYPE)
|
{"hexsha": "1ec7b50d5ac247d9aed5f39c4af27458fb589958", "size": 2126, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/core/creation/test_array_r1.py", "max_stars_repo_name": "sonnerm/ttarray", "max_stars_repo_head_hexsha": "c962cb2be303dfdb6743aa802bd11b89043e7b71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/core/creation/test_array_r1.py", "max_issues_repo_name": "sonnerm/ttarray", "max_issues_repo_head_hexsha": "c962cb2be303dfdb6743aa802bd11b89043e7b71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/core/creation/test_array_r1.py", "max_forks_repo_name": "sonnerm/ttarray", "max_forks_repo_head_hexsha": "c962cb2be303dfdb6743aa802bd11b89043e7b71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.298245614, "max_line_length": 71, "alphanum_fraction": 0.6665098777, "include": true, "reason": "import numpy", "num_tokens": 570}
|
import pandas as pd
import numpy as np
import matplotlib.cm as cm
import matplotlib
from matplotlib.colors import LinearSegmentedColormap
from sklearn.preprocessing import StandardScaler
from transformers import BertTokenizerFast
from tqdm import tqdm
tqdm.pandas()
import ast
import logging
log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(level=logging.INFO, format=log_fmt)
logger = logging.getLogger("AttentionVisualizer")
class AttentionVisualizer():
def __init__(self, model_dir):
self.model_dir = model_dir
# tokenizer
self.tokenizer = BertTokenizerFast.from_pretrained(self.model_dir)
# combine word tokens
def combine_word_tokens(self, tokens_list, attn_list, agg_fn):
df_html = pd.DataFrame({'tokens':tokens_list, 'attention':attn_list})
# filter to remove special tokens
special_tokens = ['[CLS]', '[PAD]', '[SEP]']
df_html = df_html.loc[~df_html['tokens'].isin(special_tokens), :].reset_index(drop=True)
df_html['word_grp'] = 0
group = 0
for i in range(len(df_html['tokens'])):
word = df_html['tokens'].tolist()[i]
# if word is not a word piece, count as word
if '##' not in word:
group = group + 1
df_html.loc[i, 'word_grp'] = group
combined_tokens = df_html.groupby('word_grp')['tokens'].apply(lambda x: ' '.join(x))
combined_attn = df_html.groupby('word_grp')['attention'].agg(agg_fn)
# rescale attention
combined_attn = combined_attn / combined_attn.sum()
# clean up tokens
combined_tokens = combined_tokens.str.replace(' ##', '')
# output lists
combined_tokens = combined_tokens.tolist()
combined_attn = combined_attn.tolist()
return combined_tokens, combined_attn
# Create html visualization of attention weights
def create_html(self, tokens_list, attn_list, clip_neg=True):
# create custom colour map
cmap = LinearSegmentedColormap.from_list('rg', ['r', 'w', 'g'], N=256)
df_html = pd.DataFrame({'tokens':tokens_list, 'attention':attn_list})
# filter to remove special tokens
special_tokens = ['[CLS]', '[PAD]', '[SEP]']
df_html = df_html.loc[~df_html['tokens'].isin(special_tokens), :].reset_index(drop=True)
# Rescale attention weights
df_html['attention'] = df_html['attention'] / df_html['attention'].sum()
# create colour map
norm = matplotlib.colors.TwoSlopeNorm(vmin=-3, vcenter=0, vmax=3)
m = cm.ScalarMappable(norm=norm, cmap=cmap)
# standardize attention weights
norm_attn = pd.Series(
StandardScaler().fit_transform(df_html['attention'].values.reshape(-1,1)).flatten()
)
# clip outliers
norm_attn[norm_attn > 3] = 3
norm_attn[norm_attn < -3] = -3
# clip norm weights <= 0
if clip_neg:
norm_attn[norm_attn <= 0] = 0
# get colours
df_html['colour'] = norm_attn.apply(lambda x: matplotlib.colors.to_hex(m.to_rgba(x)))
html_text = '<span style="background-color:' + df_html['colour'] + ';">' \
+ df_html['tokens'] + '</span>'
html_text = ' '.join(html_text)
return html_text
def visualize_attention(self, df, agg_fn='max'):
df = df.copy()
# convert strings to back to lists
if isinstance(df['input_ids'].values[0], str):
logger.info('Convert input_ids strings back to lists...')
df['input_ids'] = df['input_ids'].progress_apply(ast.literal_eval)
if isinstance(df['attn_wts'].values[0], str):
logger.info('Convert attn_wts strings back to lists...')
df['attn_wts'] = df['attn_wts'].progress_apply(ast.literal_eval)
# get tokens from ids
logger.info('Convert ids to tokens...')
df['tokens'] = df['input_ids'].progress_apply(self.tokenizer.convert_ids_to_tokens)
# combine tokens and attention weights from word pieces
logger.info('Combine word pieces and attention weights...')
new_tokens_attn = \
df.progress_apply(lambda x: self.combine_word_tokens(x['tokens'], x['attn_wts'], agg_fn=agg_fn), axis=1)
# convert to structured form
new_tokens_attn = new_tokens_attn.apply(pd.Series)
# concat with original dataframe
df['new_tokens'] = new_tokens_attn.iloc[:,0]
df['new_attn_wts'] = new_tokens_attn.iloc[:,1]
# create html strings
logger.info('Generate HTML text field...')
df['html'] = \
df.progress_apply(lambda x: self.create_html(x['new_tokens'], x['new_attn_wts']), axis=1)
return df
|
{"hexsha": "6c72271f3132e98b5b0c55ec0187b720a4c1f432", "size": 4821, "ext": "py", "lang": "Python", "max_stars_repo_path": "src/visualization/visualizer.py", "max_stars_repo_name": "howewenann/fake_news", "max_stars_repo_head_hexsha": "aa69c302c5b50fad08af321e1e116ed8506ebaf6", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/visualization/visualizer.py", "max_issues_repo_name": "howewenann/fake_news", "max_issues_repo_head_hexsha": "aa69c302c5b50fad08af321e1e116ed8506ebaf6", "max_issues_repo_licenses": ["FTL"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-05-31T05:58:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T05:58:04.000Z", "max_forks_repo_path": "src/visualization/visualizer.py", "max_forks_repo_name": "howewenann/long_texts", "max_forks_repo_head_hexsha": "aa69c302c5b50fad08af321e1e116ed8506ebaf6", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4357142857, "max_line_length": 112, "alphanum_fraction": 0.628707737, "include": true, "reason": "import numpy", "num_tokens": 1143}
|
#!/usr/bin/env python3
# encoding: utf-8
import os
import threading
import datetime
import time
import pandas as pd
import numpy as np
from .data_sets import TimeSeries, LiveTimeSeries, TimeSeriesForecast
def _get_example_data_set_path():
this_dir, this_filename = os.path.split(__file__)
return os.path.join(this_dir, 'datasets', 'internet-traffic-data.csv')
class LiveRandomData(LiveTimeSeries):
def __init__(self):
LiveTimeSeries.__init__(self, 'Live Random Time Series',
'Random data which is generated on the fly.', 'live data')
generator = threading.Thread(target=self.update_data)
generator.daemon=True
generator.start()
def update_data(self, *args, **kwargs):
mu = np.random.randint(0, 11)
sigma = np.random.ranf() * 2
while True:
timestamp = datetime.datetime.now()
data_point = sigma * np.random.randn() + mu
with self.mutex:
self.data[timestamp] = data_point
time.sleep(1)
def generate_random_live_data_set():
return LiveRandomData()
def generate_internet_traffic_forecast():
data = pd.read_csv(
_get_example_data_set_path(), parse_dates='Time', index_col='Time')
data = data / 8 / 2**30 # convert bits into GB
data = data['Internet traffic data (in bits)']
split_point = int(len(data) * 0.75)
training_set = data[:split_point]
test_set = data[split_point:]
forecast = pd.Series([data[t-1] for t in range(split_point, len(data))],
index=test_set.index, name='value')
upper_bound = forecast * 1.20
upper_bound.name = 'upper bound'
lower_bound = forecast * 0.80
lower_bound.name = 'lower bound'
prediction = pd.DataFrame([forecast, upper_bound, lower_bound]).transpose()
return TimeSeriesForecast('Internet Traffic Forecast', 'A exemplary \
forecast of the internet traffic of a private ISP.', training_set,
prediction, validation_split=1120780799)
def load_internet_traffic_data_set():
data = pd.read_csv(
_get_example_data_set_path(), parse_dates='Time', index_col='Time')
data = data / 8 / 2**30 # convert bits into GB
data.rename(columns={'Internet traffic data (in bits)':
'Internet traffic data (in GB)'}, inplace=True)
ts = data['Internet traffic data (in GB)']
description = 'Internet traffic data (in GB) from a private ISP with \
centres in 11 European cities. The data corresponds to a transatlantic \
link and was collected from 06:57 hours on 7 June to 11:17 hours on 31 \
July 2005. Data collected at five minute intervals.'
return TimeSeries('Internet Traffic Data Set', description, ts,
legend='traffic')
def generate_random_data_set(nsamples=1000):
generate_random_data_set.counter += 1
rng = pd.date_range('2010-01-01', periods=nsamples, freq='H')
mu = np.random.randint(0, 11)
sigma = np.random.ranf() * 2
ts = pd.Series(sigma * np.random.randn(len(rng)) + mu, index=rng)
name = 'Random Data Set {}'.format(generate_random_data_set.counter)
description = 'Random data of {} samples, drawn from a normal distribution \
with μ={} and σ={:.2f}'.format(nsamples, mu, sigma)
return TimeSeries(name, description, ts, legend='random')
generate_random_data_set.counter = 0
|
{"hexsha": "44a1a1c33be366ac281eb57f7c634812cd3d9b98", "size": 3379, "ext": "py", "lang": "Python", "max_stars_repo_path": "timeline/example_data_sets.py", "max_stars_repo_name": "dumfug/mmis2", "max_stars_repo_head_hexsha": "7a1ea3180ec5818407799d5685dc6240b5c68697", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "timeline/example_data_sets.py", "max_issues_repo_name": "dumfug/mmis2", "max_issues_repo_head_hexsha": "7a1ea3180ec5818407799d5685dc6240b5c68697", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "timeline/example_data_sets.py", "max_forks_repo_name": "dumfug/mmis2", "max_forks_repo_head_hexsha": "7a1ea3180ec5818407799d5685dc6240b5c68697", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7282608696, "max_line_length": 80, "alphanum_fraction": 0.675347736, "include": true, "reason": "import numpy", "num_tokens": 821}
|
DEFINER FORTH ." FORTH" DOES> ;
DEFINER UFLOAD ." UFLOAD" DOES> ;
DEFINER FNEGATE ." FNEGATE" DOES> ;
DEFINER F/ ." F/" DOES> ;
DEFINER F* ." F*" DOES> ;
DEFINER F+ ." F+" DOES> ;
DEFINER F- ." F-" DOES> ;
DEFINER LOAD ." LOAD" DOES> ;
DEFINER BVERIFY ." BVERIFY" DOES> ;
DEFINER VERIFY ." VERIFY" DOES> ;
DEFINER BLOAD ." BLOAD" DOES> ;
DEFINER BSAVE ." BSAVE" DOES> ;
DEFINER SAVE ." SAVE" DOES> ;
DEFINER LIST ." LIST" DOES> ;
DEFINER EDIT ." EDIT" DOES> ;
DEFINER FORGET ." FORGET" DOES> ;
DEFINER REDEFINE ." REDEFINE" DOES> ;
DEFINER EXIT ." EXIT" DOES> ;
\ ."
DEFINER ( ." (" DOES> ;
DEFINER [ ." [" DOES> ;
DEFINER +LOOP ." +LOOP" DOES> ;
DEFINER LOOP ." LOOP" DOES> ;
DEFINER DO ." DO" DOES> ;
DEFINER UNTIL ." UNTIL" DOES> ;
DEFINER REPEAT ." REPEAT" DOES> ;
DEFINER BEGIN ." BEGIN" DOES> ;
DEFINER THEN ." THEN" DOES> ;
DEFINER ELSE ." ELSE" DOES> ;
DEFINER WHILE ." WHILE" DOES> ;
DEFINER IF ." IF" DOES> ;
DEFINER ] ." ]" DOES> ;
DEFINER LEAVE ." LEAVE" DOES> ;
DEFINER J ." J" DOES> ;
DEFINER I' ." I'" DOES> ;
DEFINER I ." I" DOES> ;
DEFINER DEFINITIONS ." DEFINITIONS" DOES> ;
DEFINER VOCABULARY ." VOCABULARY" DOES> ;
DEFINER IMMEDIATE ." IMMEDIATE" DOES> ;
DEFINER RUNS> ." RUNS>" DOES> ;
\ DOES>
DEFINER COMPILER ." COMPILER" DOES> ;
DEFINER CALL ." CALL" DOES> ;
DEFINER DEFINER ." DEFINER" DOES> ;
DEFINER ASCII ." ASCII" DOES> ;
DEFINER LITERAL ." LITERAL" DOES> ;
DEFINER CONSTANT ." CONSTANT" DOES> ;
DEFINER VARIABLE ." VARIABLE" DOES> ;
DEFINER ALLOT ." ALLOT" DOES> ;
DEFINER C, ." C," DOES> ;
\ ,
DEFINER CREATE ." CREATE" DOES> ;
DEFINER : ." :" DOES> ;
DEFINER DECIMAL ." DECIMAL" DOES> ;
DEFINER MIN ." MIN" DOES> ;
DEFINER MAX ." MAX" DOES> ;
DEFINER XOR ." XOR" DOES> ;
DEFINER AND ." AND" DOES> ;
DEFINER OR ." OR" DOES> ;
DEFINER 2- ." 2-" DOES> ;
DEFINER 1- ." 1-" DOES> ;
DEFINER 2+ ." 2+" DOES> ;
DEFINER 1+ ." 1+" DOES> ;
DEFINER D+ ." D+" DOES> ;
DEFINER - ." -" DOES> ;
DEFINER + ." +" DOES> ;
DEFINER DNEGATE ." DNEGATE" DOES> ;
DEFINER NEGATE ." NEGATE" DOES> ;
DEFINER U/MOD ." U/MOD" DOES> ;
DEFINER */ ." */" DOES> ;
DEFINER * ." *" DOES> ;
DEFINER MOD ." MOD" DOES> ;
DEFINER / ." /" DOES> ;
DEFINER */MOD ." */MOD" DOES> ;
DEFINER /MOD ." /MOD" DOES> ;
DEFINER U* ." U*" DOES> ;
DEFINER D< ." D<" DOES> ;
DEFINER U< ." U<" DOES> ;
DEFINER < ." <" DOES> ;
DEFINER > ." >" DOES> ;
DEFINER = ." =" DOES> ;
DEFINER 0> ." 0>" DOES> ;
DEFINER 0< ." 0<" DOES> ;
DEFINER 0= ." 0=" DOES> ;
DEFINER ABS ." ABS" DOES> ;
DEFINER OUT ." OUT" DOES> ;
DEFINER IN ." IN" DOES> ;
DEFINER INKEY ." INKEY" DOES> ;
DEFINER BEEP ." BEEP" DOES> ;
DEFINER PLOT ." PLOT" DOES> ;
DEFINER AT ." AT" DOES> ;
DEFINER F. ." F." DOES> ;
DEFINER EMIT ." EMIT" DOES> ;
DEFINER CR ." CR" DOES> ;
DEFINER SPACES ." SPACES" DOES> ;
DEFINER SPACE ." SPACE" DOES> ;
DEFINER HOLD ." HOLD" DOES> ;
DEFINER CLS ." CLS" DOES> ;
DEFINER # ." #" DOES> ;
DEFINER #S ." #S" DOES> ;
DEFINER U. ." U." DOES> ;
DEFINER . ." ." DOES> ;
DEFINER SIGN ." SIGN" DOES> ;
DEFINER #> ." #>" DOES> ;
DEFINER <# ." <#" DOES> ;
DEFINER TYPE ." TYPE" DOES> ;
DEFINER ROLL ." ROLL" DOES> ;
DEFINER PICK ." PICK" DOES> ;
DEFINER OVER ." OVER" DOES> ;
DEFINER ROT ." ROT" DOES> ;
DEFINER ?DUP ." ?DUP" DOES> ;
DEFINER R> ." R>" DOES> ;
DEFINER >R ." >R" DOES> ;
DEFINER ! ." !" DOES> ;
DEFINER @ ." @" DOES> ;
DEFINER C! ." C!" DOES> ;
DEFINER C@ ." C@" DOES> ;
DEFINER SWAP ." SWAP" DOES> ;
DEFINER DROP ." DROP" DOES> ;
DEFINER DUP ." DUP" DOES> ;
DEFINER SLOW ." SLOW" DOES> ;
DEFINER FAST ." FAST" DOES> ;
DEFINER INVIS ." INVIS" DOES> ;
DEFINER VIS ." VIS" DOES> ;
DEFINER CONVERT ." CONVERT" DOES> ;
DEFINER NUMBER ." NUMBER" DOES> ;
DEFINER EXECUTE ." EXECUTE" DOES> ;
DEFINER FIND ." FIND" DOES> ;
DEFINER VLIST ." VLIST" DOES> ;
DEFINER WORD ." WORD" DOES> ;
DEFINER RETYPE ." RETYPE" DOES> ;
DEFINER QUERY ." QUERY" DOES> ;
DEFINER LINE ." LINE" DOES> ;
DEFINER PAD ." PAD" DOES> ;
DEFINER BASE ." BASE" DOES> ;
DEFINER CURRENT ." CURRENT" DOES> ;
DEFINER CONTEXT ." CONTEXT" DOES> ;
DEFINER HERE ." HERE" DOES> ;
DEFINER ABORT ." ABORT" DOES> ;
DEFINER QUIT ." QUIT" DOES> ;
|
{"hexsha": "86568622a58791f487182f7e9d6ac37eabed3b2e", "size": 4211, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "h2oforth/jup.f", "max_stars_repo_name": "hemmerling/cpp-h2oforth", "max_stars_repo_head_hexsha": "d97eb2d8cc93c9b0843bc20534f1da27f06502d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "h2oforth/jup.f", "max_issues_repo_name": "hemmerling/cpp-h2oforth", "max_issues_repo_head_hexsha": "d97eb2d8cc93c9b0843bc20534f1da27f06502d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "h2oforth/jup.f", "max_forks_repo_name": "hemmerling/cpp-h2oforth", "max_forks_repo_head_hexsha": "d97eb2d8cc93c9b0843bc20534f1da27f06502d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.865248227, "max_line_length": 44, "alphanum_fraction": 0.5810971266, "num_tokens": 1509}
|
# -*- coding: utf-8 -*-
"""Tests for single-instance prediction"""
import os
import pytest
import numpy as np
import treelite
import treelite_runtime
from treelite.util import has_sklearn
from treelite.contrib import _libext
from .metadata import dataset_db
from .util import os_compatible_toolchains, check_predictor_output
@pytest.mark.skipif(not has_sklearn(), reason='Needs scikit-learn')
@pytest.mark.parametrize('toolchain', os_compatible_toolchains())
@pytest.mark.parametrize('dataset', ['mushroom', 'dermatology', 'toy_categorical'])
def test_single_inst(tmpdir, annotation, dataset, toolchain):
# pylint: disable=too-many-locals
"""Run end-to-end test"""
libpath = os.path.join(tmpdir, dataset_db[dataset].libname + _libext())
model = treelite.Model.load(dataset_db[dataset].model, model_format=dataset_db[dataset].format)
annotation_path = os.path.join(tmpdir, 'annotation.json')
if annotation[dataset] is None:
annotation_path = None
else:
with open(annotation_path, 'w') as f:
f.write(annotation[dataset])
params = {
'annotate_in': (annotation_path if annotation_path else 'NULL'),
'quantize': 1, 'parallel_comp': model.num_tree
}
model.export_lib(toolchain=toolchain, libpath=libpath, params=params, verbose=True)
predictor = treelite_runtime.Predictor(libpath=libpath, verbose=True)
from sklearn.datasets import load_svmlight_file
X_test, _ = load_svmlight_file(dataset_db[dataset].dtest, zero_based=True)
out_prob = [[] for _ in range(4)]
out_margin = [[] for _ in range(4)]
for i in range(X_test.shape[0]):
x = X_test[i, :]
# Scipy CSR matrix
out_prob[0].append(predictor.predict_instance(x))
out_margin[0].append(predictor.predict_instance(x, pred_margin=True))
# NumPy 1D array with 0 as missing value
x = x.toarray().flatten()
out_prob[1].append(predictor.predict_instance(x, missing=0.0))
out_margin[1].append(predictor.predict_instance(x, missing=0.0, pred_margin=True))
# NumPy 1D array with np.nan as missing value
np.place(x, x == 0.0, [np.nan])
out_prob[2].append(predictor.predict_instance(x, missing=np.nan))
out_margin[2].append(predictor.predict_instance(x, missing=np.nan, pred_margin=True))
# NumPy 1D array with np.nan as missing value
# (default when `missing` parameter is unspecified)
out_prob[3].append(predictor.predict_instance(x))
out_margin[3].append(predictor.predict_instance(x, pred_margin=True))
for i in range(4):
check_predictor_output(dataset, X_test.shape,
out_margin=np.squeeze(np.array(out_margin[i])),
out_prob=np.squeeze(np.array(out_prob[i])))
|
{"hexsha": "10040bceec5b2d77432a8a520206cd458b22ee59", "size": 2816, "ext": "py", "lang": "Python", "max_stars_repo_path": "tests/python/test_single_inst.py", "max_stars_repo_name": "wphicks/treelite", "max_stars_repo_head_hexsha": "d0bf6e3277fc07a82708ca1515108e374b4b8cdb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/python/test_single_inst.py", "max_issues_repo_name": "wphicks/treelite", "max_issues_repo_head_hexsha": "d0bf6e3277fc07a82708ca1515108e374b4b8cdb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/python/test_single_inst.py", "max_forks_repo_name": "wphicks/treelite", "max_forks_repo_head_hexsha": "d0bf6e3277fc07a82708ca1515108e374b4b8cdb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3230769231, "max_line_length": 99, "alphanum_fraction": 0.69140625, "include": true, "reason": "import numpy", "num_tokens": 679}
|
subroutine simunpack(cpack,len,idrstmpl,ndpts,fld)
!$$$ SUBPROGRAM DOCUMENTATION BLOCK
! . . . .
! SUBPROGRAM: simunpack
! PRGMMR: Gilbert ORG: W/NP11 DATE: 2000-06-21
!
! ABSTRACT: This subroutine unpacks a data field that was packed using a
! simple packing algorithm as defined in the GRIB2 documention,
! using info from the GRIB2 Data Representation Template 5.0.
!
! PROGRAM HISTORY LOG:
! 2000-06-21 Gilbert
!
! USAGE: CALL simunpack(cpack,len,idrstmpl,ndpts,fld)
! INPUT ARGUMENT LIST:
! cpack - The packed data field (character*1 array)
! len - length of packed field cpack().
! idrstmpl - Contains the array of values for Data Representation
! Template 5.0
! ndpts - The number of data values to unpack
!
! OUTPUT ARGUMENT LIST:
! fld() - Contains the unpacked data values
!
! REMARKS: None
!
! ATTRIBUTES:
! LANGUAGE: XL Fortran 90
! MACHINE: IBM SP
!
!$$$
character(len=1),intent(in) :: cpack(len)
integer,intent(in) :: ndpts,len
integer,intent(in) :: idrstmpl(*)
real,intent(out) :: fld(ndpts)
integer :: ifld(ndpts)
integer(4) :: ieee
real :: ref,bscale,dscale
ieee = idrstmpl(1)
call rdieee(ieee,ref,1)
bscale = 2.0**real(idrstmpl(2))
dscale = 10.0**real(-idrstmpl(3))
nbits = idrstmpl(4)
itype = idrstmpl(5)
!
! if nbits equals 0, we have a constant field where the reference value
! is the data value at each gridpoint
!
if (nbits.ne.0) then
call gbytes(cpack,ifld,0,nbits,0,ndpts)
do j=1,ndpts
fld(j)=((real(ifld(j))*bscale)+ref)*dscale
enddo
else
do j=1,ndpts
fld(j)=ref
enddo
endif
return
end
|
{"hexsha": "612a28355fbeb434781167d043594268e0ef6b44", "size": 1847, "ext": "f", "lang": "FORTRAN", "max_stars_repo_path": "ungrib/src/ngl/g2/simunpack.f", "max_stars_repo_name": "martinremy/wps", "max_stars_repo_head_hexsha": "8bddbdbb612a0e019ae110df481461d5d904053a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38, "max_stars_repo_stars_event_min_datetime": "2020-11-30T21:49:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T23:09:46.000Z", "max_issues_repo_path": "ungrib/src/ngl/g2/simunpack.f", "max_issues_repo_name": "martinremy/wps", "max_issues_repo_head_hexsha": "8bddbdbb612a0e019ae110df481461d5d904053a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-07-07T20:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-23T15:13:01.000Z", "max_forks_repo_path": "ungrib/src/ngl/g2/simunpack.f", "max_forks_repo_name": "WRF-CMake/WPS", "max_forks_repo_head_hexsha": "69f5da12997d6685cb0640132c5ef398ba12c341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-12-21T22:39:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T09:30:17.000Z", "avg_line_length": 27.9848484848, "max_line_length": 73, "alphanum_fraction": 0.5917704385, "num_tokens": 565}
|
[STATEMENT]
lemma contains_predE:
assumes "Predicate.eval (contains_pred A x) y"
obtains "contains A x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (contains A x \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
pred.eval (contains_pred A x) y
goal (1 subgoal):
1. (contains A x \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(simp add: contains_pred_def contains_def split: if_split_asm)
|
{"llama_tokens": 175, "file": null, "length": 2}
|
import scipy.signal
import numpy as np
# ===========================
# Set rewards
# ===========================
class Reward(object):
def __init__(self, factor, gamma):
# Reward parameters
self.factor = factor
self.gamma = gamma
# Set step rewards to total episode reward
def total(self, ep_batch, tot_reward):
for step in ep_batch:
step[2] = tot_reward*self.factor
return ep_batch
# Set step rewards to discounted reward
def discount(self, r_batch):
# print('START---------in discount-----------')
# print('factor={}, gamma={}'.format(self.factor, self.gamma))
x = r_batch
# print('ep_batch[:,2] -> ' + str(x))
discounted = scipy.signal.lfilter([1], [1, -self.gamma], x[::-1], axis=0)[::-1]
# print('afte lfilter ->', discounted)
discounted *= self.factor
# print('afte *factor ->', discounted)
# print('ep_batch[:,2] -> ' + str(ep_batch[i,2]))
# print('END---------in discount-----------')
# print('reward discounted = ', discounted)
return discounted
# Set step rewards to discounted reward
def discount_batch(self, ep_batch):
# print('START---------in discount-----------')
# print('factor={}, gamma={}'.format(self.factor, self.gamma))
x = ep_batch[:,2]
# print('ep_batch[:,2] -> ' + str(x))
discounted = scipy.signal.lfilter([1], [1, -self.gamma], x[::-1], axis=0)[::-1]
# print('afte lfilter ->', discounted)
discounted *= self.factor
# print('afte *factor ->', discounted)
for i in range(len(discounted)):
ep_batch[i,2] = discounted[i]
# print('ep_batch[:,2] -> ' + str(ep_batch[i,2]))
# print('END---------in discount-----------')
return ep_batch
def discount_ori_print(self, ep_batch):
print('START---------in discount-----------')
print('factor={}, gamma={}'.format(self.factor, self.gamma))
x = ep_batch[:,2]
print('ep_batch[:,2] -> ' + str(x))
discounted = scipy.signal.lfilter([1], [1, -self.gamma], x[::-1], axis=0)[::-1]
print('afte lfilter ->', discounted)
discounted *= self.factor
print('afte *factor ->', discounted)
for i in range(len(discounted)):
ep_batch[i,2] = discounted[i]
print('ep_batch[:,2] -> ' + str(ep_batch[i,2]))
print('END---------in discount-----------')
return ep_batch
def discount_005(self, ep_batch):
# print('START---------in discount-----------')
# print('factor={}, gamma={}, len(x)={}'.format(self.factor, self.gamma,len(x)))
x = ep_batch[:,2]
# print('ep_batch[:,2] -> ' + str(x))
discounted_ep_rs = np.zeros_like(x)
for t in reversed(range(0, len(x))):
discounted_ep_rs[t] = 0.05 # all 0.05
# print('discounted_ep_rs -> ' + str(discounted_ep_rs))
# discounted_ep_rs *= self.factor
# print('discounted_ep_rs after * factor-> ' + str(discounted_ep_rs))
for i in range(len(discounted_ep_rs)):
ep_batch[i,2] = discounted_ep_rs[i]
# print('ep_batch[:,2] -> ' + str(ep_batch[:,2]))
# print('END---------in discount-----------')
return ep_batch
def discount_add_005(self, ep_batch):
# print('START---------in discount-----------')
# print('factor={}, gamma={}, len(x)={}'.format(self.factor, self.gamma,len(x)))
x = ep_batch[:,2]
# print('ep_batch[:,2] -> ' + str(x))
discounted_ep_rs = np.zeros_like(x)
running_add = 0
for t in reversed(range(0, len(x))):
discounted_ep_rs[t] = running_add * 0.05 * 1.0
running_add+=1
# print('discounted_ep_rs -> ' + str(discounted_ep_rs))
# discounted_ep_rs *= self.factor
# print('discounted_ep_rs after * factor-> ' + str(discounted_ep_rs))
for i in range(len(discounted_ep_rs)):
ep_batch[i,2] = discounted_ep_rs[i]
# print('ep_batch[:,2] -> ' + str(ep_batch[:,2]))
# print('END---------in discount-----------')
return ep_batch
def reverse_add_rewards(self, ep_rs, r_dicount = 0.9):
print('reverse_and_norm_rewards ep_rs -> len = {}, {}'.format(len(ep_rs), ep_rs))
# discount episode rewards
discounted_ep_rs = np.zeros_like(ep_rs)
running_add = 0
for t in reversed(range(0, len(ep_rs))):
running_add = running_add * r_dicount + ep_rs[t]
discounted_ep_rs[t] = running_add
print('reverse_add_rewards -> discounted_ep_rs = ' + str(discounted_ep_rs))
return discounted_ep_rs
|
{"hexsha": "a207f8638e1fecb593e6da37fc38cc7160e80332", "size": 4775, "ext": "py", "lang": "Python", "max_stars_repo_path": "DRL/component/reward.py", "max_stars_repo_name": "mdecourse/lightDRL", "max_stars_repo_head_hexsha": "4eff160f3797f88d20a059104c75e49d5295d932", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2018-01-07T08:48:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T07:29:31.000Z", "max_issues_repo_path": "DRL/component/reward.py", "max_issues_repo_name": "mdecourse/lightDRL", "max_issues_repo_head_hexsha": "4eff160f3797f88d20a059104c75e49d5295d932", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DRL/component/reward.py", "max_forks_repo_name": "mdecourse/lightDRL", "max_forks_repo_head_hexsha": "4eff160f3797f88d20a059104c75e49d5295d932", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-10-17T17:47:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T07:55:32.000Z", "avg_line_length": 34.6014492754, "max_line_length": 89, "alphanum_fraction": 0.5365445026, "include": true, "reason": "import numpy,import scipy", "num_tokens": 1174}
|
import numpy as np
import os
import logging
import pickle
import ray
from ray.tune import Trainable
from ray.tune.resources import Resources
from ray.experimental.sgd.tf.tf_runner import TFRunner
logger = logging.getLogger(__name__)
class TFTrainer:
def __init__(self,
model_creator,
data_creator,
config=None,
num_replicas=1,
use_gpu=False,
verbose=False):
"""Sets up the TensorFlow trainer.
Args:
model_creator (dict -> Model): This function takes in the `config`
dict and returns a compiled TF model.
data_creator (dict -> tf.Dataset, tf.Dataset): Creates
the training and validation data sets using the config.
`config` dict is passed into the function.
config (dict): configuration passed to 'model_creator',
'data_creator'. Also contains `fit_config`, which is passed
into `model.fit(data, **fit_config)` and
`evaluate_config` which is passed into `model.evaluate`.
num_replicas (int): Sets number of workers used in distributed
training. Workers will be placed arbitrarily across the
cluster.
use_gpu (bool): Enables all workers to use GPU.
verbose (bool): Prints output of one model if true.
"""
self.model_creator = model_creator
self.data_creator = data_creator
self.config = {} if config is None else config
self.use_gpu = use_gpu
self.num_replicas = num_replicas
self.verbose = verbose
# Generate actor class
# todo: are these resource quotas right?
# should they be exposed to the client codee?
Runner = ray.remote(num_cpus=1, num_gpus=int(use_gpu))(TFRunner)
# todo: should we warn about using
# distributed training on one device only?
# it's likely that whenever this happens it's a mistake
if num_replicas == 1:
# Start workers
self.workers = [
Runner.remote(
model_creator,
data_creator,
config=self.config,
verbose=self.verbose)
]
# Get setup tasks in order to throw errors on failure
ray.get(self.workers[0].setup.remote())
else:
# Start workers
self.workers = [
Runner.remote(
model_creator,
data_creator,
config=self.config,
verbose=self.verbose and i == 0)
for i in range(num_replicas)
]
# Compute URL for initializing distributed setup
ips = ray.get(
[worker.get_node_ip.remote() for worker in self.workers])
ports = ray.get(
[worker.find_free_port.remote() for worker in self.workers])
urls = [
"{ip}:{port}".format(ip=ips[i], port=ports[i])
for i in range(len(self.workers))
]
# Get setup tasks in order to throw errors on failure
ray.get([
worker.setup_distributed.remote(urls, i, len(self.workers))
for i, worker in enumerate(self.workers)
])
def train(self):
"""Runs a training epoch."""
# see ./tf_runner.py:setup_distributed
# for an explanation of only taking the first worker's data
worker_stats = ray.get([w.step.remote() for w in self.workers])
stats = worker_stats[0].copy()
return stats
def validate(self):
"""Evaluates the model on the validation data set."""
logger.info("Starting validation step.")
# see ./tf_runner.py:setup_distributed
# for an explanation of only taking the first worker's data
stats = ray.get([w.validate.remote() for w in self.workers])
stats = stats[0].copy()
return stats
def get_model(self):
"""Returns the learned model."""
state = ray.get(self.workers[0].get_state.remote())
return self._get_model_from_state(state)
def save(self, checkpoint):
"""Saves the model at the provided checkpoint.
Args:
checkpoint (str): Path to target checkpoint file.
"""
state = ray.get(self.workers[0].get_state.remote())
with open(checkpoint, "wb") as f:
pickle.dump(state, f)
return checkpoint
def restore(self, checkpoint):
"""Restores the model from the provided checkpoint.
Args:
checkpoint (str): Path to target checkpoint file.
"""
with open(checkpoint, "rb") as f:
state = pickle.load(f)
state_id = ray.put(state)
ray.get([worker.set_state.remote(state_id) for worker in self.workers])
def shutdown(self):
"""Shuts down workers and releases resources."""
for worker in self.workers:
worker.shutdown.remote()
worker.__ray_terminate__.remote()
def _get_model_from_state(self, state):
"""Creates model and load weights from state"""
model = self.model_creator(self.config)
model.set_weights(state["weights"])
# This part is due to ray.get() changing scalar np.int64 object to int
state["optimizer_weights"][0] = np.array(
state["optimizer_weights"][0], dtype=np.int64)
if model.optimizer.weights == []:
model._make_train_function()
model.optimizer.set_weights(state["optimizer_weights"])
return model
class TFTrainable(Trainable):
@classmethod
def default_resource_request(cls, config):
return Resources(
cpu=0,
gpu=0,
extra_cpu=config["num_replicas"],
extra_gpu=int(config["use_gpu"]) * config["num_replicas"])
def _setup(self, config):
self._trainer = TFTrainer(
model_creator=config["model_creator"],
data_creator=config["data_creator"],
config=config.get("trainer_config", {}),
num_replicas=config["num_replicas"],
use_gpu=config["use_gpu"])
def _train(self):
train_stats = self._trainer.train()
validation_stats = self._trainer.validate()
train_stats.update(validation_stats)
return train_stats
def _save(self, checkpoint_dir):
return self._trainer.save(os.path.join(checkpoint_dir, "model"))
def _restore(self, checkpoint_path):
return self._trainer.restore(checkpoint_path)
def _stop(self):
self._trainer.shutdown()
|
{"hexsha": "55cdbeb82567cedebc310d950201479a8c2d4112", "size": 6800, "ext": "py", "lang": "Python", "max_stars_repo_path": "python/ray/experimental/sgd/tf/tf_trainer.py", "max_stars_repo_name": "eisber/ray", "max_stars_repo_head_hexsha": "94a286ef1d8ad5a3093b7f996a811727fa0e2d3e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-10-18T17:44:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T14:37:21.000Z", "max_issues_repo_path": "python/ray/experimental/sgd/tf/tf_trainer.py", "max_issues_repo_name": "eisber/ray", "max_issues_repo_head_hexsha": "94a286ef1d8ad5a3093b7f996a811727fa0e2d3e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-30T17:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T17:52:44.000Z", "max_forks_repo_path": "python/ray/experimental/sgd/tf/tf_trainer.py", "max_forks_repo_name": "eisber/ray", "max_forks_repo_head_hexsha": "94a286ef1d8ad5a3093b7f996a811727fa0e2d3e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-26T07:54:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-26T07:54:25.000Z", "avg_line_length": 33.3333333333, "max_line_length": 79, "alphanum_fraction": 0.5857352941, "include": true, "reason": "import numpy", "num_tokens": 1357}
|
"""
Filename: plotter.py
Author: Deanna Nash, dlnash@ucsb.edu
Description: Functions for plotting
"""
# Import Python modules
import os, sys
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import matplotlib.ticker as mticker
import colorsys
from matplotlib.colors import LinearSegmentedColormap # Linear interpolation for color maps
import matplotlib.patches as mpatches
def draw_basemap(ax, datacrs=ccrs.PlateCarree(), extent=None, xticks=None, yticks=None, grid=False, left_lats=True, right_lats=False, bottom_lons=True, mask_ocean=False):
"""
Creates and returns a background map on which to plot data.
Map features include continents and country borders.
Option to set lat/lon tickmarks and draw gridlines.
Parameters
----------
ax :
plot Axes on which to draw the basemap
datacrs :
crs that the data comes in (usually ccrs.PlateCarree())
extent : float
Set map extent to [lonmin, lonmax, latmin, latmax]
Default: None (uses global extent)
grid : bool
Whether to draw grid lines. Default: False
xticks : float
array of xtick locations (longitude tick marks)
yticks : float
array of ytick locations (latitude tick marks)
left_lats : bool
Whether to add latitude labels on the left side. Default: True
right_lats : bool
Whether to add latitude labels on the right side. Default: False
Returns
-------
ax :
plot Axes with Basemap
Notes
-----
- Grayscale colors can be set using 0 (black) to 1 (white)
- Alpha sets transparency (0 is transparent, 1 is solid)
"""
# Use map projection (CRS) of the given Axes
mapcrs = ax.projection
## Map Extent
# If no extent is given, use global extent
if extent is None:
ax.set_global()
extent = [-180., 180., -90., 90.]
# If extent is given, set map extent to lat/lon bounding box
else:
ax.set_extent(extent, crs=datacrs)
# Add map features (continents and country borders)
ax.add_feature(cfeature.LAND, facecolor='0.9')
ax.add_feature(cfeature.BORDERS, edgecolor='0.4', linewidth=0.8)
ax.add_feature(cfeature.COASTLINE, edgecolor='0.4', linewidth=0.8)
if mask_ocean == True:
ax.add_feature(cfeature.OCEAN, edgecolor='0.4', zorder=12, facecolor='white') # mask ocean
## Tickmarks/Labels
## Add in meridian and parallels
if mapcrs == ccrs.NorthPolarStereo():
gl = ax.gridlines(draw_labels=False,
linewidth=.5, color='black', alpha=0.5, linestyle='--')
elif mapcrs == ccrs.SouthPolarStereo():
gl = ax.gridlines(draw_labels=False,
linewidth=.5, color='black', alpha=0.5, linestyle='--')
else:
gl = ax.gridlines(crs=mapcrs, draw_labels=True,
linewidth=.5, color='black', alpha=0.5, linestyle='--')
gl.top_labels = False
gl.left_labels = left_lats
gl.right_labels = right_lats
gl.bottom_labels = bottom_lons
gl.xlocator = mticker.FixedLocator(xticks)
gl.ylocator = mticker.FixedLocator(yticks)
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 10, 'color': 'gray'}
gl.ylabel_style = {'size': 10, 'color': 'gray'}
## Gridlines
# Draw gridlines if requested
if (grid == True):
gl.xlines = True
gl.ylines = True
if (grid == False):
gl.xlines = False
gl.ylines = False
# apply tick parameters
ax.tick_params(direction='out',
labelsize=10,
length=4,
pad=2,
color='black')
return ax
def add_subregion_boxes(ax, subregion_xy, width, height, ecolor, datacrs):
'''This function will add subregion boxes to the given axes.
subregion_xy
[[ymin, xmin], [ymin, xmin]]
'''
for i in range(len(subregion_xy)):
ax.add_patch(mpatches.Rectangle(xy=subregion_xy[i], width=width[i], height=height[i],
fill=False,
edgecolor=ecolor,
linewidth=1.0,
transform=datacrs,
zorder=100))
return ax
def plot_maxmin_points(lon, lat, data, extrema, nsize, symbol, color='k',
plotValue=True, transform=None):
"""
This function will find and plot relative maximum and minimum for a 2D grid. The function
can be used to plot an H for maximum values (e.g., High pressure) and an L for minimum
values (e.g., low pressue). It is best to used filetered data to obtain a synoptic scale
max/min value. The symbol text can be set to a string value and optionally the color of the
symbol and any plotted value can be set with the parameter color
lon = plotting longitude values (2D)
lat = plotting latitude values (2D)
data = 2D data that you wish to plot the max/min symbol placement
extrema = Either a value of max for Maximum Values or min for Minimum Values
nsize = Size of the grid box to filter the max and min values to plot a reasonable number
symbol = String to be placed at location of max/min value
color = String matplotlib colorname to plot the symbol (and numerica value, if plotted)
plot_value = Boolean (True/False) of whether to plot the numeric value of max/min point
The max/min symbol will be plotted on the current axes within the bounding frame
(e.g., clip_on=True)
^^^ Notes from MetPy. Function adapted from MetPy.
"""
from scipy.ndimage.filters import maximum_filter, minimum_filter
if (extrema == 'max'):
data_ext = maximum_filter(data, nsize, mode='nearest')
elif (extrema == 'min'):
data_ext = minimum_filter(data, nsize, mode='nearest')
else:
raise ValueError('Value for hilo must be either max or min')
mxy, mxx = np.where(data_ext == data)
for i in range(len(mxy)):
ax.text(lon[mxy[i], mxx[i]], lat[mxy[i], mxx[i]], symbol, color=color, size=13,
clip_on=True, horizontalalignment='center', verticalalignment='center',
fontweight='extra bold',
transform=transform)
ax.text(lon[mxy[i], mxx[i]], lat[mxy[i], mxx[i]],
'\n \n' + str(np.int(data[mxy[i], mxx[i]])),
color=color, size=8, clip_on=True, fontweight='bold',
horizontalalignment='center', verticalalignment='center',
transform=transform, zorder=10)
return ax
def loadCPT(path):
"""A function that loads a .cpt file and converts it into a colormap for the colorbar.
This code was adapted from the GEONETClass Tutorial written by Diego Souza, retrieved 18 July 2019.
https://geonetcast.wordpress.com/2017/06/02/geonetclass-manipulating-goes-16-data-with-python-part-v/
Parameters
----------
path :
Path to the .cpt file
Returns
-------
cpt :
A colormap that can be used for the cmap argument in matplotlib type plot.
"""
try:
f = open(path)
except:
print ("File ", path, "not found")
return None
lines = f.readlines()
f.close()
x = np.array([])
r = np.array([])
g = np.array([])
b = np.array([])
colorModel = 'RGB'
for l in lines:
ls = l.split()
if l[0] == '#':
if ls[-1] == 'HSV':
colorModel = 'HSV'
continue
else:
continue
if ls[0] == 'B' or ls[0] == 'F' or ls[0] == 'N':
pass
else:
x=np.append(x,float(ls[0]))
r=np.append(r,float(ls[1]))
g=np.append(g,float(ls[2]))
b=np.append(b,float(ls[3]))
xtemp = float(ls[4])
rtemp = float(ls[5])
gtemp = float(ls[6])
btemp = float(ls[7])
x=np.append(x,xtemp)
r=np.append(r,rtemp)
g=np.append(g,gtemp)
b=np.append(b,btemp)
if colorModel == 'HSV':
for i in range(r.shape[0]):
rr, gg, bb = colorsys.hsv_to_rgb(r[i]/360.,g[i],b[i])
r[i] = rr ; g[i] = gg ; b[i] = bb
if colorModel == 'RGB':
r = r/255.0
g = g/255.0
b = b/255.0
xNorm = (x - x[0])/(x[-1] - x[0])
red = []
blue = []
green = []
for i in range(len(x)):
red.append([xNorm[i],r[i],r[i]])
green.append([xNorm[i],g[i],g[i]])
blue.append([xNorm[i],b[i],b[i]])
colorDict = {'red': red, 'green': green, 'blue': blue}
# Makes a linear interpolation
cpt = LinearSegmentedColormap('cpt', colorDict)
return cpt
def make_cmap(colors, position=None, bit=False):
'''
make_cmap takes a list of tuples which contain RGB values. The RGB
values may either be in 8-bit [0 to 255] (in which bit must be set to
True when called) or arithmetic [0 to 1] (default). make_cmap returns
a cmap with equally spaced colors.
Arrange your tuples so that the first color is the lowest value for the
colorbar and the last is the highest.
position contains values from 0 to 1 to dictate the location of each color.
'''
import matplotlib as mpl
import numpy as np
bit_rgb = np.linspace(0,1,256)
if position == None:
position = np.linspace(0,1,len(colors))
else:
if len(position) != len(colors):
sys.exit("position length must be the same as colors")
elif position[0] != 0 or position[-1] != 1:
sys.exit("position must start with 0 and end with 1")
if bit:
for i in range(len(colors)):
colors[i] = (bit_rgb[colors[i][0]],
bit_rgb[colors[i][1]],
bit_rgb[colors[i][2]])
cdict = {'red':[], 'green':[], 'blue':[]}
for pos, color in zip(position, colors):
cdict['red'].append((pos, color[0], color[0]))
cdict['green'].append((pos, color[1], color[1]))
cdict['blue'].append((pos, color[2], color[2]))
cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256)
return cmap
def nice_intervals(data, nlevs):
'''
Purpose::
Calculates nice intervals between each color level for colorbars
and contour plots. The target minimum and maximum color levels are
calculated by taking the minimum and maximum of the distribution
after cutting off the tails to remove outliers.
Input::
data - an array of data to be plotted
nlevs - an int giving the target number of intervals
Output::
clevs - A list of floats for the resultant colorbar levels
'''
# Find the min and max levels by cutting off the tails of the distribution
# This mitigates the influence of outliers
data = data.ravel()
mn = mstats.scoreatpercentile(data, 5)
mx = mstats.scoreatpercentile(data, 95)
# if min less than 0 and or max more than 0 put 0 in center of color bar
if mn < 0 and mx > 0:
level = max(abs(mn), abs(mx))
mnlvl = -1 * level
mxlvl = level
# if min is larger than 0 then have color bar between min and max
else:
mnlvl = mn
mxlvl = mx
# hack to make generated intervals from mpl the same for all versions
autolimit_mode = mpl.rcParams.get('axes.autolimit_mode')
if autolimit_mode:
mpl.rc('axes', autolimit_mode='round_numbers')
locator = mpl.ticker.MaxNLocator(nlevs)
clevs = locator.tick_values(mnlvl, mxlvl)
if autolimit_mode:
mpl.rc('axes', autolimit_mode=autolimit_mode)
# Make sure the bounds of clevs are reasonable since sometimes
# MaxNLocator gives values outside the domain of the input data
clevs = clevs[(clevs >= mnlvl) & (clevs <= mxlvl)]
return clevs
|
{"hexsha": "6271e131c0b3e1bfd38f2a501ebbc7f388fe489a", "size": 12398, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/deanna_nash/modules/plotter.py", "max_stars_repo_name": "dlnash/USWest_Water", "max_stars_repo_head_hexsha": "012d286977e330f82088736599bd9d7ba7083b41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-07-14T15:16:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T08:47:58.000Z", "max_issues_repo_path": "notebooks/deanna_nash/modules/plotter.py", "max_issues_repo_name": "dlnash/USWest_Water", "max_issues_repo_head_hexsha": "012d286977e330f82088736599bd9d7ba7083b41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/deanna_nash/modules/plotter.py", "max_forks_repo_name": "dlnash/USWest_Water", "max_forks_repo_head_hexsha": "012d286977e330f82088736599bd9d7ba7083b41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-13T20:10:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T18:01:11.000Z", "avg_line_length": 35.3219373219, "max_line_length": 170, "alphanum_fraction": 0.5999354735, "include": true, "reason": "import numpy,from scipy", "num_tokens": 3162}
|
import random
import matplotlib.pyplot as plt
import numpy as np
import time
class Trainer(object):
def __init__(self, lr, batch_size, epoch, lamda):
self.lr = lr
self.batch_size = batch_size
self.epoch = epoch
self.lamda = lamda
def gradient_ascent(self, model, batch_x, batch_y):
*grad, = model.compute_batch_grad(batch_x, batch_y, self.lamda)
model.fit_params(self.lr, *grad)
def train(self, model, train_x, train_y, test_x, test_y):
order = [i for i in range(len(train_x))]
ll, acc = [], []
start_time = time.time()
for i in range(self.epoch):
random.shuffle(order)
for j in range(0, len(order), self.batch_size):
tmp = order[j: j+self.batch_size]
batch_x = [train_x[k] for k in tmp]
batch_y = [train_y[k] for k in tmp]
self.gradient_ascent(model, batch_x, batch_y)
ll.append(model.compute_batch_ll(train_x, train_y))
acc.append(self.eval(model, test_x, test_y))
print(f"iter:{i},loglikelihood:{ll[-1]}, acc:{acc[-1]}")
total_time = time.time()-start_time
print(f"Time:{total_time}")
tmp = np.array([ll, acc])
plt.title('LogLikeliHood')
plt.xlabel('iterate times')
plt.ylabel('loglikelihood')
plt.plot(range(len(ll)), ll)
plt.show()
plt.title('Accuracy')
plt.xlabel('iterate times')
plt.ylabel('accuracy')
plt.plot(range(len(acc)), acc)
plt.show()
def eval(self, model, test_x, test_y):
p1, p2 = 0, 0
for i in range(len(test_x)):
pred, *_ = model.inference(test_x[i])
tmp = (np.array(pred) == np.array(test_y[i]))
p1 += tmp.sum()
p2 += tmp.shape[0]
return p1/p2
|
{"hexsha": "b0f7f9567aff09e43f041c95778a4eafd2b954f3", "size": 1872, "ext": "py", "lang": "Python", "max_stars_repo_path": "AML/HW3/utils/trainer.py", "max_stars_repo_name": "ZRZ-Unknow/20fall-CourseNote", "max_stars_repo_head_hexsha": "e20735fd1ca0949eaa1c50d5cd84f147ec714404", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AML/HW3/utils/trainer.py", "max_issues_repo_name": "ZRZ-Unknow/20fall-CourseNote", "max_issues_repo_head_hexsha": "e20735fd1ca0949eaa1c50d5cd84f147ec714404", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AML/HW3/utils/trainer.py", "max_forks_repo_name": "ZRZ-Unknow/20fall-CourseNote", "max_forks_repo_head_hexsha": "e20735fd1ca0949eaa1c50d5cd84f147ec714404", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.320754717, "max_line_length": 71, "alphanum_fraction": 0.5625, "include": true, "reason": "import numpy", "num_tokens": 470}
|
# Imports
import os
import random
import numpy as np
from time import time
import cProfile
import io
import pstats
import sys
sys.path.append("/Users/au568658/Desktop/Academ/Projects/tomsup")
import tomsup as ts
# Set seed
random.seed(1995)
# - Simulation settings - #
n_tests = 20
n_sim = 8
n_rounds = 60
# (Short run)
# n_tests = 2
# n_sim = 2
# n_rounds = 10
# Get payoff matrix
penny_comp = ts.PayoffMatrix(name="penny_competitive")
n_jobs = 4
# Create list of agents
agents = ["2-ToM", "RB"]
# Set parameters
start_params = [{}, {}]
# Initialize vector for populaitng with times
elapsed_times = [None] * n_tests
# pr = cProfile.Profile()
# pr.enable()
for test in range(n_tests):
# print(test)
# Get start time
start_time = time()
# Make group
group = ts.create_agents(agents, start_params)
# Set as round robin tournament
group.set_env(env="round_robin")
# Run tournament
results = group.compete(
p_matrix=penny_comp,
n_rounds=n_rounds,
n_sim=n_sim,
save_history=False,
verbose=False,
n_jobs=n_jobs,
)
# Save elapsed time in vector
elapsed_times[test] = time() - start_time
# Get mean and standard deviations
print(np.mean(elapsed_times))
print(np.std(elapsed_times))
# pr.disable()
# with open("output_time2.txt", "w") as f:
# ps = pstats.Stats(pr, stream=f)
# ps.strip_dirs().sort_stats("time").print_stats()
# with open("output_calls2.txt", "w") as f:
# ps = pstats.Stats(pr, stream=f)
# ps.strip_dirs().sort_stats("calls").print_stats()
# python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)
# python -m cProfile -o speed.txt simulations/speedtest.py
|
{"hexsha": "6728f93bf4a76c1818388f404ac4eac2a50942b7", "size": 1722, "ext": "py", "lang": "Python", "max_stars_repo_path": "papers/introducing_tomsup/comparison/tomsup_speed_comparison.py", "max_stars_repo_name": "langner/tomsup", "max_stars_repo_head_hexsha": "8dad2e701ef797c0a1d5ea323109efae1c527fe0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32, "max_stars_repo_stars_event_min_datetime": "2019-08-22T10:05:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:23:40.000Z", "max_issues_repo_path": "papers/introducing_tomsup/comparison/tomsup_speed_comparison.py", "max_issues_repo_name": "langner/tomsup", "max_issues_repo_head_hexsha": "8dad2e701ef797c0a1d5ea323109efae1c527fe0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16, "max_issues_repo_issues_event_min_datetime": "2020-09-20T13:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:29:23.000Z", "max_forks_repo_path": "papers/introducing_tomsup/comparison/tomsup_speed_comparison.py", "max_forks_repo_name": "langner/tomsup", "max_forks_repo_head_hexsha": "8dad2e701ef797c0a1d5ea323109efae1c527fe0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-09-19T10:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T22:11:02.000Z", "avg_line_length": 19.7931034483, "max_line_length": 79, "alphanum_fraction": 0.6742160279, "include": true, "reason": "import numpy", "num_tokens": 486}
|
// Copyright Tom Westerhout 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "testing.hpp"
#include <utility>
#include <boost/static_views/raw_view.hpp>
#include <boost/static_views/transform.hpp>
auto test_make()
{
static constexpr int xs_data[20] = {};
struct foo {
foo() = default;
foo(foo const&) = delete;
foo(foo&&) = default;
foo& operator=(foo&&) = default;
foo& operator=(foo const&) = delete;
constexpr auto operator()(int const x) const noexcept
{
return 1.0f / static_cast<float>(x);
}
};
// construction from an lvalue reference
{
static constexpr auto xs = boost::static_views::raw_view(xs_data);
// Normal function call
constexpr auto ys = boost::static_views::transform(xs, foo{});
using ys_type = std::remove_cv_t<decltype(ys)>;
STATIC_ASSERT(boost::static_views::View<ys_type>,
"transform view constructed from an lvalue reference does not "
"model the View concept.");
STATIC_ASSERT((boost::static_views::Same<ys_type::reference, float>),
"But foo::operator() returns a float!");
STATIC_ASSERT((boost::static_views::Same<ys_type::value_type, float>),
"But foo::operator() returns a float!");
// Curried function call
constexpr auto zs = boost::static_views::transform(foo{})(xs);
using zs_type = std::remove_cv_t<decltype(zs)>;
STATIC_ASSERT(boost::static_views::View<zs_type>,
"transform view constructed from an lvalue reference does not "
"model the View concept.");
}
// construction from an rvalue reference
{
static constexpr auto foo_c = foo{};
// Normal function call
constexpr auto ys = boost::static_views::transform(
boost::static_views::raw_view(xs_data), foo_c);
using ys_type = std::remove_cv_t<decltype(ys)>;
STATIC_ASSERT(boost::static_views::View<ys_type>,
"transform view constructed from an rvalue reference does not "
"model the View concept.");
// Curried function call
// This one is tricky, because foo_c is a reference and foo's copy
// constructor is deleted, so the reference has to be propagated all the
// way.
constexpr auto zs = boost::static_views::transform(foo_c)(
boost::static_views::raw_view(xs_data));
using zs_type = std::remove_cv_t<decltype(zs)>;
STATIC_ASSERT(boost::static_views::View<zs_type>,
"transform view constructed from an rvalue reference does not "
"model the View concept.");
}
// copy and move
{
static constexpr auto foo_c = foo{};
static constexpr auto xs = boost::static_views::raw_view(xs_data);
constexpr auto ys = boost::static_views::transform(xs, foo{});
constexpr auto zs = boost::static_views::transform(xs, foo_c);
using ys_type = std::remove_cv_t<decltype(ys)>;
using zs_type = std::remove_cv_t<decltype(zs)>;
STATIC_ASSERT(!std::is_copy_constructible<ys_type>::value,
"ys should not be copy-constructible, because foo is not.");
STATIC_ASSERT(std::is_nothrow_copy_constructible<zs_type>::value,
"zs is not nothrow copyable.");
STATIC_ASSERT(std::is_nothrow_move_constructible<ys_type>::value,
"ys is not nothrow movable.");
STATIC_ASSERT(std::is_nothrow_move_constructible<zs_type>::value,
"zs is not nothrow movable.");
STATIC_ASSERT(!std::is_copy_assignable<ys_type>::value,
"ys should not be copy-assignable, because foo is not.");
STATIC_ASSERT(std::is_nothrow_copy_assignable<zs_type>::value,
"zs is not nothrow copyable.");
STATIC_ASSERT(std::is_nothrow_move_assignable<ys_type>::value,
"drop view is not nothrow movable.");
STATIC_ASSERT(std::is_nothrow_move_assignable<zs_type>::value,
"drop view is not nothrow movable.");
}
}
int main()
{
test_make();
return boost::report_errors();
}
|
{"hexsha": "a0c17a9b0e662ab7c4cc77adbf937bed27d3b705", "size": 4380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/correctness/transform_pass.cpp", "max_stars_repo_name": "BoostGSoC17/static-map", "max_stars_repo_head_hexsha": "32537a69dbf693697577816ee06450fc4ec2a6fb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-11-03T17:59:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T04:29:29.000Z", "max_issues_repo_path": "test/correctness/transform_pass.cpp", "max_issues_repo_name": "BoostGSoC17/static-map", "max_issues_repo_head_hexsha": "32537a69dbf693697577816ee06450fc4ec2a6fb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-07-06T21:32:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-18T14:13:47.000Z", "max_forks_repo_path": "test/correctness/transform_pass.cpp", "max_forks_repo_name": "BoostGSoC17/static-map", "max_forks_repo_head_hexsha": "32537a69dbf693697577816ee06450fc4ec2a6fb", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-07-20T21:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T19:11:41.000Z", "avg_line_length": 42.1153846154, "max_line_length": 80, "alphanum_fraction": 0.6248858447, "num_tokens": 981}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The stateless command allows to encapsulate processing logic for specic
intent's command. Allows to easy build response processing pipelines with
multiple stages of intent data processing. The stateless commands may be shared
among various intents.
"""
import random
import requests
import re
import pickle
import os
import json
import joblib
import pandas as pd
import numpy as np
class Command(object):
def __init__(self):
self.x=0
def do(self, bot, entity):
"""
Execute command's action for specified intent.
Arguments:
bot the chatbot
entity the parsed NLU entity
"""
pass
class DiseasePredictCommand(Command):
"""
The command to add item to the list
"""
def do(self, bot, entity):
#count = 0
#if entity in bot.shopping_list:
# print (entity)
# print(bot.shopping_list)
# count = bot.shopping_list[entity]
#print (bot)
#print (entity)
# t = "P"
print("entity pogo rai")
print(entity)
filename = 'C:\\Users\jayit\\Downloads\\RAPID\\MedBay-V1\\chatbot2\\disease_predict.sav'
feel = str(entity)
data = [feel]
cv = pickle.load(open("C:\\Users\jayit\\Downloads\\RAPID\\MedBay-V1\\chatbot2\\vectorizer.pickle", 'rb'))
loaded_model = pickle.load(open(filename, 'rb'))
vect=cv.transform(data).toarray()
p=loaded_model.predict(vect)
return 'You might be suffering from'+ (p[0]) +'.Please Visit A Doctor. We are here to Help You!'
# return t
class AskSymptomBackCommand(Command):
"""
The command to greet user
"""
def __init__(self):
"""
Default constructor which will create list of gretings to be picked
randomly to make our bot more human-like
"""
self.greetings = ["Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"At your service.Don't worry, you will be fine.Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"I can help you consult a doctor. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"I can help you finding the right doctor to help you feel better. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"Don't worry. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"Help me understand better. Don't worry. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough"]
def do(self, bot, entity):
s = random.choice(self.greetings)
print("Printing : "+s)
return s
class DiseasePredictFromSymptomCommand(Command):
"""
The command to add item to the list
"""
def do(self, bot, entity):
#count = 0
#if entity in bot.shopping_list:
# print (entity)
# print(bot.shopping_list)
# count = bot.shopping_list[entity]
#print (bot)
#print (entity)
# t = "P"
print("entity pogo rai")
print(entity)
cls = joblib.load('C:\\Users\jayit\\Downloads\\RAPID\\MedBay-V1\\chatbot2\\decision_tree.joblib') # classification model
cls1 = joblib.load('C:\\Users\jayit\\Downloads\\RAPID\\MedBay-V1\\chatbot2\\gradient_boost.joblib')
cls3 = joblib.load('C:\\Users\jayit\\Downloads\\RAPID\\MedBay-V1\\chatbot2\\random_forest.joblib')
symp_list = pd.read_csv('C:\\Users\jayit\\Downloads\\RAPID\\MedBay-V1\\chatbot2\\test_data.csv').columns[:-1]
d = np.zeros((len(symp_list)))
test_case = pd.DataFrame(d).transpose()
test_case.columns= symp_list
symptoms = entity # need to input exact coulmn names with comma separated value
symptoms = symptoms.split(',')
for symp in symptoms:
symp.replace(" ", "_")
if symp in symp_list: test_case.loc[0, [symp]]=1
disease = cls.predict(test_case) #predicted disease
disease1 = cls1.predict(test_case)
disease3 = cls3.predict(test_case)
# print(disease[0])
# print("disease")
dis_doc = {'Fungal infection':'Dermatologist',
'Allergy':'Allergist/Immunologists',
'GERD':'Gastroenterologist',
'Acne':'Dermatologist',
'hepatitis A':'Hepatologist',
'hepatitis B':'Hepatologist',
'hepatitis C':'Hepatologist',
'hepatitis D':'Hepatologist',
'hepatitis E':'Hepatologist',
'Chronic cholestasis':'Gastroenterologist',
'Drug Reaction':'Pharmacologist',
'Peptic ulcer disease':'Gastroenterologist',
'AIDS':'HIV Specialist',
'Diabetes':'Endocrinologist',
'Gastroenteritis':'Gastroenterologist',
'Bronchial Asthma':'Asthma Specialist',
'Hypertension':'Cardiologist',
'Migraine':'Neurologist',
'Cervical spondylosis':'Otolaryngologist',
'Paralysis (brain hemorrhage)':'Paralysis Doctor',
'Jaundice':'Gastroenterologist',
'Malaria':'General Physician',
'Chicken pox':'General Physician',
'Dengue':'Microbiologist',
'Typhoid':'General Physician',
'Alcoholic_hepatitis':'Gastroenterologist',
'Tuberculosis':'Pulmonologists',
'Common_Cold':'Otolaryngologist',
'Pneumonia':'Pediatric',
'Dimorphic_hemmorhoids(piles)':'Proctologist',
'Heart_attack':'Cardiologist',
'Varicose_veins':'Endocrinologist',
'Hypothyroidism':'Endocrinologist',
'Hyperthyroidism':'Endocrinologist',
'Hypoglycemia':'Endocrinologist',
'Osteoarthristis':'Orthopedist',
'Arthritis':'Orthopedist',
'(vertigo)_Paroymsal_Positional_Vertigo':'ENT Specialist',
'Urinary_tract_infection':'Urologist',
'Psoriasis':'Physician',
'Impetigo':'Expert Physician'}
print(bot.flag)
if(bot.flag==1):
doctor_predicted = ""
bot.flag = 0
for k, v in dis_doc.items():
if(k == disease[0]):
doctor_predicted=doctor_predicted+" "+v
elif(k == disease1[0]):
doctor_predicted=doctor_predicted+" "+v
elif(k == disease3[0]):
doctor_predicted=doctor_predicted+" "+v
return 'You might have the following diseases '+ str(disease[0])+" "+ str(disease1[0])+" "+ str(disease3[0])+'. Please Visit A Doctor. We are here to Help You! You can consult the following doctor:'+ doctor_predicted
elif(bot.flag==2):
bot.flag = 0
return "Drug Predicting Successfully"
# print(disease1[0])
# print("disease1")
# print(disease3[0])
# print("disease3")
return 'You might have the following diseases '+ str(disease[0])+ str(disease1[0])+ str(disease3[0])+'.Please Visit A Doctor. We are here to Help You!'
class DoctorPredictIntentCommand(Command):
"""
The command to greet user
"""
def __init__(self):
"""
Default constructor which will create list of gretings to be picked
randomly to make our bot more human-like
"""
self.greetings = ["Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"At your service.Don't worry, you will be fine.Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"I can help you consult a doctor. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"I can help you finding the right doctor to help you feel better. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"Don't worry. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"Help me understand better. Don't worry. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough"]
def do(self, bot, entity):
s = random.choice(self.greetings)
print("Printing : "+s)
bot.flag=1
return s
class DrugPredictIntentCommand(Command):
"""
The command to greet user
"""
def __init__(self):
"""
Default constructor which will create list of gretings to be picked
randomly to make our bot more human-like
"""
self.greetings = ["Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"At your service.Don't worry, you will be fine.Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"I can help you consult a doctor. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"I can help you finding the right doctor to help you feel better. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"Don't worry. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough",
"Help me understand better. Don't worry. Please write your symptoms separated by commas. I have an example for you->Headache,fever,cough"]
def do(self, bot, entity):
s = random.choice(self.greetings)
print("Printing : "+s)
bot.flag=2
return s
class GreetCommand(Command):
"""
The command to greet user
"""
def __init__(self):
"""
Default constructor which will create list of gretings to be picked
randomly to make our bot more human-like
"""
self.greetings = ["Hey!", "Hello!", "Hi there!", "How are you!"]
def do(self, bot, entity):
s = random.choice(self.greetings)
print("Printing : "+s)
return s
class WishBackCommand(Command):
"""
The command to greet user
"""
def __init__(self):
"""
Default constructor which will create list of gretings to be picked
randomly to make our bot more human-like
"""
self.greetings = ["Oh! Me Amazing.How may I help you?", "I am fine.How may I assist you?", "At your service.", "First time someone asked me.I am wonderful.How may I be of your assistance?"]
def do(self, bot, entity):
s = random.choice(self.greetings)
print("Printing : "+s)
return s
class AddItemCommand(Command):
"""
The command to add item to the list
"""
def do(self, bot, entity):
#count = 0
#if entity in bot.shopping_list:
# print (entity)
# print(bot.shopping_list)
# count = bot.shopping_list[entity]
#print (bot)
#print (entity)
if (bool(re.search(r'\d', entity))==True):
t=1
L=entity.split()
a=int(L[0])
if L[1] in bot.shopping_list:
bot.shopping_list[L[1]]+=a
else:
bot.shopping_list[L[1]]=a
return t
class RemoveItemCommand(Command):
"""
The command to add item to the list
"""
def do(self, bot, entity):
#count = 0
#if entity in bot.shopping_list:
# print (entity)
# print(bot.shopping_list)
# count = bot.shopping_list[entity]
#print (bot)
#print (entity)
t=1
if (bool(re.search(r'\d', entity))==True):
L=entity.split()
a=int(L[0])
if L[1] in bot.shopping_list:
temp=bot.shopping_list[L[1]]-a
if (temp<=0):
t=0
#print(t)
else:
bot.shopping_list[L[1]]=temp
else:
t=0
#print(z)
return t
class ShowItemsCommand(Command):
"""
The command to display shopping list
"""
def do(self, bot, entity):
if len(bot.shopping_list) == 0:
s = "Your shopping list is empty!"
# print(s)
return s
s = "Shopping list items:"
l = bot.shopping_list.items()
for k, v in bot.shopping_list.items():
t = "%s - quantity: %d" % (k, v)
print(t)
s = s + "\n" + t
# print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
# print(s)
# print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
return (s,l)
class ClearListCommand(Command):
"""
The command to clear shopping list
"""
def do(self, bot, entity):
bot.shopping_list.clear()
s = "Items removed from your list!"
print(s)
return s
class ShowStatsCommand(Command):
"""
The command to show shopping list statistics
"""
def do(self, bot, entity):
s = "shopping list is empty"
unique = len(bot.shopping_list)
if unique == 0:
print(s)
total = 0
for v in bot.shopping_list.values():
total += v
t = "# of unique items: %d, total # of items: %d" % (unique, total)
s = s + '\n' + t
print(t)
return s
class SuggestCorona(Command):
def do(self, bot, entity):
response = requests.get("https://disease.sh/v2/countries/"+entity+"?yesterday=false%22%20-H%20%22accept:%20application/json").json()
# location = bot.shopping_list[entity]
# print(entity)
s = entity+"\n"+"Country:"+response['country']+"\n"+"Total Cases:"+str(response['cases'])+"\n"+"Total Cases Today:"+str(response['todayCases'])
s = s + "Total Death Count:"+str(response['deaths']) +"\n"+ "Total Deaths Today:"+str(response['todayDeaths'])+"\n"+ "Total Recovered:"+str(response['recovered']) +"\n"
s = s + "Total Active Cases:"+str(response['active']) +"\n"+ "STAY SAFE AND STAY INSIDE ~ FROM TEAM $__TROUBLESHOOTERS__$ \n"
# print(s)
return s
|
{"hexsha": "b67a267db0006ae3854dad2151d6107c62ea9638", "size": 14997, "ext": "py", "lang": "Python", "max_stars_repo_path": "chatbot2/command.py", "max_stars_repo_name": "ricksaha2000/MedBay-V1", "max_stars_repo_head_hexsha": "ee8ead4c3583066c778dc76ed0749feb70f412c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chatbot2/command.py", "max_issues_repo_name": "ricksaha2000/MedBay-V1", "max_issues_repo_head_hexsha": "ee8ead4c3583066c778dc76ed0749feb70f412c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chatbot2/command.py", "max_forks_repo_name": "ricksaha2000/MedBay-V1", "max_forks_repo_head_hexsha": "ee8ead4c3583066c778dc76ed0749feb70f412c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8712121212, "max_line_length": 228, "alphanum_fraction": 0.5700473428, "include": true, "reason": "import numpy", "num_tokens": 3480}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on Wed Nov 22 18:34:21 2017
@author: amaya
'''
import pandas as pd
import numpy as np
import h5py
allacecols = [
'proton_density',
'proton_temp',
'He4toprotons',
'proton_speed',
'x_dot_RTN',
'y_dot_RTN',
'z_dot_RTN',
'x_dot_GSE',
'y_dot_GSE',
'z_dot_GSE',
'x_dot_GSM',
'y_dot_GSM',
'z_dot_GSM',
'nHe2',
'vHe2',
'vC5',
'vO6',
'vFe10',
'vthHe2',
'vthC5',
'vthO6',
'vthFe10',
'C6to5',
'O7to6',
'avqC',
'avqO',
'avqFe',
'FetoO',
'Br',
'Bt',
'Bn',
'Bgse_x',
'Bgse_y',
'Bgse_z',
'Bgsm_x',
'Bgsm_y',
'Bgsm_z',
'Bmag',
'Lambda',
'Delta',
'dBrms',
'sigma_B']
def acereaddata(acedir, ybeg, yend, cols):
for elem in ['year','day','hr']:
if elem not in cols: cols.append(elem)
raw = pd.DataFrame()
for i in range(ybeg, yend+1):
fname = acedir+'/multi_data_1hr_year'+str(i)+'.h5'
print("Reading: ", fname)
new=h5py.File(fname, 'r')
new=np.array(new['/VG_MULTI_data_1hr/MULTI_data_1hr']).byteswap().newbyteorder()
new=pd.DataFrame(new)
new['Datetime'] = pd.to_datetime(new['year'].apply('{:0>4}'.format)+' '
+ new['day'].apply('{:0>3}'.format)+' '
+ new['hr'].apply('{:0>2}'.format),
format='%Y %j %H', errors='ignore')
new = new.set_index('Datetime')
raw = pd.concat([raw, new])
cols.remove('year')
cols.remove('day')
cols.remove('hr')
print('Total entires read:', len(raw))
return raw[cols]
def acedata(acedir, cols, ybeg, yend):
# cols_needed = ['proton_speed','proton_density','proton_temp','O7to6','x_dot_GSM','y_dot_GSM','z_dot_GSM','Bgsm_x','Bgsm_y','Bgsm_z','Bmag']
cols_needed = ['proton_speed']
for elem in cols_needed:
if elem not in cols: cols.append(elem)
data = acereaddata(acedir, ybeg, yend, cols)
nulls = pd.DataFrame([])
nulls['Null values'] = pd.Series()
for i in cols:
if i.endswith('_qual') or i.endswith('SW_type'):
nulls.loc[i] = [-1]
else:
nulls.loc[i] = [-9999.9]
#Delete nulls
for c in cols:
data = data[data[c]!=nulls.loc[c][0]]
#Keep only good quality data
for e in data.columns:
if e.startswith('qf_'):
data = data[data[e]==0]
return data, nulls
def aceaddextra(data, nulls, xcols, window=5, center=False):
if 'Zhao_SW_type' in xcols:
'''
see Zhao, L., Zurbuchen, T. H., & Fisk, L. A. (2009).
Global distribution of the solar wind during solar cycle 23: ACE
observations. Geophysical research letters, 36(14).
1: Coronal hole
2: ICME
4: Non-coronal hole
'''
assert 'O7to6' in data.columns, 'Bmag needed in the data columns to calculate: Zhao_SW_type'
assert 'proton_speed' in data.columns, 'proton_density needed in the data columns to calculate: Zhao_SW_type'
data['Zhao_SW_type']=4
data.loc[data.O7to6<0.145,'Zhao_SW_type'] = 1
data.loc[data.O7to6>6.008*np.exp(-0.00578*data.proton_speed),'Zhao_SW_type'] = 2
k_b = 8.617333262145e-5
if 'Ma' in xcols:
assert 'Bmag' in data.columns, 'Bmag needed in the data columns to calculate: Ma'
assert 'proton_density' in data.columns, 'proton_density needed in the data columns to calculate: Ma'
Va = 21.82915036515064 * data['Bmag'] / np.sqrt(data['proton_density'])
data['Ma'] = data['proton_speed']/Va
if 'Va' in xcols:
assert 'Bmag' in data.columns, 'Bmag needed in the data columns to calculate: Ma'
assert 'proton_density' in data.columns, 'proton_density needed in the data columns to calculate: Ma'
Va = 21.82915036515064 * data['Bmag'] / np.sqrt(data['proton_density'])
data['Va'] = Va
if 'Sp' in xcols:
assert 'proton_temp' in data.columns, 'proton_temp needed in the data columns to calculate: Sp'
assert 'proton_density' in data.columns, 'proton_density needed in the data columns to calculate: Sp'
Sp=data['proton_temp']*k_b/data['proton_density']**(2./3.)
data['Sp'] = Sp
if 'Texp' in xcols:
assert 'proton_speed' in data.columns, 'proton_speed needed in the data columns to calculate: Texp'
Texp=np.power(data['proton_speed']/258.0, 3.113)
data['Texp'] = Texp
if 'Tratio' in xcols:
assert 'Texp' in data.columns, 'Texp needed in the extra data columns to calculate: Tratio'
Tratio=data['Texp']/(data['proton_temp']*k_b)
data['Tratio'] = Tratio
if 'Xu_SW_type' in xcols:
'''
see Xu, F., & Borovsky, J. E. (2015). A new four-plasma categorization scheme
for the solar wind. Journal of Geophysical Research: Space Physics, 120(1), 70–100.
https://doi.org/10.1002/2014JA020412
0: Streamer belt
1: Coronal hole
2: Ejecta
3: Sector reversal
'''
assert 'Va' in data.columns, 'Va needed in the extra columns to calculate: Xu_Zhao_SW_type'
assert 'Sp' in data.columns, 'Sp needed in the extra columns to calculate: Xu_Zhao_SW_type'
assert 'Tratio' in data.columns, 'Tratio needed in the extra columns to calculate: Xu_Zhao_SW_type'
ejecta= 0.277*np.log10(data['Sp'])+0.055*np.log10(data['Tratio'])+1.83 < np.log10(data['Va'])
chole =-0.525*np.log10(data['Tratio'])-0.676*np.log10(data['Va'])+1.74 < np.log10(data['Sp'])
srev =-0.125*np.log10(data['Tratio'])-0.658*np.log10(data['Va'])+1.04 > np.log10(data['Sp'])
data.loc[ejecta, 'Xu_SW_type'] = 2
data.loc[~ejecta&chole, 'Xu_SW_type'] = 1
data.loc[~ejecta&srev, 'Xu_SW_type'] = 3
data.loc[~ejecta&~chole&~srev, 'Xu_SW_type'] = 0
if (('sigmac' in xcols) or ('sigmar' in xcols)):
assert 'x_dot_GSM' in data.columns, 'x_dot_GSM needed in the data columns to calculate: sigmac and sigmar'
assert 'y_dot_GSM' in data.columns, 'y_dot_GSM needed in the data columns to calculate: sigmac and sigmar'
assert 'z_dot_GSM' in data.columns, 'z_dot_GSM needed in the data columns to calculate: sigmac and sigmar'
assert 'Bgsm_x' in data.columns, 'Bgsm_x needed in the data columns to calculate: sigmac and sigmar'
assert 'Bgsm_y' in data.columns, 'Bgsm_y needed in the data columns to calculate: sigmac and sigmar'
assert 'Bgsm_z' in data.columns, 'Bgsm_z needed in the data columns to calculate: sigmac and sigmar'
assert 'proton_density' in data.columns, 'proton_density needed in the data columns to calculate: sigmac and sigmar'
V = data[['x_dot_GSM','y_dot_GSM','z_dot_GSM']]
B = 21.82915036515064 * data[['Bgsm_x','Bgsm_y','Bgsm_z']].div(np.sqrt(data['proton_density']), axis=0)
v = V - V.rolling(window, center=center).mean()
b = B - B.rolling(window, center=center).mean()
zp = v + b.values
zn = v - b.values
v2 = (v * v).sum(axis=1)
b2 = (b * b).sum(axis=1)
zp2 = (zp * zp).sum(axis=1)
zn2 = (zn * zn).sum(axis=1)
bdotv = (b * v.values).sum(axis=1).rolling(window, center=center).mean()
bnorm = (b2 + v2.values).rolling(window, center=center).mean()
zdotz = (zp * zn.values).sum(axis=1).rolling(window, center=center).mean()
znorm = (zp2 + zn2.values).rolling(window, center=center).mean()
sigc = 2 * bdotv / bnorm
sigr = 2 * zdotz / znorm
if 'sigmac' in xcols : data['sigmac'] = sigc
if 'sigmar' in xcols : data['sigmar'] = sigr
for end in ['min','max','mean','std','var']:
func = getattr(pd.core.window.Rolling, end)
for c in xcols:
if c.endswith(end):
e = 4 if c.startswith('log_') else 0
var = c[e:-len(end)-1]
varfunc = func(data[var].rolling(window, center=center))
data[c] = varfunc
for end in ['range']:
fmax = pd.core.window.Rolling.max
fmin = pd.core.window.Rolling.min
for c in xcols:
if c.endswith(end):
e = 4 if c.startswith('log_') else 0
var = c[e:-len(end)-1]
vmax = fmax(data[var].rolling(window, center=center))
vmin = fmin(data[var].rolling(window, center=center))
data[c] = vmax - vmin
for end in ['acor']:
func = lambda x: pd.Series(x).autocorr()
for c in xcols:
if c.endswith(end):
e = 4 if c.startswith('log_') else 0
var = c[e:-len(end)-1]
data[c] = data[var].rolling(window, center=center).apply(func, raw=False)
for c in xcols:
if c.startswith('log'):
var = c[4:]
data[c] = np.log(data[var])
data = data.dropna(axis=0)
#Appending new nulls using the mutable argument reference
for i in xcols:
if i.endswith('SW_type'):
nulls.loc[i] = -1
else:
nulls.loc[i] = -9999.9
return data
if __name__ == "__main__":
import matplotlib.pyplot as plt
cols = allacecols
acedir = '/home/amaya/Workdir/MachineLearning/Data/ACE'
ybeg = 1998
yend = 2011
data, nulls = acedata(acedir, cols, ybeg, yend)
xcols = ['log_O7to6',
'log_proton_speed',
'log_proton_density',
'sigmac',
'sigmar',
'log_FetoO',
'log_avqFe',
'log_Bmag',
'log_C6to5',
'log_proton_temp',
'proton_density',
'Ma',
'proton_speed_range',
'proton_density_range',
'proton_temp_range',
'Bgsm_x_range',
'Bgsm_y_range',
'Bgsm_z_range',
'Bmag_range',
'Bmag_acor',
'Bmag_mean',
'Bmag_std',
'log_Ma',
'log_Lambda',
'log_Delta',
'log_He4toprotons',
'log_proton_speed_range',
'log_proton_density_range',
'log_proton_temp_range',
'log_Bgsm_x_range',
'log_Bgsm_y_range',
'log_Bgsm_z_range',
'log_Bmag_range',
'log_Bmag_acor',
'log_Bmag_mean',
'log_Bmag_std',]
data = aceaddextra(data, nulls, xcols=xcols, window=7, center=False)
tdata = (data - data.min(axis=0))/(data.max(axis=0) - data.min(axis=0))
pcols = ['log_O7to6',
'log_proton_speed',
'log_proton_density',
'sigmac',
'sigmar',
'log_FetoO',
'log_avqFe',
'log_Bmag',
'log_C6to5',
'proton_temp',
'log_proton_temp',
'proton_density',
'He4toprotons',
'Ma',
'Lambda',
'Delta',
'proton_speed_range',
'proton_density_range',
'proton_temp_range',
'Bgsm_x_range',
'Bgsm_y_range',
'Bgsm_z_range',
'Bmag_range',
'Bmag_acor',
'Bmag_mean',
'Bmag_std',
'log_Ma',
'log_Lambda',
'log_Delta',
'log_He4toprotons',
'log_proton_speed_range',
'log_proton_density_range',
'log_proton_temp_range',
'log_Bgsm_x_range',
'log_Bgsm_y_range',
'log_Bgsm_z_range',
'log_Bmag_range',
'log_Bmag_acor',
'log_Bmag_mean',
'log_Bmag_std',]
tdata = np.array([tdata[c].values for c in pcols]).T
plt.violinplot(tdata, showextrema=False)
plt.boxplot(tdata, notch=True, showfliers=False, showmeans=True)
# plt.xticks(range(1,len(pcols)+1), labels=pcols)
plt.xticks(range(1,len(pcols)+1))
|
{"hexsha": "f47c944a59304afa3a2aff6e72b829b9304812be", "size": 12709, "ext": "py", "lang": "Python", "max_stars_repo_path": "acedata.py", "max_stars_repo_name": "murci3lag0/swinsom", "max_stars_repo_head_hexsha": "586e81e9b2e6829c0d56127a2209891675e29fcd", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-27T07:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T20:06:24.000Z", "max_issues_repo_path": "acedata.py", "max_issues_repo_name": "murci3lag0/swinsom", "max_issues_repo_head_hexsha": "586e81e9b2e6829c0d56127a2209891675e29fcd", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-04-26T10:31:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-29T12:33:59.000Z", "max_forks_repo_path": "acedata.py", "max_forks_repo_name": "murci3lag0/swinsom", "max_forks_repo_head_hexsha": "586e81e9b2e6829c0d56127a2209891675e29fcd", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-27T07:46:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T13:20:51.000Z", "avg_line_length": 35.4011142061, "max_line_length": 145, "alphanum_fraction": 0.5330867889, "include": true, "reason": "import numpy", "num_tokens": 3558}
|
from cvxopt import matrix, solvers
import numpy as npy
import math
class SVM:
def __init__(self, data):
self.data = data
def constructQPMatrices(self):
N = len(self.data)
P = npy.zeros((N, N))
for n in range(N):
dn = self.data[n]
for m in range(N):
dm = self.data[m]
yy = dn.val * dm.val
xTx = self.kernel(dn.x, dm.x, dn.y, dm.y)
P[n, m] = yy * xTx
self.P = matrix(P)
q = npy.ones(N)
q = -1 * q
self.q = matrix(q)
G = npy.ones(N)
G = -1 * G
G = npy.diag(G)
self.G = matrix(G)
h = npy.zeros(N)
self.h = matrix(h)
A = []
for d in self.data:
A.append([float(d.val)])
self.A = matrix(A, (1, N))
b = 0.
self.b = matrix(b)
def kernel(cls, xn, xm, yn, ym):
return xn * xm + yn * ym
def solve(self):
sol = solvers.qp(self.P, self.q, self.G, self.h, self.A, self.b)
self.alphas = sol['x']
print(sol['x'])
def calcW(self):
N = len(self.data)
w = [0, 0]
sx = []
sy = []
# get w based on sum(a * x * y)
for i in range(N):
a = self.alphas[i]
if a > 0: # only positive alphas are support vectors
y = self.data[i].val
ayx = [a * y * self.data[i].x,
a * y * self.data[i].y]
w = [sum(aa) for aa in zip(w, ayx)]
if a > 1: #others are sufficiently close to 0 to not count as supports
sx.append(self.data[i].x)
sy.append(self.data[i].y)
self.supportx = sx
self.supporty = sy
self.w = w
def calcB(self):
N = len(self.data)
poswTx = []
negwTx = []
for i in range(N):
a = self.alphas[i]
d = self.data[i]
if d.val > 0:
poswTx.append(self.w[0] * d.x + self.w[1] * d.y)
else:
negwTx.append(self.w[0] * d.x + self.w[1] * d.y)
minPos = min(poswTx)
maxNeg = max(negwTx)
self.b = -.5 * (minPos + maxNeg)
def getWAndb(self):
self.calcW()
self.calcB()
return self.w,self.b
def train(self):
self.constructQPMatrices()
self.solve()
return self.getWAndb()
def predict(self, x, y):
result = self.w[0] * x + self.w[1] * y + self.b
return self.sign(result)
def test(self, data):
correct = 0
for d in data:
prediction = self.predict(d.x, d.y)
if prediction == d.val:
correct = correct + 1
return float(correct) / len(data)
def sign(self, v):
if v >= 0: return 1
else: return -1
class RadialKernelSVM(SVM):
def kernel(cls, xn, xm, yn, ym):
GAMMA = .5
xdiff = xn - xm
ydiff = yn - ym
mag = xdiff**2 + ydiff**2
return math.exp(-1 * GAMMA * mag)
def predict(self, x, y):
tosum = []
for i in range(len(self.data)):
d = self.data[i]
a = self.alphas[i]
result = a * d.val * self.kernel(d.x, x, d.y, y)
tosum.append(result)
return self.sign(sum(tosum))
|
{"hexsha": "97312013d58dd279454ea3a5f95974e5c3320bd7", "size": 3369, "ext": "py", "lang": "Python", "max_stars_repo_path": "hw7/svm.py", "max_stars_repo_name": "hakuliu/inf552", "max_stars_repo_head_hexsha": "3fc1fbec0ea1692742b76d4fe8bd0f6946eba4f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-24T00:29:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-24T00:29:53.000Z", "max_issues_repo_path": "hw7/svm.py", "max_issues_repo_name": "hakuliu/inf552", "max_issues_repo_head_hexsha": "3fc1fbec0ea1692742b76d4fe8bd0f6946eba4f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw7/svm.py", "max_forks_repo_name": "hakuliu/inf552", "max_forks_repo_head_hexsha": "3fc1fbec0ea1692742b76d4fe8bd0f6946eba4f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9153846154, "max_line_length": 82, "alphanum_fraction": 0.4538438706, "include": true, "reason": "import numpy", "num_tokens": 956}
|
import argparse
import gym
import numpy as np
import os
# import tensorflow as tf
import time
import pickle
import json
from argparse import Namespace
from MAA2C import MAA2C
from common.utils import agg_double_list
import sys
# import matplotlib.pyplot as plt
from env_utils import make_env
MAX_EPISODES = 2500
EPISODES_BEFORE_TRAIN = 1
EVAL_EPISODES = 10
EVAL_INTERVAL = 20
# roll out n steps
ROLL_OUT_N_STEPS = 25
# only remember the latest ROLL_OUT_N_STEPS
MEMORY_CAPACITY = ROLL_OUT_N_STEPS
# only use the latest ROLL_OUT_N_STEPS for training A2C
BATCH_SIZE = ROLL_OUT_N_STEPS
REWARD_DISCOUNTED_GAMMA = 0.99
ENTROPY_REG = 0.01
#
DONE_PENALTY = -10.
CRITIC_LOSS = "mse"
MAX_GRAD_NORM = None
EPSILON_START = 0.99
EPSILON_END = 0.05
EPSILON_DECAY = 500
RANDOM_SEED = 2018
env_params = {}
with open('env_params.json') as params_file:
env_params = json.load(params_file)
print(env_params)
def run():
# Create environment
env, state_dim, action_dim, max_steps = make_env(env_params=Namespace(**env_params))
env_eval, state_dim, action_dim, max_steps = make_env(env_params=Namespace(**env_params))
# Create agent trainers
# obs_shape_n = [env.observation_space[i].shape for i in range(env.n)]
# num_adversaries = min(env.n, arglist.num_adversaries)
obs_shape_n = state_dim
act_shape_n = action_dim
maa2c = MAA2C(env, env_params['n_agents'], obs_shape_n, act_shape_n, max_steps = max_steps)
episodes =[]
eval_rewards =[]
while maa2c.n_episodes < MAX_EPISODES:
# print(maa2c.env_state)
maa2c.interact()
# if maa2c.n_episodes >= EPISODES_BEFORE_TRAIN:
# maa2c.train()
maa2c.train()
if maa2c.episode_done and ((maa2c.n_episodes)%EVAL_INTERVAL == 0):
rewards, _ = maa2c.evaluation(env_eval, EVAL_EPISODES)
rewards_mu, rewards_std = agg_double_list(rewards)
print("Episode %d, Average Reward %.2f, STD %.2f" % (maa2c.n_episodes, rewards_mu, rewards_std))
episodes.append(maa2c.n_episodes)
eval_rewards.append(rewards_mu)
if __name__ == '__main__':
run()
|
{"hexsha": "bb0e4a5eae5bca8d490b37fd768c83f2de06f353", "size": 2137, "ext": "py", "lang": "Python", "max_stars_repo_path": "notebooks/maa2c_final/run_maa2c.py", "max_stars_repo_name": "nyu-ds-2019/flatland-reinforcement-learning", "max_stars_repo_head_hexsha": "3d7b25cac24b02e73769767019815a992ddab00f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-22T08:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:13:36.000Z", "max_issues_repo_path": "notebooks/maa2c_final/run_maa2c.py", "max_issues_repo_name": "nyu-ds-2019/flatland-reinforcement-learning", "max_issues_repo_head_hexsha": "3d7b25cac24b02e73769767019815a992ddab00f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/maa2c_final/run_maa2c.py", "max_forks_repo_name": "nyu-ds-2019/flatland-reinforcement-learning", "max_forks_repo_head_hexsha": "3d7b25cac24b02e73769767019815a992ddab00f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-04-19T15:34:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T09:06:13.000Z", "avg_line_length": 25.4404761905, "max_line_length": 108, "alphanum_fraction": 0.7187646233, "include": true, "reason": "import numpy", "num_tokens": 621}
|
import cgnsutilities as cu
import numpy as np
# BC type dictionary
BCdic = cu.BC
BClist = list(BCdic.keys())
BCval = list(BCdic.values())
print(BCdic)
# Read a grid
grid = cu.readGrid('./inputFiles/grid_absper_vis_latest_output.cgns')
#grid = cu.readGrid('./inputFiles/naca0012.cgns')
# Print some info
grid.printInfo()
grid.printBlockInfo()
nblk = len(grid.blocks)
blk1 = grid.blocks[0]
nbc = len(blk1.bocos)
print(' =========== BCs ===============')
# bc infos
for i,boco in enumerate(blk1.bocos):
print(' =================')
print('BC #'+str(i)+': ')
print('Name: ',boco.name.decode('utf8').strip())
print('Type: ',boco.type)
print(BClist[BCval.index(boco.type)])
print('Family: ', boco.family.decode('utf8').strip())
ndset = len(boco.dataSets)
print('Ndatasets: ', ndset)
# print('PtRange:',boco.ptRange)
if ndset >= 1:
dset = boco.dataSets[0]
print('Dname: ',dset.name.decode('utf8').strip())
print('Dtype: ',dset.type)
nddirch = len(dset.dirichletArrays)
ndneuma = len(dset.neumannArrays)
print('nDirichlet: ',nddirch)
print('nNeumann: ',ndneuma)
if nddirch>=1:
print(' +++ Data Set 1 +++')
dirchdata = dset.dirichletArrays[0]
dataname = dirchdata.name.decode('utf8').strip()
print('ArrayName: ', dirchdata.name.decode('utf8').strip())
if dataname == 'Pressure':
dirchdata.dataArr =np.array([101325])
print('ArrayNDim: ', dirchdata.nDimensions)
print('ArrayDtype: ', dirchdata.dataType)
print('ArrayDDim: ', dirchdata.dataDimensions)
print('Array: ', dirchdata.dataArr)
print('NP arrary shp', dirchdata.dataArr.shape)
print(' =========== B2B ===============')
nb2b = len(blk1.B2Bs)
print('# Block to Block connection: ', nb2b)
for b2b in blk1.B2Bs:
print('name: ',b2b.name.decode('utf8').strip())
print('donor name:', b2b.donorName.decode('utf8').strip())
# print('range:', b2b.ptRange)
# print('donor range: ', b2b.donorRange)
print('transform: ', b2b.transform)
print('ifperiodic: ', b2b.periodic)
if b2b.periodic:
print('rotCenter', b2b.rotCenter)
print('rotAngles', b2b.rotAngles)
print('translation', b2b.trans)
grid.writeToCGNS('./inputFiles/grid_absper_vis_latest_output.cgns')
|
{"hexsha": "cf4c94a29ff2f7d9af2a0ed187620e4d6c10c51b", "size": 2314, "ext": "py", "lang": "Python", "max_stars_repo_path": "examples/cgns_explore.py", "max_stars_repo_name": "tianboxi/cgnsutilities", "max_stars_repo_head_hexsha": "789ddfbbada4e9eb6f96d85af731e6e71cb17305", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/cgns_explore.py", "max_issues_repo_name": "tianboxi/cgnsutilities", "max_issues_repo_head_hexsha": "789ddfbbada4e9eb6f96d85af731e6e71cb17305", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/cgns_explore.py", "max_forks_repo_name": "tianboxi/cgnsutilities", "max_forks_repo_head_hexsha": "789ddfbbada4e9eb6f96d85af731e6e71cb17305", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5915492958, "max_line_length": 69, "alphanum_fraction": 0.624891962, "include": true, "reason": "import numpy", "num_tokens": 700}
|
[STATEMENT]
lemma wlconf_ext_list [rule_format (no_asm)]: "
\<And>X. \<lbrakk>G,s\<turnstile>l[\<sim>\<Colon>\<preceq>]L\<rbrakk> \<Longrightarrow>
\<forall>vs Ts. distinct vns \<longrightarrow> length Ts = length vns
\<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> G,s\<turnstile>l(vns[\<mapsto>]vs)[\<sim>\<Colon>\<preceq>]L(vns[\<mapsto>]Ts)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>X. G,s\<turnstile>l[\<sim>\<Colon>\<preceq>]L \<Longrightarrow> \<forall>vs Ts. distinct vns \<longrightarrow> length Ts = length vns \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> G,s\<turnstile>l(vns [\<mapsto>] vs)[\<sim>\<Colon>\<preceq>]L(vns [\<mapsto>] Ts)
[PROOF STEP]
apply (unfold wlconf_def)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>X. \<forall>n. ! T:L n: ! v:l n: G,s\<turnstile>v\<Colon>\<preceq>T \<Longrightarrow> \<forall>vs Ts. distinct vns \<longrightarrow> length Ts = length vns \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L(vns [\<mapsto>] Ts)) n: ! v:(l(vns [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T)
[PROOF STEP]
apply (induct_tac "vns")
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>X. \<forall>n. ! T:L n: ! v:l n: G,s\<turnstile>v\<Colon>\<preceq>T \<Longrightarrow> \<forall>vs Ts. distinct [] \<longrightarrow> length Ts = length [] \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L([] [\<mapsto>] Ts)) n: ! v:(l([] [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T)
2. \<And>X a list. \<lbrakk>\<forall>n. ! T:L n: ! v:l n: G,s\<turnstile>v\<Colon>\<preceq>T; \<forall>vs Ts. distinct list \<longrightarrow> length Ts = length list \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L(list [\<mapsto>] Ts)) n: ! v:(l(list [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T)\<rbrakk> \<Longrightarrow> \<forall>vs Ts. distinct (a # list) \<longrightarrow> length Ts = length (a # list) \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L(a # list [\<mapsto>] Ts)) n: ! v:(l(a # list [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T)
[PROOF STEP]
apply clarsimp
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>X a list. \<lbrakk>\<forall>n. ! T:L n: ! v:l n: G,s\<turnstile>v\<Colon>\<preceq>T; \<forall>vs Ts. distinct list \<longrightarrow> length Ts = length list \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L(list [\<mapsto>] Ts)) n: ! v:(l(list [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T)\<rbrakk> \<Longrightarrow> \<forall>vs Ts. distinct (a # list) \<longrightarrow> length Ts = length (a # list) \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L(a # list [\<mapsto>] Ts)) n: ! v:(l(a # list [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T)
[PROOF STEP]
apply clarify
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>X a list vs Ts n T v. \<lbrakk>\<forall>n. ! T:L n: ! v:l n: G,s\<turnstile>v\<Colon>\<preceq>T; \<forall>vs Ts. distinct list \<longrightarrow> length Ts = length list \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L(list [\<mapsto>] Ts)) n: ! v:(l(list [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T); distinct (a # list); length Ts = length (a # list); list_all2 (conf G s) vs Ts; (L(a # list [\<mapsto>] Ts)) n = Some T; (l(a # list [\<mapsto>] vs)) n = Some v\<rbrakk> \<Longrightarrow> G,s\<turnstile>v\<Colon>\<preceq>T
[PROOF STEP]
apply (frule list_all2_lengthD)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>X a list vs Ts n T v. \<lbrakk>\<forall>n. ! T:L n: ! v:l n: G,s\<turnstile>v\<Colon>\<preceq>T; \<forall>vs Ts. distinct list \<longrightarrow> length Ts = length list \<longrightarrow> list_all2 (conf G s) vs Ts \<longrightarrow> (\<forall>n. ! T:(L(list [\<mapsto>] Ts)) n: ! v:(l(list [\<mapsto>] vs)) n: G,s\<turnstile>v\<Colon>\<preceq>T); distinct (a # list); length Ts = length (a # list); list_all2 (conf G s) vs Ts; (L(a # list [\<mapsto>] Ts)) n = Some T; (l(a # list [\<mapsto>] vs)) n = Some v; length vs = length Ts\<rbrakk> \<Longrightarrow> G,s\<turnstile>v\<Colon>\<preceq>T
[PROOF STEP]
apply clarsimp
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
|
{"llama_tokens": 1738, "file": null, "length": 7}
|
import os
import numpy as np
from lib.utils.utils import unique
from visualization.utils_name_generation import generate_image_name
import cv2
colormap = {
0: (128, 128, 128), # Sky
1: (128, 0, 0), # Building
2: (128, 64, 128), # Road
3: (0, 0, 192), # Sidewalk
4: (64, 64, 128), # Fence
5: (128, 128, 0), # Vegetation
6: (192, 192, 128), # Pole
7: (64, 0, 128), # Car
8: (192, 128, 128), # Sign
9: (64, 64, 0), # Pedestrian
10: (0, 128, 192), # Cyclist
11: (0, 0, 0) # Void
}
conversion_list = {
1: 1, #wall
2: 1, #building;edifice
3: 0, #sky
4: 2, #floor;flooring
5: 5, #tree
6: 1, #ceiling
7: 2, #road;route
8: 11, #bed
9: 1, #windowpane;window
10: 5, #grass
11: 11, #cabinet
12: 3, #sidewalk;pavement
13: 9, #person;individual;someone;somebody;mortal;soul
14: 2, #earth;ground
15: 1, #door;double;door
16: 11, #table
17: 11, #mountain;mount
18: 5, #plant;flora;plant;life
19: 11, #curtain;drape;drapery;mantle;pall
20: 11, #chair
21: 7, #car;auto;automobile;machine;motorcar
22: 11, #water
23: 11, #painting;picture
24: 11, #sofa;couch;lounge
25: 11, #shelf
26: 1, #house
27: 11, #sea
28: 11, #mirror
29: 11, #rug;carpet;carpeting
30: 2, #field
31: 11, #armchair
32: 11, #seat
33: 4, #fence;fencing
34: 11, #desk
35: 11, #rock;stone
36: 11, #wardrobe;closet;press
37: 6, #lamp
38: 11, #bathtub;bathing;tub;bath;tub
39: 4, #railing;rail
40: 11, #,cushion
41: 11, #base;pedestal;stand
42: 11, #box
43: 6, #column;pillar
44: 8, #signboard;sign
45: 11, #chest;of;drawers;chest;bureau;dresser
46: 11, #counter
47: 2, #sand
48: 11, #sink
49: 1, #skyscraper
50: 11, #fireplace;hearth;open;fireplace
51: 11, #refrigerator;icebox
52: 11, #grandstand;covered;stand
53: 2, #,path
54: 4, #stairs;steps
55: 2, #runway
56: 1, #case;display;case;showcase;vitrine
57: 11, #pool;table;billiard;table;snooker;table
58: 11, #pillow
59: 11, #screen;door;screen
60: 4, #stairway;staircase
61: 11, #river
62: 11, #,bridge;span
63: 11, #bookcase
64: 11, #blind;screen
65: 11, #coffee;table;cocktail;table
66: 11, #toilet;can;commode;crapper;pot;potty;stool;throne
67: 11, #flower
68: 11, #book
69: 11, #hill
70: 11, #bench
71: 11, #countertop
72: 11, #stove;kitchen;stove;range;kitchen;range;cooking;stove
73: 11, #palm;palm;tree
74: 11, #kitchen;island
75: 11, #computer;computing;machine;computing;device;data;processor;electronic;computer;information;processing;system
76: 11, #swivel;chair
77: 11, #boat
78: 11, #bar
79: 11, #arcade;machine
80: 11, #hovel;hut;hutch;shack;shanty
81: 7, #bus;autobus;coach;charabanc;double-decker;jitney;motorbus;motorcoach;omnibus;passenger;vehicle
82: 11, #towel
83: 6, #light;light;source
84: 7, #truck;motortruck
85: 1, #tower
86: 11, #chandelier;pendant;pendent
87: 11, #awning;sunshade;sunblind
88: 6, #streetlight;street;lamp
89: 11, #booth;cubicle;stall;kiosk
90: 11, #television;television;receiver;television;set;tv;tv;set;idiot;box;boob;tube;telly;goggle;box
91: 11, #airplane;aeroplane;plane
92: 11, #dirt;track
93: 11, #apparel;wearing;apparel;dress;clothes
94: 6, #pole
95: 3, #land;ground;soil
96: 11, #bannister;banister;balustrade;balusters;handrail
97: 11, #escalator;moving;staircase;moving;stairway
98: 11, #ottoman;pouf;pouffe;puff;hassock
99: 11, #bottle
100: 11, #buffet;counter;sideboard
101: 11, #poster;posting;placard;notice;bill;card
102: 11, #stage
103: 7, #van
104: 11, #ship
105: 11, #fountain
106: 11, #conveyer;belt;conveyor;belt;conveyer;conveyor;transporter
107: 11, #canopy
108: 11, #washer;automatic;washer;washing;machine
109: 11, #plaything;toy
110: 11, #swimming;pool;swimming;bath;natatorium
111: 11, #0,stool
112: 11, #barrel;cask
113: 11, #basket;handbasket
114: 11, #waterfall;falls
115: 11, #tent;collapsible;shelter
116: 11, #bag
117: 10, #minibike;motorbike
118: 11, #cradle
119: 11, #oven
120: 11, #ball
121: 11, #food;solid;food
122: 11, #step;stair
123: 7, #tank;storage;tank
124: 11, #trade;name;brand;name;brand;marque
125: 11, #microwave;microwave;oven
126: 11, #pot;flowerpot
127: 11, #animal;animate;being;beast;brute;creature;fauna
128: 10, #bicycle;bike;wheel;cycle
129: 11, #lake
130: 11, #dishwasher;dish;washer;dishwashing;machine
131: 11, #screen;silver;screen;projection;screen
132: 11, #blanket;cover
133: 11, #sculpture
134: 11, #hood;exhaust;hood
135: 11, #sconce
136: 11, #vase
137: 8, #traffic;light;traffic;signal;stoplight
138: 11, #tray
139: 11, #ashcan;trash;can;garbage;can;wastebin;ash;bin;ash-bin;ashbin;dustbin;trash;barrel;trash;bin
140: 11, #fan
141: 11, #pier;wharf;wharfage;dock
142: 11, #crt;screen
143: 11, #plate
144: 11, #monitor;monitoring;device
145: 11, #bulletin;board;notice;board
146: 11, #shower
147: 11, #radiator
148: 11, #glass;drinking;glass
149: 11, #clock
150: 11, #flag
}
def convert_labels_to_kitti(predictions, mode='BGR'):
predictions = predictions.astype('int')
labelmap_kitti = np.zeros(predictions.shape, dtype=np.uint8)
labelmap_rgb = np.zeros((predictions.shape[0], predictions.shape[1], 3),
dtype=np.uint8)
for label in unique(predictions):
if label < 0:
continue
label_kitti = conversion_list[label + 1]
labelmap_rgb += (predictions == label)[:, :, np.newaxis] * \
np.tile(np.uint8(colormap[label_kitti]),
(predictions.shape[0], predictions.shape[1], 1))
labelmap_kitti[predictions == label] = label_kitti
if mode == 'BGR':
return labelmap_kitti, labelmap_rgb[:, :, ::-1]
else:
return labelmap_kitti, labelmap_rgb
def visualize_result(data, preds, args):
(img, info) = data
kitti_pred, pred_color = convert_labels_to_kitti(preds)
# aggregate images and save
im_vis = pred_color.astype(np.uint8)
img_name_rgb, img_name = generate_image_name(info)
a = os.path.join(args.output_path, img_name_rgb)
print(a)
cv2.imwrite(os.path.join(args.output_path, img_name_rgb), im_vis)
# aggregate images and save
im_vis = kitti_pred.astype(np.uint8)
cv2.imwrite(os.path.join(args.output_path, img_name), im_vis)
|
{"hexsha": "f77edd79ddc078e2b9a97d245640262d3e0f31c8", "size": 6842, "ext": "py", "lang": "Python", "max_stars_repo_path": "visualization/kitti_visualizer.py", "max_stars_repo_name": "luca-morreale/semantic-segmentation-pytorch", "max_stars_repo_head_hexsha": "d823fb4115a7ef5c8d47b3e5995a498bbcd9a9b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "visualization/kitti_visualizer.py", "max_issues_repo_name": "luca-morreale/semantic-segmentation-pytorch", "max_issues_repo_head_hexsha": "d823fb4115a7ef5c8d47b3e5995a498bbcd9a9b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "visualization/kitti_visualizer.py", "max_forks_repo_name": "luca-morreale/semantic-segmentation-pytorch", "max_forks_repo_head_hexsha": "d823fb4115a7ef5c8d47b3e5995a498bbcd9a9b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.823255814, "max_line_length": 122, "alphanum_fraction": 0.6151710026, "include": true, "reason": "import numpy", "num_tokens": 2889}
|
[STATEMENT]
lemma inv_in_frac:
assumes "a \<in> carrier Q\<^sub>p"
assumes "a \<noteq>\<zero>"
shows "inv\<^bsub>Q\<^sub>p\<^esub> a \<in> carrier Q\<^sub>p"
"inv\<^bsub>Q\<^sub>p\<^esub> a \<noteq>\<zero>"
"inv\<^bsub>Q\<^sub>p\<^esub> a \<in> nonzero Q\<^sub>p"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. inv a \<in> carrier Q\<^sub>p &&& inv a \<noteq> \<zero> &&& inv a \<in> nonzero Q\<^sub>p
[PROOF STEP]
apply (simp add: assms(1) assms(2) field_inv(3))
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. inv a \<noteq> \<zero>
2. inv a \<in> nonzero Q\<^sub>p
[PROOF STEP]
using assms(1) assms(2) field_inv(1)
[PROOF STATE]
proof (prove)
using this:
a \<in> carrier Q\<^sub>p
a \<noteq> \<zero>
\<lbrakk>?a \<in> carrier Q\<^sub>p; ?a \<noteq> \<zero>\<rbrakk> \<Longrightarrow> inv ?a \<otimes> ?a = \<one>
goal (2 subgoals):
1. inv a \<noteq> \<zero>
2. inv a \<in> nonzero Q\<^sub>p
[PROOF STEP]
apply fastforce
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. inv a \<in> nonzero Q\<^sub>p
[PROOF STEP]
using Qp.not_nonzero_memE assms(1) assms(2) nonzero_inverse_Qp
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?a \<notin> nonzero Q\<^sub>p; ?a \<in> carrier Q\<^sub>p\<rbrakk> \<Longrightarrow> ?a = \<zero>
a \<in> carrier Q\<^sub>p
a \<noteq> \<zero>
?u \<in> nonzero Q\<^sub>p \<Longrightarrow> inv ?u \<in> nonzero Q\<^sub>p
goal (1 subgoal):
1. inv a \<in> nonzero Q\<^sub>p
[PROOF STEP]
by blast
|
{"llama_tokens": 646, "file": "Padic_Field_Padic_Fields", "length": 5}
|
theory Automation
imports Graph_Theory.Graph_Theory
begin
section \<open>Automation\<close>
text \<open>
The purpose of this section is to collect use cases for proof automation in the graph library.
\<close>
subsection \<open>Noschinski\<close>
lemma (in wf_digraph) "u \<rightarrow>\<^sup>+ v \<Longrightarrow> v \<rightarrow>\<^sup>* y \<Longrightarrow> y \<rightarrow> x \<Longrightarrow> u \<rightarrow>\<^sup>+ x"
using reachable1_reachable_trans by blast
lemma (in wf_digraph)
assumes "awalk u p v" "v \<rightarrow>\<^sup>* y" "y \<rightarrow> x"
shows "u \<rightarrow>\<^sup>* x" "\<exists>q. awalk u q x"
using assms reachable_adj_trans reachable_awalk reachable_trans
apply -
apply metis+
done
lemma (in wf_digraph)
assumes "apath u p1 v" "v \<rightarrow> y" "trail y p2 x"
shows "\<exists>e. awalk u (p1@e#p2) x"
using assms
using reachable_awalk unfolding trail_def apath_def apply(auto) sorry
lemma (in wf_digraph)
assumes "v \<rightarrow>\<^sup>* y" "y \<rightarrow> x" "x \<rightarrow>\<^sup>+ v"
shows "\<exists>c. cycle c"
using assms unfolding cycle_def sorry
lemma (in wf_digraph)
assumes "awalk u p v" "v \<rightarrow> x" "awalk x (p1#ps1) u"
shows "\<exists>c. cycle c"
using assms unfolding cycle_def sorry
lemma (in wf_digraph)
assumes "v \<rightarrow>\<^sup>* x" "awalk x p y"
shows "\<mu> w v y < \<infinity>"
sorry
text \<open>
In general, the automation does not seem to work so well if you mix reachability and awalks.
\<close>
end
|
{"author": "wimmers", "repo": "archive-of-graph-formalizations", "sha": "cf49dd3379174cca7f3f1de16214e1c66238841e", "save_path": "github-repos/isabelle/wimmers-archive-of-graph-formalizations", "path": "github-repos/isabelle/wimmers-archive-of-graph-formalizations/archive-of-graph-formalizations-cf49dd3379174cca7f3f1de16214e1c66238841e/Automation.thy"}
|
# Copyright (c) Anyi Rao. All rights reserved.
import argparse
from datetime import datetime
import numpy as np
import json
import os
import os.path as osp
import pickle
import pdb
import shutil
from tqdm import tqdm
|
{"hexsha": "55fb65b0fac8dd505abb934b0ac0232832f1b60a", "size": 217, "ext": "py", "lang": "Python", "max_stars_repo_path": "raykit/package.py", "max_stars_repo_name": "AnyiRao/raykit", "max_stars_repo_head_hexsha": "7b4bf7eea7bfe444e8ef377f3f035b179e5ef4a4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "raykit/package.py", "max_issues_repo_name": "AnyiRao/raykit", "max_issues_repo_head_hexsha": "7b4bf7eea7bfe444e8ef377f3f035b179e5ef4a4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raykit/package.py", "max_forks_repo_name": "AnyiRao/raykit", "max_forks_repo_head_hexsha": "7b4bf7eea7bfe444e8ef377f3f035b179e5ef4a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0833333333, "max_line_length": 46, "alphanum_fraction": 0.8064516129, "include": true, "reason": "import numpy", "num_tokens": 52}
|
import base64
import io
from json import load as jsonload
from os import path
import cv2
import numpy as np
from PIL import Image
from keras import backend as K
from keras.models import load_model as load
from sklearn.externals import joblib
path_prefix = path.dirname(path.abspath(__file__))
config_path = path.join(path_prefix, 'config.json')
def load_weights():
"""Loads models weights from config file."""
with open(config_path) as f:
return jsonload(f)
class ModelNotFoundError(Exception):
"""Custom exception to indicate when a model does not exist or could not be found. """
def __init__(self, message):
super().__init__(message)
def fetch(name):
"""
Fetches an appropriate model to perform the prediction.
:param name: model's name
:return: a trained model
"""
K.clear_session()
try:
full_weights_path = path.join(path_prefix, *load_weights()[name])
if name == 'svm':
return SVMModel(joblib.load(full_weights_path))
elif name == 'cnn':
return CNNModel(load(full_weights_path))
elif name == 'mlp':
return MLPModel(load(full_weights_path))
except KeyError:
raise ModelNotFoundError(f'Model named {name} does not exist.')
def _b64_to_image(base64_string):
"""
Private function to convert a base64 string into a Numpy array.
:param base64_string:
:return: Numpy array
"""
imgdata = base64.b64decode(str(base64_string))
output = io.BytesIO(imgdata)
output.seek(0)
image = Image.open(output)
original_image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
return cv2.resize(original_image, (28, 28), cv2.INTER_AREA)
class CNNModel:
"""
A class wrapper for a Convolutional Neural Network implemented in Keras.
"""
def __init__(self, model):
self.model = model
def predict(self, image_b64):
"""
Predicts the label of the image.
:param image_b64:
:return: prediction as integer
"""
image = _b64_to_image(image_b64)
return self.model.predict_classes(image.reshape(-1, 28, 28, 1)).tolist()[0]
class MLPModel:
"""
A class wrapper for a Multilayer Perceptron implemented in Keras.
"""
def __init__(self, model):
self.model = model
def predict(self, image_b64):
"""
Predicts the label of the image.
:param image_b64:
:return: prediction as integer
"""
image = _b64_to_image(image_b64)
return self.model.predict_classes(image.reshape(-1, 28 * 28)).tolist()[0]
class SVMModel:
"""
A class wrapper for a Support Vector Machine implemented in scikit-learn.
"""
def __init__(self, model):
self.model = model
def predict(self, image_b64):
"""
Predicts the label of the image.
:param image_b64:
:return: prediction as integer
"""
image = _b64_to_image(image_b64)
return self.model.predict([image.reshape(-1)]).tolist()[0]
def list_models():
"""Lists all available models."""
return sorted(load_weights().keys())
|
{"hexsha": "cac149680175e6dbec7976ac5606e63bd081e49e", "size": 3179, "ext": "py", "lang": "Python", "max_stars_repo_path": "ml_models.py", "max_stars_repo_name": "miguendes/mnist-api", "max_stars_repo_head_hexsha": "26ec224a3ee5f37dc7e62be4519bae4b7ef6b6a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-03-23T01:32:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-23T01:32:05.000Z", "max_issues_repo_path": "ml_models.py", "max_issues_repo_name": "mendesmiguel/mnist-api", "max_issues_repo_head_hexsha": "26ec224a3ee5f37dc7e62be4519bae4b7ef6b6a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-03-18T21:55:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T00:59:56.000Z", "max_forks_repo_path": "ml_models.py", "max_forks_repo_name": "mendesmiguel/mnist-api", "max_forks_repo_head_hexsha": "26ec224a3ee5f37dc7e62be4519bae4b7ef6b6a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8359375, "max_line_length": 90, "alphanum_fraction": 0.6480025165, "include": true, "reason": "import numpy", "num_tokens": 742}
|
module CartesianFDM
using Base.Iterators
using LinearAlgebra
using SparseArrays
using Reexport
@reexport using Symbolics
const subscripts = ("\u2081", "\u2082", "\u2083")
const TupleN{T,N} = NTuple{N,T}
export scalar, vector
export Periodic, periodic
export NonPeriodic, nonperiodic
export Dirichlet, dir
export Neumann, neu
export Mixed
export star
export CartesianFDMContext, cartesianfdmcontext
export mask, gradient, divergence, strainrate, divergence2, dissipation, permanent
export linearize
export spacing, coordinate
export potentialflow
include("symbolics.jl")
include("topology.jl")
include("boundary.jl")
include("stencil.jl")
include("operators.jl")
include("calculus.jl")
include("linearization.jl")
include("mesh.jl")
include("flow.jl")
end
|
{"hexsha": "db21aaf312f021a165e84a2b4347e26255aeb9e5", "size": 770, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/CartesianFDM.jl", "max_stars_repo_name": "JuliaCutCell/CartesianFDM.jl", "max_stars_repo_head_hexsha": "bb1b2812c9649b2b46b62ba30b3cbf60f702b3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CartesianFDM.jl", "max_issues_repo_name": "JuliaCutCell/CartesianFDM.jl", "max_issues_repo_head_hexsha": "bb1b2812c9649b2b46b62ba30b3cbf60f702b3ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CartesianFDM.jl", "max_forks_repo_name": "JuliaCutCell/CartesianFDM.jl", "max_forks_repo_head_hexsha": "bb1b2812c9649b2b46b62ba30b3cbf60f702b3ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.7391304348, "max_line_length": 82, "alphanum_fraction": 0.7844155844, "num_tokens": 204}
|
// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/Exception.h>
#include <vw/Plate/Rpc.h>
#include <vw/Plate/RpcChannel.h>
#include <vw/Plate/HTTPUtils.h>
#include <vw/Plate/Rpc.pb.h>
#include <vw/Core/Log.h>
#include <vw/Core/Debugging.h>
#include <google/protobuf/descriptor.h>
#include <boost/scoped_ptr.hpp>
using namespace vw;
using namespace vw::platefile;
namespace pb = ::google::protobuf;
#define NOIMPL { vw_throw(vw::NoImplErr() << "Not implemented: " << VW_CURRENT_FUNCTION); }
void RpcBase::Reset() NOIMPL
bool RpcBase::Failed() const NOIMPL
std::string RpcBase::ErrorText() const NOIMPL
void RpcBase::StartCancel() NOIMPL
void RpcBase::SetFailed(const std::string& /*reason*/) NOIMPL
bool RpcBase::IsCanceled() const NOIMPL
void RpcBase::NotifyOnCancel(::google::protobuf::Closure* /*callback*/) NOIMPL
class RpcServerBase::Task {
RpcBase* m_rpc;
const Url m_url;
boost::shared_ptr<IChannel> m_chan;
ThreadMap& m_stats;
bool m_go;
public:
Task(RpcBase* rpc, const Url& u, ThreadMap& stats)
: m_rpc(rpc), m_url(u), m_stats(stats), m_go(true) {}
void operator()();
void stop() {m_go = false;}
protected:
// return = false means timeout
bool handle_one_request();
};
ThreadMap::Locked::Locked(ThreadMap& m)
: m_map(m), m_lock(new Mutex::Lock(m_map.m_mutex)) {}
ThreadMap::Locked::~Locked() {
m_lock.reset();
}
void ThreadMap::Locked::add(const std::string& key, vw::int64 val) {
m_map.m_data[key] += val;
}
int64 ThreadMap::Locked::get(const std::string& key) const {
return m_map.m_data[key];
}
void ThreadMap::Locked::clear() {
m_map.m_data.clear();
}
void ThreadMap::add(const std::string& key, vw::int64 val) {
Mutex::Lock lock(m_mutex);
m_data[key] += val;
}
vw::int64 ThreadMap::get(const std::string& key) const {
Mutex::Lock lock(m_mutex);
map_t::const_iterator i = m_data.find(key);
if (i == m_data.end())
return 0;
return i->second;
}
void ThreadMap::clear() {
Mutex::Lock lock(m_mutex);
m_data.clear();
}
void RpcServerBase::launch_thread(const Url& url) {
m_task.reset(new Task(this, url, m_stats));
m_thread.reset(new Thread(m_task));
}
RpcServerBase::RpcServerBase(const Url& url) {
launch_thread(url);
}
RpcServerBase::~RpcServerBase() {
stop();
m_thread.reset();
m_task.reset();
}
void RpcServerBase::stop() {
if (m_task)
m_task->stop();
if (m_thread)
m_thread->join();
}
void RpcServerBase::bind(const Url& url) {
launch_thread(url);
}
ThreadMap::Locked RpcServerBase::stats() {
return ThreadMap::Locked(m_stats);
}
void RpcBase::set_debug(bool on) {
m_debug = on;
}
bool RpcBase::debug() const {
return m_debug;
}
void RpcServerBase::Task::operator()() {
try {
// TODO: pass something more useful than u.string()
m_chan.reset(IChannel::make_bind(m_url, m_url.string()));
m_chan->set_timeout(250);
while (m_go) {
try {
handle_one_request();
} catch (const NetworkErr& err) {
vw_out(ErrorMessage) << "Network error! This is probably fatal. Recreating channel." << std::endl;
m_stats.add("fatal_error");
// TODO: pass something more useful than u.string()
m_chan.reset(IChannel::make_bind(m_url, m_url.string()));
m_chan->set_timeout(250);
}
}
m_chan.reset();
} catch (const std::exception& e) {
std::cerr << VW_CURRENT_FUNCTION << ": caught exception: " << e.what() << std::endl;
std::abort();
}
}
bool RpcServerBase::Task::handle_one_request() {
RpcWrapper q_wrap, a_wrap;
switch (m_chan->recv_message(q_wrap)) {
case 0:
m_stats.add("timeout");
return false;
case -1:
// message corruption?
m_stats.add("client_error");
return false;
default:
break;
}
const pb::MethodDescriptor* method = m_rpc->service()->GetDescriptor()->FindMethodByName(q_wrap.method());
VW_ASSERT(method, RpcErr() << "Unrecognized RPC method: " << q_wrap.method());
typedef boost::scoped_ptr<pb::Message> msg_t;
msg_t q(m_rpc->service()->GetRequestPrototype(method).New());
msg_t a(m_rpc->service()->GetResponsePrototype(method).New());
a_wrap.set_method(q_wrap.method());
// Attempt to parse the actual request message from the request_wrapper.
if (!q->ParseFromString(q_wrap.payload())) {
// they're not speaking our protocol. just ignore it.
m_stats.add("client_error");
return false;
}
// copy the metadata over
a_wrap.set_requestor(q_wrap.requestor());
if (q_wrap.seq() != a_wrap.seq())
a_wrap.set_seq(q_wrap.seq());
try {
m_rpc->service()->CallMethod(method, m_rpc, q.get(), a.get(), null_callback());
a_wrap.set_payload(a->SerializeAsString());
a_wrap.mutable_error()->set_code(RpcErrorMsg::SUCCESS);
m_stats.add("msgs");
} catch (const NetworkErr &e) {
// we can't respond to these, unfortunately... channel might be down. just
// rethrow, let higher-level logic work it out.
throw;
} catch (const PlatefileErr &e) {
// These exceptions should be reported back to the far side as a specific
// error code
a_wrap.mutable_error()->set_code(e.code());
a_wrap.mutable_error()->set_msg(e.what());
m_stats.add("client_error");
} catch (const std::exception &e) {
// These exceptions should be reported back to the far side as a general
// server error- unless we're in debug mode, in which case... rethrow!
a_wrap.mutable_error()->set_code(RpcErrorMsg::REMOTE_ERROR);
a_wrap.mutable_error()->set_msg(e.what());
m_stats.add("server_error");
vw_out(WarningMessage) << "Server Error: " << e.what() << std::endl;
if (m_rpc->debug()) {
m_chan->send_message(a_wrap);
throw;
}
}
m_chan->send_message(a_wrap);
return true;
}
// TODO: Make the clientname settable here.
RpcClientBase::RpcClientBase(const Url& u)
: m_chan(IChannel::make_conn(u, u.string())) {}
// TODO: Make the clientname settable here.
RpcClientBase::RpcClientBase(const Url& u, int32 timeout, uint32 retries)
: m_chan(IChannel::make_conn(u, u.string())) {
m_chan->set_timeout(timeout);
m_chan->set_retries(retries);
}
pb::RpcChannel* RpcClientBase::base_channel() {
return m_chan.get();
}
void RpcClientBase::set_timeout(int32 t) {
m_chan->set_timeout(t);
}
void RpcClientBase::set_retries(uint32 t) {
m_chan->set_retries(t);
}
|
{"hexsha": "ce0e741ad7bf641cf2fab91f55f78d607c20216f", "size": 6537, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Plate/Rpc.cc", "max_stars_repo_name": "tkeemon/visionworkbench", "max_stars_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-02T04:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-02T04:06:43.000Z", "max_issues_repo_path": "src/vw/Plate/Rpc.cc", "max_issues_repo_name": "tkeemon/visionworkbench", "max_issues_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Plate/Rpc.cc", "max_forks_repo_name": "tkeemon/visionworkbench", "max_forks_repo_head_hexsha": "df59fcb31191e1fc4fecfe1901963da1614a52b1", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4663865546, "max_line_length": 108, "alphanum_fraction": 0.6767630412, "num_tokens": 1746}
|
import numpy as np
##### DESCRIPTION #####
# This part of the module handles the mathematic
# formulation for channel coefficients estimation
# Compute the first and second coefficients of the fft considering that the third one is 0
def get_fft_01(rss): # Vector with the 4 rrs-like values corresponding to the required measurements [paper]
n_nan = sum(np.isnan(rss)) # Number of NaNs in rss (maximum of 1)
if n_nan > 1: # If there's more than 1, return a NaN
return np.nan
if n_nan == 1:
ii = np.argwhere(np.isnan(rss))[0] # If there's only one, then solve it using that the third coefficient
fft_3_coefs = np.array([1, -1, 1, -1])
if ii%2 == 0:
rss[ii] = -np.nansum(rss*fft_3_coefs)
else:
rss[ii] = np.nansum(rss*fft_3_coefs)
fft_0 = np.mean(rss) # First coefficient
fft_1 = np.dot(rss, [1, 1j, -1, -1j])/4 # Second coefficient
return fft_0, fft_1
# Compute the channe coefficient from the measures corresponding to that antenna assuming the antenna is off
def get_coef_off(rss): # Vector with the 4 rrs-like values corresponding to the required measurements [paper]
fft_0, fft_1 = get_fft_01(rss) # Get first and second fft coefficients
a = 2*np.abs(fft_1) # Amplitude of the wave
b = np.max((fft_0, a)) # Constant offset of the wave
top = np.sqrt(b+a) # High point of the wave (undoing the square)
bot = np.sqrt(b-a) # Low point of the wave (undoing the square)
amplitude = (top - bot)/2 # The amplitude of the coefficient is half the difference between top and bot
coef = amplitude*fft_1/np.abs(fft_1) # The coefficient has the same phase as fft_1
return coef
# Compute the channel coefficient from the measures corresponding to that antenna assuming the antenna is on
def get_coef_on(rss, phase_0): # Vector with the 4 rrs-like values corresponding to the required measurements [paper] and phase of the antenna when it was on
fft_0, fft_1 = get_fft_01(rss)
a = 2*np.abs(fft_1)
b = np.max((fft_0, a))
top = np.sqrt(b+a)
bot = np.sqrt(b-a)
amplitude = (top - bot)/2 # So far its the same as for get_coef_off
phase = np.angle(fft_1) # This time we compute the phase to later correct it
amplitude_0 = (top + bot)/2 # The amplitude of the array response of all the other antennas is the middle point between top and bot
phase -= np.angle(amplitude_0 + amplitude*np.exp((phase - phase_0)*1j)) # Phase correction described in the paper
return amplitude*np.exp(1j*phase)
|
{"hexsha": "2e4147115347003fc503c383d0bbc2fb21c12061", "size": 2815, "ext": "py", "lang": "Python", "max_stars_repo_path": "py_aco/core.py", "max_stars_repo_name": "Joanguitar/ACO", "max_stars_repo_head_hexsha": "3a52ddbdb1bd8c5826b8d0fcfca02f8c4e37be74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py_aco/core.py", "max_issues_repo_name": "Joanguitar/ACO", "max_issues_repo_head_hexsha": "3a52ddbdb1bd8c5826b8d0fcfca02f8c4e37be74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py_aco/core.py", "max_forks_repo_name": "Joanguitar/ACO", "max_forks_repo_head_hexsha": "3a52ddbdb1bd8c5826b8d0fcfca02f8c4e37be74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.1956521739, "max_line_length": 171, "alphanum_fraction": 0.6241563055, "include": true, "reason": "import numpy", "num_tokens": 731}
|
module DynamicPricingExamples
end # module
|
{"hexsha": "a6ae10cab1e11f1dc254bfdfb64e7fc9d8ed9a11", "size": 44, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "src/DynamicPricingExamples.jl", "max_stars_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_stars_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-02-19T06:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T07:57:57.000Z", "max_issues_repo_path": "src/DynamicPricingExamples.jl", "max_issues_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_issues_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DynamicPricingExamples.jl", "max_forks_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl", "max_forks_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.0, "max_line_length": 29, "alphanum_fraction": 0.8409090909, "num_tokens": 10}
|
# 4. faza: Analiza podatkov
Sestevek_po_pridelkih_regijah$leto <- as.character(Sestevek_po_pridelkih_regijah$leto)
Sestevek_po_pridelkih_regijah$Kolicina <- as.character(Sestevek_po_pridelkih_regijah$Kolicina)
Sestevek_po_pridelkih_regijah <- Sestevek_po_pridelkih_regijah %>% mutate(leto = parse_integer(leto), Kolicina = parse_number(Kolicina))
prileganje <- lm(Kolicina ~ leto, data = Sestevek_po_pridelkih_regijah)
predict(prileganje, data.frame(leto=seq(2010,2022,1)))
graf_napoved <- ggplot(Sestevek_po_pridelkih_regijah, aes(x=leto, y=Kolicina)) + geom_point() +
geom_smooth(method='lm', formula=y ~ poly(x,2,raw=TRUE), fullrange=TRUE, color='green') + scale_x_continuous('leto', breaks = seq(2010, 2022, 1), limits = c(2010,2022))+ xlab('Leto') + ylab('Količina ton/ha proizvedbe')
|
{"hexsha": "43e35bcbb24637bf9ba496c25596af9154e6fa4f", "size": 804, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "BlackPhoenixSlo/APPR-2020-21", "max_stars_repo_head_hexsha": "60578b3d0cad6fe9aa0aef216fa44b11330b1d91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "BlackPhoenixSlo/APPR-2020-21", "max_issues_repo_head_hexsha": "60578b3d0cad6fe9aa0aef216fa44b11330b1d91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-11-06T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-28T09:22:32.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "BlackPhoenixSlo/APPR-2020-21", "max_forks_repo_head_hexsha": "60578b3d0cad6fe9aa0aef216fa44b11330b1d91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2, "max_line_length": 221, "alphanum_fraction": 0.7723880597, "num_tokens": 306}
|
from __future__ import division
# Python 3 compatibility
#from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import map
from builtins import range
import re
import math
import networkx as nx
import subprocess as s
from struct import pack
import RNA
import ribolands as ril
# Tracks findpath calls for profiling output.
PROFILE = {'findpath-calls': 0,
'mfe': 0,
'hb': 0,
'feature': 0,
'cogr': 0,
'prune': 0}
class TrafoUsageError(Exception):
pass
class TrafoAlgoError(Exception):
pass
class DebuggingAlert(Exception):
pass
class TrafoLandscape(nx.DiGraph):
"""
A cotranscriptional interface to explore RNA energy landscapes.
A directed graph (:ob:`networkx.DiGraph()`) where nodes are RNA secondary
structures and edges are transition rates between secondary structures. Two
structures are called neighbors, if there exists an edge connecting them.
This object is initialized with the full-length RNA sequence and general RNA
folding parameters. New (or initial) conformations are found using the
routine TrafoLandscape.expand(), the landscape can be coarse-grained into a
more compact representation using the routine TrafoLandscape.coarse_grain()
and TrafoLandscape.get_simulation_files_tkn() returns a rate matrix to
simulate RNA folding, TrafoLandscape.update_occupancies_tkn() reads a
simulation output and updates the occupancies of structures accordingly.
TrafoLandscape.prune() removes improbable nodes from the landscape.
Args:
fullseq (str): The nucleotide sequence of a full-length molecule.
vrna_md (:obj:`RNA.md()`): ViennaRNA model details. Contains RNA
folding parameters such as Temperature, noLP, etc...
"""
def __init__(self, fullseq, vrna_md):
super(TrafoLandscape, self).__init__()
self._full_sequence = fullseq
self._model_details = vrna_md
self._fold_compound = RNA.fold_compound(fullseq, vrna_md)
# Adjust simulation parameters
self._RT = 0.61632077549999997
if vrna_md.temperature != 37.0:
kelvin = 273.15 + vrna_md.temperature
self._RT = (self._RT/310.15) * kelvin
# Private instance variables:
self._transcript_length = 0
self._total_time = 0
self._nodeid = 0
# Default parameters:
self._p_min = 0.01 # probability threshold
self._fpath = 20 # findpath_search_width
self._k0 = 2e5 # set directly
self._dG_max = 0 # set using t_slow
self._dG_min = 0 # set using t_fast
@property
def full_sequence(self):
return self._full_sequence
@property
def transcript(self):
return self._full_sequence[0:self._transcript_length]
@property
def t_fast(self):
"""Time-scale separation parameter for coarse-graining.
Expected folding times faster than t-fast are considered instantaneous,
and used to assign a conformation to a macrostate. This parameter is
equivalent to the internal dG_min parameter, which quantifies the minmal
energy barrier to separate two macrostates.
t_fast = 1/(self._k0 * exp(-self.dG_min/self._RT))
"""
return 1/(self._k0 * math.exp(-self._dG_min/self._RT))
@t_fast.setter
def t_fast(self, value):
self._dG_min = max(0, -self._RT * math.log(1 / value / self._k0))
@property
def t_slow(self):
"""Time-scale separation parameter for finding new neighbors.
When new a potential new relevant RNA conformation was found, then this
conformation needs to be connected to the existing energy landscape.
This parameter is used to *reject* a transition rate toward a new
energetically better structure if it is lower than t-slow, it is
equivalen to the internal dG_max parameter, which quantifies the maximal
energy barrier that can be overcome within a folding simulation.
t_slow = 1(self._k0 * exp(-self.dG_max/self._RT))
"""
if self._dG_max == 0:
return None
else:
return 1/(self._k0 * exp(-self._dG_max/self._RT))
@t_slow.setter
def t_slow(self, value):
if value is None:
self._dG_max = 0
else:
self._dG_max = -self._RT * math.log(1 / value / self._k0)
@property
def p_min(self):
"""A probability threshold to identify relevant RNA structures.
This paramenter is relevant for TrafoLandscape.expand() and
TrafoLandscape.prune(). During expansion, only conformations with
probability greater than p_min are considered. During pruning, all
conformations with probability lower than p_min are evaluated to be
removed from the landscape.
"""
return self._p_min
@p_min.setter
def p_min(self, value):
self._p_min = value
@property
def findpath_search_width(self):
"""Search width for a heuristic to find transition state energies.
"""
return self._fpath
@findpath_search_width.setter
def findpath_search_width(self, val):
self._fpath = val
def graph_copy(self):
"""Returns a copy of the TrafoLandscape Graph.
This does not include internal parameters such as the current
transcript length, current nodeID, current time, etc.
"""
copy = TrafoLandscape(self.full_sequence, self._model_details)
copy.add_nodes_from(self.nodes(data=True))
copy.add_edges_from(self.edges(data=True))
return copy
def graph_to_json(self, name):
"""Prints the current graph into a JSON file format.
There exits a script to visualize the output files using d3js in your
browser. Search for it in: ribolands/d3js/start_server.py
Args:
name (str): The basename of the *.json file.
"""
import json
from networkx.readwrite import json_graph
d = json_graph.node_link_data(self)
json.dump(d, open(name+'.json', 'w'))
def graph_to_pdf(self, name):
import matplotlib.pyplot as plt
name += 'mpl.pdf'
nl = [x for x in self.nodes if self.node[x]['active']]
nd = nx.get_node_attributes(self, 'identity')
nx.drawing.nx_pylab.draw_networkx(self, nodelist=nl, labels=nd)
plt.axis('off') # turn of axis
plt.savefig(name)
plt.clf()
def sorted_nodes(self, descending=False):
""" Returns active nodes and their attributes sorted by energy.
Args:
descending (bool, optional): sorting parameter.
True: energetically high to low.
False: energetically low to high.
Defaults to False.
"""
active = [n_d for n_d in self.nodes(data=True) if n_d[1]['active']]
return sorted(active, key=lambda x: (
x[1]['energy'], x[0]), reverse=descending)
def get_saddle(self, s1, s2):
"""Returns the saddle energy of a transition edge."""
if self.has_edge(s1, s2):
return self[s1][s2]['saddle']
else:
return None
def get_rate(self, s1, s2):
"""Returns the direct transition rate of two secondary structures."""
if self.has_edge(s1, s2):
return self[s1][s2]['weight']
else:
return 0
def add_transition_edge(self, s1, s2, ts=None, fpath=None, fpathE=None, call=None, fake=False):
"""Calculates transition rates from direct path barrier heights.
Uses the *findpath* direct path heuristic to find the lowest energy barrier
between two secondary structures. Typically s2 is the new, energetically
better structure, but this is not enforced. In case a transient structure
"ts" is specified, the rate is computed as the minimum between the direct
path s1 -> s2 and the indirect folding path s1 -> ts -> s2.
Rates are computed using the Metropolis model. k0 and RT are global
variables in the ConformaitonGraph object.
Args:
s1 (str): start secondary structure (must be part of TrafoLandscape already)
s2 (str): final secondary structure (may be added to TrafoLandscape)
ts (str, optional): transient secondary structure which is not on the
direct folding path. If a transient structure is specified, the direct
path barriers s1 -> ts and ts -> s2 must be known already.
fpath (int, optional): the search width parameter for the findpath routine.
Defaults to None: using global TrafoLandscape parameter.
fpathE (flt, optional): an upper bound on the energy of the transition
state for findpath. A neighbor is only valid, if there exits a path
via an energetically *better* transition state.
Returns:
bool: True if the transition edge was added to the graph, False otherwise.
"""
fullseq = self._full_sequence
md = self._model_details
fc = self._fold_compound
_RT = self._RT
_k0 = self._k0
if fpath is None:
fpath = self._fpath
#if self._dG_max:
# maxE = self.node[s1]['energy'] + self._dG_max
# fpathE = min(maxE, fpathE) if fpathE else maxE
assert s1 != s2
# Lookup the in-direct path barrier first
if ts: # then we know that the indirect path has to be part of saddles
tsE1 = self.get_saddle(s1, ts)
tsE2 = self.get_saddle(s2, ts)
tsE = max(tsE1, tsE2)
saddleE = self.get_saddle(s1, s2)
# This line will ensure that findpath is *not called*, instead,
# tsE is used as saddle energy.
if fake and ts and saddleE is None:
saddleE = 9999
def findpath_wrap(s1, s2, maxE, fpath):
if maxE:
dcal_bound = int(round(maxE * 100))
dcal_sE = fc.path_findpath_saddle(s1, s2, maxE=dcal_bound, width=fpath)
else :
dcal_sE = fc.path_findpath_saddle(s1, s2, width=fpath)
return float(dcal_sE)/100 if dcal_sE else dcal_sE
# Now this is the computationally heavy part ...
if saddleE is None:
if ts:
saddleE = findpath_wrap(s1, s2, tsE, fpath)
saddleE = tsE if saddleE is None else saddleE
else:
saddleE = findpath_wrap(s1, s2, fpathE, fpath)
PROFILE['findpath-calls'] += 1
if call:
PROFILE[call] += 1
elif ts:
saddleE = min(saddleE, tsE)
if fpathE and saddleE:
assert saddleE <= fpathE
if saddleE is not None: # Add the edge.
e1 = self.node[s1]['energy']
e2 = self.node[s2]['energy'] if self.has_node(s2) else round(fc.eval_structure(s2), 2)
# ensure saddle is not lower than s1, s2
saddleE = max(saddleE, max(e1, e2))
# Energy barrier
dG_1s = saddleE - e1
dG_2s = saddleE - e2
# Metropolis Rule
k_12 = _k0 * math.exp(-dG_1s/_RT)
k_21 = _k0 * math.exp(-dG_2s/_RT)
self.add_weighted_edges_from([(s1, s2, k_12)])
self.add_weighted_edges_from([(s2, s1, k_21)])
self[s1][s2]['saddle'] = saddleE
self[s2][s1]['saddle'] = saddleE
if 'meta' not in self[s1][s2] :
self[s1][s2]['meta'] = call
self[s2][s1]['meta'] = call
return not (saddleE is None)
def expand(self, extend=1, exp_mode='default', mfree=6, p_min=None, warning=False):
"""Find new secondary structures and add them to :obj:`TrafoLandscape()`
The function supports two move-sets: 1) The mfe structure for the current
sequence length is connected to all present structures, 2) The conformation
graph is expanded using helix-breathing.
Args:
extend (int, optional): number of nucleotide extensions before graph
expansion (updates the global variable transcript length). Defaults to 1.
exp_mode (str, optional): choose from "mfe-only": only use current mfe
structure as potential new neighbor. "breathing-only": only use breathing
neighborhood. "default": do both mfe and breathing.
mfree (int, optional): minimum number of freed bases during a
helix-opening step. Defaults to 6.
p_min (flt, optional): Minimum probability of a structure for neighbor
generation. Defaults to None: using global TrafoLandscape parameter.
warning (bool, optional): When using 'breathing-only' search mode,
print a warning if MFE structure is not part of the ensemble. Be
aware that calculating the MFE structure just for this warning is not
recommended for large systems!
Returns:
int: Number of new nodes
"""
if p_min is None:
p_min = self._p_min
fseq = self.full_sequence
self._transcript_length += extend
if self._transcript_length > len(fseq):
self._transcript_length = len(fseq)
seq = self.transcript
csid = self._nodeid
md = self._model_details
fc_full = self._fold_compound
if exp_mode not in ['default', 'mfe-only', 'breathing-only']:
raise TrafoUsageError('unknown expansion mode')
# Calculate MFE of current transcript
if exp_mode == 'default' or exp_mode == 'mfe-only' or len(self) == 0 or warning:
fc_tmp = RNA.fold_compound(seq, md)
ss, mfe = fc_tmp.mfe()
future = '.' * (len(fseq) - len(seq))
ss = ss + future
# If there is no node because we are in the beginning, add the node,
# otherwise, try to add transition edges from every node to MFE.
if len(self) == 0:
en = round(fc_full.eval_structure(ss), 2)
self.add_node(ss, energy=en, occupancy=1.0,
identity=self._nodeid, active=True, last_seen=0)
self._nodeid += 1
elif exp_mode == 'default' or exp_mode == 'mfe-only':
# Try to connect MFE to every existing state
fpathE = 9999
for ni in sorted(self.nodes(), key=lambda x: RNA.bp_distance(ss, x)):
if ni == ss:
continue
if self.node[ni]['active'] == False:
continue
if self.has_edge(ni, ss):
# in case it was there but inactive
self.node[ss]['active'] = True
self.node[ss]['last_seen'] = 0
assert self.get_saddle(ss, ni) is not None
fpathE = self.get_saddle(ss, ni) \
if self.get_saddle(ss, ni) < fpathE else fpathE
continue
if self.has_node(ss): # from a previous iteration
if self.add_transition_edge(ni, ss, fpathE=fpathE+1.00, call='mfe'):
# in case it was there but inactive
self.node[ss]['active'] = True
self.node[ss]['last_seen'] = 0
elif self.add_transition_edge(ni, ss, fpathE=fpathE+1.00, call='mfe'):
en = round(fc_full.eval_structure(ss), 2)
self.node[ss]['active'] = True
self.node[ss]['last_seen'] = 0
self.node[ss]['energy'] = en
self.node[ss]['occupancy'] = 0.0
self.node[ss]['identity'] = self._nodeid
self._nodeid += 1
if self.get_saddle(ss, ni) is not None:
fpathE = self.get_saddle(ss, ni) \
if self.get_saddle(ss, ni) < fpathE else fpathE
if exp_mode == 'default' or exp_mode == 'breathing-only':
# Do the helix breathing graph expansion
# Initialize a dictionary to store the feature expansion during each
# graph expansion round: ext_moves[ext_seq] = [set((con,paren),...),
# structure] where ext_seq = exterior-loop sequence with ((xxx))
# replacing constrained elements
ext_moves = dict()
# Every neighbor generation can only produce energetically better
# neighbors, so they are sorted upfront. Note that there are inactive
# nodes that might become active during expansion, but their occupancy
# will not change.
for ni, data in sorted(self.nodes(data=True),
key=lambda x: x[1]['energy'], reverse=True):
if data['active'] == False:
continue
en = data['energy']
#occ = data['occupancy']
#if occ < p_min:
# continue
# short secondary structure (without its future)
sss = ni[0:len(seq)]
# compute a set of all helix breathing open steps
opened = open_breathing_helices(seq, sss, mfree)
# do a constrained exterior loop folding for all of them and then
# connect them to the present conformation and to each other.
connect = [ni]
for onbr in opened:
nbr, ext_seq = fold_exterior_loop(md, seq, onbr, ext_moves)
future = '.' * (len(ni) - len(nbr))
nbr += future
if ni == nbr:
continue
if self.has_edge(ni, nbr):
# in case it was there but inactive
self.node[nbr]['active'] = True
self.node[nbr]['last_seen'] = 0
continue
for con in connect:
if con == nbr:
continue
if self.has_node(nbr):
if self.add_transition_edge(con, nbr, call='hb'):
# in case it was there but inactive
self.node[nbr]['active'] = True
self.node[nbr]['last_seen'] = 0
elif self.add_transition_edge(con, nbr, call='hb'):
enbr = round(fc_full.eval_structure(nbr), 2)
self.node[nbr]['energy'] = enbr
self.node[nbr]['active'] = True
self.node[nbr]['last_seen'] = 0
self.node[nbr]['occupancy'] = 0.0
self.node[nbr]['identity'] = self._nodeid
self._nodeid += 1
else:
msg = "# helix breathing: could not add transition edge!"
raise DebuggingAlert(msg)
#continue
if self.has_node(nbr) and self.node[nbr]['active']:
connect.append(nbr)
# Now connect the neighbor with *historic* transitions of parents.
# We store the exterior-open neighbor here, that means there are
# three possible reasons for duplication:
# 1) different (or longer) helix was opened / same historic features
# 2) the same helix was opened / difference is in historic features
# 3) different helix / different history
if ext_moves[ext_seq][0]:
for (parent, child) in ext_moves[ext_seq][0]:
assert parent != ni # Parents may never be the same
if child == nbr:
# the parents differ in breathing helices,
# no historic differences
continue
# Now the case with historic differences ...
if self.has_edge(parent, ni):
if self.has_node(child) and self.has_node(nbr):
if self.has_edge(nbr, child):
continue
# TODO: Calculate saddleE from saddleE of parents?
sP = self.get_saddle(ni, parent)
sC1 = round(self.node[child]['energy'] \
+ sP - self.node[parent]['energy'], 2)
sC2 = round(self.node[nbr]['energy'] \
+ sP - self.node[ni]['energy'], 2)
if sC1 == sC2: # avoid findpath!
self.add_weighted_edges_from([(nbr, child, None)])
self.add_weighted_edges_from([(child, nbr, None)])
self[nbr][child]['saddle'] = sC1
self[child][nbr]['saddle'] = sC1
if self.add_transition_edge(nbr, child, call='feature'):
# in case it was there but inactive
self.node[nbr]['active'] = True
self.node[nbr]['last_seen'] = 0
# in case it was there but inactive
self.node[child]['active'] = True
self.node[child]['last_seen'] = 0
else:
# Can only happen when using dG_max
self.remove_edge(nbr, child)
self.remove_edge(child, nbr)
continue
else:
if self.add_transition_edge(nbr, child, call='feature'):
# in case it was there but inactive
self.node[nbr]['active'] = True
self.node[nbr]['last_seen'] = 0
# in case it was there but inactive
self.node[child]['active'] = True
self.node[child]['last_seen'] = 0
else:
# Apparently, either child or nbr could not be connected
# to the graph, but since parents are connected we should
# give it a try.. but then again, this can only happen when
# using dG_max during rate computation.
continue
# Track the final structure, every new identical ext-change will be
# connected, if the parents were connected.
ext_moves[ext_seq][0].add((ni, nbr))
if warning and not self.has_node(ss) or (not self.node[ss]['active']):
print("# WARNING: mfe secondary structure not connected\n# {}".format(ss))
# Post processing of graph after expansion:
# remove nodes that have been inactive for a long time.
for ni in list(self.nodes()):
if self.node[ni]['active'] == False:
self.node[ni]['last_seen'] += 1
else:
self.node[ni]['last_seen'] = 0
if self.node[ni]['last_seen'] >= 5:
self.remove_node(ni)
return self._nodeid - csid
def coarse_grain(self, dG_min=None):
"""Landscape coarse-graining base on energy barriers.
Every structure gets assigned to an energetically better or equal
macrostate. If a structure gets a assigned to itself, well then it
represents the macrostate
Try it in two iterations:
-> assign every structure to its macrostate.
-> remove nodes but and use transition to
Processes an energetically sorted list of structures (high to low
energies) and tries to merge their occupancy into a neighboring, better
conformation (forming a macro-state). The current structure is merged
(and therefore removed from the graph) if there exists a neighbor that
has better energy and the energy barrier is lower than the dG_min
parameter. If there are multiple better neighbors with a minimal
transition energy barrier, then the occupancy is transfered to the
neighbor with the lowest energy, in the degenerate case the
lexicographically first structure is chosen.
Args:
dG_min (flt, optional): Minimum energy barrier between separate
macrostates.
Returns:
dict[del-node] = macro-node: A mapping from deleted nodes to macro-state
"""
merged_nodes = dict()
merged_to = dict()
if dG_min is None:
dG_min = self._dG_min
assert dG_min is not None
# sort by energy (high to low)
for ni, data in sorted(self.nodes(data=True),
key=lambda x: (x[1]['energy'], x), reverse=True):
if data['active'] == False:
continue
en = data['energy']
# get all active neighbors (low to high)
nbrs = [x for x in sorted(self.successors(ni),
key=lambda x: (self.node[x]['energy'], x), reverse=False) if self.node[x]['active']]
if nbrs == []:
break
# lowest neighbor structure and energy
best, been = nbrs[0], self.node[nbrs[0]]['energy']
if been - en > 0.0001:
# local minimum
continue
# among all energetically better neighbors, find the neighbor with the
# lowest energy barrier ...
(transfer, minsE) = (best, self.get_saddle(ni, best))
for e, nbr in enumerate(nbrs[1:]):
if self.node[nbr]['energy'] - en >= 0.0001:
break
sE = self.get_saddle(ni, nbr)
if sE - minsE < 0.0001:
(transfer, minsE) = (nbr, sE)
if minsE - en - dG_min > 0.0001: # avoid precision errors
# do not merge, if the barrier is too high.
continue
# connect all neighboring nodes to the transfer node
for e, nb1 in enumerate(nbrs, 1):
if nb1 == transfer:
continue
(s1, s2) = (nb1, transfer) if \
self.node[nb1]['energy'] > self.node[transfer]['energy'] else \
(transfer, nb1)
always_true = self.add_transition_edge(s1, s2, ts=ni, call='cogr')
if always_true is False:
raise TrafoAlgoError('Did not add the transition edge!')
# remove the node
self.node[ni]['active'] = False
self.node[ni]['last_seen'] = 1
self.node[transfer]['occupancy'] += self.node[ni]['occupancy']
self.node[ni]['occupancy'] = 0.0
merged_nodes[ni] = transfer
if transfer in merged_to:
merged_to[transfer].append(ni)
else:
merged_to[transfer] = [ni]
if ni in merged_to:
fathers = merged_to[ni]
for f in fathers:
merged_nodes[f] = transfer
merged_to[transfer].append(f)
del merged_to[ni]
return merged_nodes
def simulate(self, t0, t8, tmpfile=None):
# treekin wrapper function using:
# "self.get_simulation_files_tkn"
# "self.update_occupancies_tkn"
raise NotImplementedError
def get_simulation_files_tkn(self, name, binrates=True):
""" Print a rate matrix and the initial occupancy vector.
This function prints files and parameters to simulate dynamics using the
commandline tool treekin. A *.bar file contains a sorted list of present
structures, their energy and their neighborhood and the corresponding
energy barriers. A *.rts or *.rts.bin file contains the matrix of
transition rates either in text or binary format. Additionaly, it returns
a vector "p0", which contains the present occupancy of structures. The
order or elements in p0 contains
Note:
A *.bar file contains the energy barriers to transition between local
minima. In contrast to files produced by `barriers`, where local minimum
is always *directly* connected to an energetically better local minimum,
here a path towards the MFE structure can proceed via an energetically
worse structure first.
Args:
name (str): Name of output files name.bar, name.rts, name.rts.bin.
binrates (bool, optional): Print rates in binary format or text format.
Defaults to True: binary format.
"""
seq = self.transcript
sorted_nodes = self.sorted_nodes(descending=False)
bfile = name + '.bar'
rfile = name + '.rts'
brfile = rfile + '.bin'
p0 = []
with open(bfile, 'w') as bar, open(rfile, 'w') as rts, open(brfile, 'wb') as brts:
bar.write(" {}\n".format(seq))
brts.write(pack("i", len(sorted_nodes)))
for e, (ni, data) in enumerate(sorted_nodes, 1):
# Calculate barrier heights to all other basins.
nMsE = set()
for ee, (be, _) in enumerate(sorted_nodes, 1):
if e == ee:
continue
sE = self.get_saddle(be, ni)
if sE is not None:
nMsE.add((ee, sE))
mystr = ' '.join(['({:3d} {:6.2f})'.format(x_y[0], x_y[1] - data['energy']) for x_y in sorted(list(nMsE), key=lambda x: x[0])])
# Print structures and neighbors to bfile:
bar.write("{:4d} {} {:6.2f} {}\n".format(e, ni[:len(seq)], data['energy'], mystr))
# Add ni occupancy to p0
if data['occupancy'] > 0:
p0.append("{}={}".format(e, data['occupancy']))
# Print rate matrix to rfile and brfile
trates = []
rates = []
for (nj, jdata) in sorted_nodes:
if self.has_edge(ni, nj):
rates.append(self[ni][nj]['weight'])
trates.append(self[nj][ni]['weight'])
else:
rates.append(0)
trates.append(0)
line = "".join(map("{:10.4g}".format, rates))
rts.write("{}\n".format(line))
for r in trates:
brts.write(pack("d", r))
return [bfile, brfile if binrates else rfile, p0, sorted_nodes]
# update_time_and_occupancies_tkn(self, tfile)
def update_occupancies_tkn(self, tfile, sorted_nodes):
"""
Update the occupancy in the Graph and the total simulation time
"""
# http://www.regular-expressions.info/floatingpoint.html
reg_flt = re.compile(b'[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?.')
lastlines = s.check_output(['tail', '-2', tfile]).strip().split(b'\n')
if not reg_flt.match(lastlines[0]):
raise TrafoAlgoError('Cannot parse simulation output', tfile)
else:
if reg_flt.match(lastlines[1]):
time = float(lastlines[1].split()[0])
iterations = None
tot_occ = sum(map(float, lastlines[1].split()[1:]))
for e, occu in enumerate(lastlines[1].split()[1:]):
ss = sorted_nodes[e][0]
self.node[ss]['occupancy'] = float(occu)/tot_occ
else :
time = float(lastlines[0].split()[0])
iterations = int(lastlines[-1].split()[-1])
tot_occ = sum(map(float, lastlines[0].split()[1:]))
for e, occu in enumerate(lastlines[0].split()[1:]):
ss = sorted_nodes[e][0]
self.node[ss]['occupancy'] = float(occu)/tot_occ
return time, iterations
def prune(self, p_min=None, maxh=None, mocca=None, detailed=False):
""" Delete nodes or report them as still reachable.
Use the occupancy cutoff to choose which nodes to keep and which ones to
remove. Every node with occuancy < cutoff will be removed and its neighbors
connected with each other. You may set the *maxh* parameter to reject the
removal of a node that has a very high energy barrier to all its neighbors.
Args:
p_min (flt, optional): Occupancy cutoff for neighbor generation.
Defaults to None: using global TrafoLandscape parameter.
maxh (flt, optional): Don't remove structures that are separated with
an energy barrier higher than maxh.
Returns:
int, int, int:
number of deleted nodes,
number of still reachable nodes,
number of rejected deletions due to maxh
"""
if p_min is None:
p_min = self._p_min
deleted_nodes = 0
still_reachables = 0
rejected = 0
for ni, data in self.sorted_nodes(descending=False): # sort high to low..
if data['occupancy'] - p_min > 0.0000001:
continue
en = data['energy']
# get all active neighbors (low to high)
nbrs = [x for x in sorted(self.successors(ni),
key=lambda x: self.node[x]['energy'], reverse=False) if self.node[x]['active']]
# looks good!
if mocca and len([x for x in nbrs if self.node[x]['occupancy'] >= p_min]) > mocca:
rejected += 1
continue
# lowest neighbor structure and energy
best, been = nbrs[0], self.node[nbrs[0]]['energy']
if been - en > 0.0001:
still_reachables += 1
continue
# among *all* neighbors, find the neighbor with the lowest energy barrier
(transfer, minsE) = (best, self.get_saddle(ni, best))
for e, nbr in enumerate(nbrs[1:]):
sE = self.get_saddle(ni, nbr)
if sE - minsE < 0.0001:
(transfer, minsE) = (nbr, sE)
if maxh and (minsE - en - maxh > 0.0001):
# do not merge, if the barrier is too high.
rejected += 1
continue
# remove the node
self.node[ni]['active'] = False
self.node[ni]['last_seen'] = 1
self.node[transfer]['occupancy'] += self.node[ni]['occupancy']
self.node[ni]['occupancy'] = 0.0
deleted_nodes += 1
for e, nb1 in enumerate(nbrs, 1):
for nb2 in nbrs[e:]:
always_true = self.add_transition_edge(nb2, nb1, ts=ni, call='prune',
fake=not detailed)
if always_true is False:
raise TrafoAlgoError('Did not add the transition edge!')
return deleted_nodes, still_reachables, rejected
def sorted_trajectories_iter(self, sorted_nodes, tfile, softmap=None):
""" Yields the time course information using a treekin output file.
Args:
sorted_nodes (list): a list of nodes sorted by their energy
tfile (str): treekin-output file name.
softmap (dict, optional): A mapping to transfer occupancy between
states. Likely not the most efficient implementation.
Yields:
list: ID, time, occupancy, structure, energy
"""
# http://www.regular-expressions.info/floatingpoint.html
reg_flt = re.compile('[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?.')
ttime = self._total_time
with open(tfile) as tkn:
# this is ugly, but used to check if we're at the last line
prevcourse = []
tknlines = tkn.readlines()
for line in tknlines:
if reg_flt.match(line):
course = list(map(float, line.strip().split()))
time = course[0]
# softmap hack:
# preprocess the timeline by merging all states
if softmap:
macrostates = [0] * len(course)
macromap = dict()
for e, occu in enumerate(course[1:]):
ss = sorted_nodes[e][0]
# map occupancy to (energetically better)
if ss in softmap:
mapss = softmap[ss]
mapid = macromap[mapss]
else:
# we *must* have seen this state before, given
# there are no degenerate sorting errors...
mapid = e + 1
macromap[ss] = mapid
macrostates[mapid] += occu
course[1:] = macrostates[1:]
for e, occu in enumerate(course[1:]):
# is it above visibility threshold?
ss = sorted_nodes[e][0]
sss = ss[0:self._transcript_length]
yield self.node[ss]['identity'], ttime + time, occu, \
sss, self.node[ss]['energy']
prevcourse = course
return
def open_breathing_helices(seq, ss, free=6):
""" open all breathable helices, i.e. those that share a base-pair
with an exterior loop region
"""
nbrs = set()
pt = ril.make_pair_table(ss, base=0)
# mutable secondary structure
nbr = list(ss)
rec_fill_nbrs(nbrs, ss, nbr, pt, (0, len(ss)), free)
nbrs.add(''.join(nbr))
return nbrs
def rec_fill_nbrs(nbrs, ss, mb, pt, xxx_todo_changeme, free):
""" recursive helix opening
TODO: Test function, but looks good
:param nbrs: a set of all neighboring conformations
:param ss: reference secondary structure
:param mb: a mutable version of ss, which, after the final round will have
all breathing helices opened
:param pt: pair table (zero based)
:param (n,m): the range of the pt under current investigation
:param free: number of bases that should be freed
:return:
"""
(n, m) = xxx_todo_changeme
skip = 0 # fast forward in case we have deleted stuff
for i in range(n, m):
j = pt[i]
if j == -1:
continue
if i < skip:
continue
nb = list(ss)
[o, l] = [0, 0]
[p, q] = [i, j]
add = True
while p < q and (l == 0 or o < free):
if pt[p] != q or p != pt[q]:
""" this is a multiloop """
# i,j = 1, len(pt)
rec_fill_nbrs(nbrs, ''.join(nb), mb, pt, (p, q), free - o)
add = False
break
# remove the base-pairs
pt[p] = pt[q] = -1
nb[p] = nb[q] = '.'
mb[p] = mb[q] = '.'
o += 2 # one base-pair deleted, two bases freed
l = 0 # reset interior-loop size
while (p < q and pt[p + 1] == -1):
[p, l] = [p + 1, l + 1]
p += 1
while (p < q and pt[q - 1] == -1):
[q, l] = [q - 1, l + 1]
q -= 1
o += l
if add:
nbrs.add(''.join(nb))
skip = j + 1
return
def fold_exterior_loop(md, seq, con, ext_moves):
""" Constrained folding of the exterior loop.
All constrained helices are replaced with the motif:
NNNNNNN
((xxx))
for example a helix with the closing-stack CG-UG:
CG ~ UG -> CGNNNUG
(( ~ )) -> ((xxx))
This reduces the sequence length (n) and therefore the runtime O(n^3),
and it enables the identification of independent structures with the same
exterior loop features.
Args:
md (RNA.md()): ViennaRNA model details (temperature, noLP, etc.)
seq (str): RNA sequence
con (str): RNA structure constraint
ext_moves (dict()): Dictionary storing all mappings from exterior-loop
constraints (features) to parents.
Returns:
(str, str):
"""
spacer = 'NNN'
pt = ril.make_pair_table(con, base=0)
ext_seq = ''
ext_con = ''
# shrink the sequences
skip = 0
for i, j in enumerate(pt):
if i < skip:
continue
if j == -1:
ext_seq += seq[i]
ext_con += '.'
else:
ext_seq += seq[i] + seq[i + 1]
ext_seq += spacer
ext_seq += seq[j - 1] + seq[j]
ext_con += '(('
ext_con += 'x' * len(spacer)
ext_con += '))'
skip = j + 1
# If we have seen this exterior loop before, then we don't need to
# calculate again, and we have to trace back if the parents are connected.
if ext_seq in ext_moves:
css = ext_moves[ext_seq][1]
else:
fc_tmp = RNA.fold_compound(ext_seq, md)
fc_tmp.constraints_add(
ext_con, RNA.CONSTRAINT_DB_DEFAULT | RNA.CONSTRAINT_DB_ENFORCE_BP)
css, cfe = fc_tmp.mfe()
ext_moves[ext_seq] = [set(), css]
del fc_tmp
# replace characters in constraint
c, skip = 0, 0
for i, j in enumerate(pt):
if i < skip:
continue
if j == -1:
con = con[:i] + css[c] + con[i + 1:]
c += 1
else:
c += len(spacer) + 4
skip = j + 1
ss = con
return ss, ext_seq
|
{"hexsha": "e618a16f7550ae3cc2e39c2b5a4b257bba5f4794", "size": 42847, "ext": "py", "lang": "Python", "max_stars_repo_path": "ribolands/trafo.py", "max_stars_repo_name": "entzian/ribolands", "max_stars_repo_head_hexsha": "04bb3274947ff81ef0d5b859b38e56b0c0709f15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ribolands/trafo.py", "max_issues_repo_name": "entzian/ribolands", "max_issues_repo_head_hexsha": "04bb3274947ff81ef0d5b859b38e56b0c0709f15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ribolands/trafo.py", "max_forks_repo_name": "entzian/ribolands", "max_forks_repo_head_hexsha": "04bb3274947ff81ef0d5b859b38e56b0c0709f15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1189138577, "max_line_length": 143, "alphanum_fraction": 0.5372371461, "include": true, "reason": "import networkx,from networkx", "num_tokens": 9758}
|
MODULE complex_class
IMPLICIT NONE
! Type definition
TYPE,PUBLIC :: complex_ob ! This will be the name we instantiate
PRIVATE
REAL :: re ! Real part
REAL :: im ! Imaginary part
END TYPE complex_ob
! Now add methods
CONTAINS
!(Insert methods here)
SUBROUTINE temp(x)
REAL :: x
x = 1.
END SUBROUTINE temp
END MODULE complex_class
|
{"hexsha": "9bfe78c95f8d316b7c09b767c4e178b3d0f2d054", "size": 406, "ext": "f90", "lang": "FORTRAN", "max_stars_repo_path": "Fortran952003ForScientistsandEngineers3rdStephenJChapman/chap16/complex_class.f90", "max_stars_repo_name": "yangyang14641/FortranLearning", "max_stars_repo_head_hexsha": "3d4a91aacd957361aff5873054edf35c586e8a55", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-03-12T02:18:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T07:58:56.000Z", "max_issues_repo_path": "Fortran952003ForScientistsandEngineers3rdStephenJChapman/chap16/complex_class.f90", "max_issues_repo_name": "yangyang14641/FortranLearning", "max_issues_repo_head_hexsha": "3d4a91aacd957361aff5873054edf35c586e8a55", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fortran952003ForScientistsandEngineers3rdStephenJChapman/chap16/complex_class.f90", "max_forks_repo_name": "yangyang14641/FortranLearning", "max_forks_repo_head_hexsha": "3d4a91aacd957361aff5873054edf35c586e8a55", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-05-11T02:36:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-05T06:36:55.000Z", "avg_line_length": 19.3333333333, "max_line_length": 67, "alphanum_fraction": 0.618226601, "num_tokens": 99}
|
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Desription
# ==============================================================================
#
# Tests related to the API function to invert rotations.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# File: ./src/inv_rotations.jl
# ============================
# Functions: inv_rotation
# -----------------------
@testset "Invert rotations (Float64)" begin
T = Float64
# DCM
# ==========================================================================
# Create a random DCM.
D = create_rotation_matrix(_rand_ang(T), :Z) *
create_rotation_matrix(_rand_ang(T), :Y) *
create_rotation_matrix(_rand_ang(T), :X)
Di = inv_rotation(D)
@test eltype(Di) === T
Die = inv(D)
@test Di ≈ Die
# Quaternion
# ==========================================================================
# Create a random quaternion.
q = Quaternion(_rand_ang(T), _rand_ang(T), _rand_ang(T), _rand_ang(T))
q = q / norm(q)
qi = inv_rotation(q)
@test eltype(qi) === T
qie = inv(q)
@test qi ≈ qie
# Euler angle and axis
# ==========================================================================
# Create a random Euler angle and axis.
v = @SVector rand(T, 3)
a = _rand_ang(T)
av = EulerAngleAxis(a, v)
avi = inv_rotation(av)
@test eltype(avi) === T
avie = inv(av)
@test avi ≈ avie
# Euler angles
# ==========================================================================
# Create random Euler angles.
ea = EulerAngles(_rand_ang(T), _rand_ang(T), _rand_ang(T), rand(valid_rot_seqs))
eai = inv_rotation(ea)
@test eltype(eai) === T
eaie = inv(ea)
@test eai ≈ eaie
end
@testset "Invert rotations (Float32)" begin
T = Float32
# DCM
# ==========================================================================
# Create a random DCM.
D = create_rotation_matrix(_rand_ang(T), :Z) *
create_rotation_matrix(_rand_ang(T), :Y) *
create_rotation_matrix(_rand_ang(T), :X)
Di = inv_rotation(D)
@test eltype(Di) === T
Die = inv(D)
@test Di ≈ Die
# Quaternion
# ==========================================================================
# Create a random quaternion.
q = Quaternion(_rand_ang(T), _rand_ang(T), _rand_ang(T), _rand_ang(T))
q = q / norm(q)
qi = inv_rotation(q)
@test eltype(qi) === T
qie = inv(q)
@test qi ≈ qie
# Euler angle and axis
# ==========================================================================
# Create a random Euler angle and axis.
v = @SVector rand(T, 3)
a = _rand_ang(T)
av = EulerAngleAxis(a, v)
avi = inv_rotation(av)
@test eltype(avi) === T
avie = inv(av)
@test avi ≈ avie
# Euler angles
# ==========================================================================
# Create random Euler angles.
ea = EulerAngles(_rand_ang(T), _rand_ang(T), _rand_ang(T), rand(valid_rot_seqs))
eai = inv_rotation(ea)
@test eltype(eai) === T
eaie = inv(ea)
@test eai ≈ eaie
end
|
{"hexsha": "f246564718aee8e5b5ae50df92ba08ca59e86edb", "size": 3223, "ext": "jl", "lang": "Julia", "max_stars_repo_path": "test/inv_rotations.jl", "max_stars_repo_name": "ChrisRackauckas/ReferenceFrameRotations.jl", "max_stars_repo_head_hexsha": "eded8889b66537e0907398ac53299587f8839d69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/inv_rotations.jl", "max_issues_repo_name": "ChrisRackauckas/ReferenceFrameRotations.jl", "max_issues_repo_head_hexsha": "eded8889b66537e0907398ac53299587f8839d69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/inv_rotations.jl", "max_forks_repo_name": "ChrisRackauckas/ReferenceFrameRotations.jl", "max_forks_repo_head_hexsha": "eded8889b66537e0907398ac53299587f8839d69", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6030534351, "max_line_length": 84, "alphanum_fraction": 0.4213465715, "num_tokens": 836}
|
# noinspection PyUnresolvedReferences
from difs import dif1, dif2, dif3, dif4
import numpy as np
def next_move(difficulty, *args):
difficulties = {
1: dif1.completely_random, # random element in avalable moves
2: dif2.winning_or_block_then_random, # Order: win, block, random in available moves
3: dif3.get_two_winning_moves, # Order: win, block, get two winning, middle, random corner, random side
4: dif4.minimax # Calculates best move, unbeatable
}
return np.array(difficulties[difficulty](*args)).take(0) # I use np.array because .take(0) returns first element regardless of dimnetion
|
{"hexsha": "dd2ce438e48e1afca3564c27b6c989473efdef5d", "size": 641, "ext": "py", "lang": "Python", "max_stars_repo_path": "NaC/computer_move.py", "max_stars_repo_name": "thdb-theo/Board-Games", "max_stars_repo_head_hexsha": "0af6ca2e4c8cfbc5642070e35d91edcc899b03a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NaC/computer_move.py", "max_issues_repo_name": "thdb-theo/Board-Games", "max_issues_repo_head_hexsha": "0af6ca2e4c8cfbc5642070e35d91edcc899b03a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NaC/computer_move.py", "max_forks_repo_name": "thdb-theo/Board-Games", "max_forks_repo_head_hexsha": "0af6ca2e4c8cfbc5642070e35d91edcc899b03a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7333333333, "max_line_length": 141, "alphanum_fraction": 0.72074883, "include": true, "reason": "import numpy", "num_tokens": 176}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.