text
stringlengths 0
3.34M
|
---|
-- -------------------------------------------------------------- [ Lens.idr ]
-- Description : Idris port of Control.Applicative
-- Copyright : (c) Huw Campbell
-- --------------------------------------------------------------------- [ EOH ]
module Control.Lens
import public Control.Lens.At
import public Control.Lens.Types
import public Control.Lens.Const
import public Control.Lens.First
import public Control.Lens.Getter
import public Control.Lens.Review
import public Control.Lens.Setter
import public Control.Lens.Prism
import public Control.Lens.Tuple
import public Control.Lens.Maths
import public Control.Lens.Market
import public Control.Lens.Iso
import public Control.Lens.Lens
import public Control.Monad.Identity
import public Data.Bifunctor
import public Data.Bitraversable
import public Data.Contravariant
import public Data.Curried
import public Data.Profunctor
import public Data.Tagged
import public Data.Yoneda
-- --------------------------------------------------------------------- [ EOF ]
|
#' Evaluate Function Calls on HPC Schedulers (LSF, SGE, SLURM)
#'
#' Provides the \code{Q} function to send arbitrary function calls to
#' workers on HPC schedulers without relying on network-mounted storage.
#' Allows using remote schedulers via SSH.
#'
#' Under the hood, this will submit a cluster job that connects to the master
#' via TCP the master will then send the function and argument chunks to the
#' worker and the worker will return the results to the master until everything
#' is done and you get back your result
#'
#' Computations are done entirely on the network and without any temporary
#' files on network-mounted storage, so there is no strain on the file system
#' apart from starting up R once per job. This removes the biggest bottleneck
#' in distributed computing.
#'
#' Using this approach, we can easily do load-balancing, i.e. workers that get
#' their jobs done faster will also receive more function calls to work on. This
#' is especially useful if not all calls return after the same time, or one
#' worker has a high load.
#'
#' For more detailed usage instructions, see the documentation of the \code{Q}
#' function.
#'
#' @name clustermq
#' @docType package
#' @useDynLib clustermq
#' @import Rcpp
NULL
|
import torch
import torch.optim as optim
from torch.autograd import Variable
import numpy as np
from rllab.misc.overrides import overrides
from pytorchrl.reward_functions.airl_discriminator import AIRLDiscriminator
from pytorchrl.irl.fusion_manager import RamFusionDistr
from pytorchrl.irl.imitation_learning import SingleTimestepIRL
from pytorchrl.misc.utils import TrainingIterator
class AIRL(SingleTimestepIRL):
"""
Adversarial Inverse Reinforcement Learning
Similar to GAN_GCL except operates on single timesteps.
"""
def __init__(
self,
env_spec,
expert_trajs=None,
discriminator_class=AIRLDiscriminator,
discriminator_args={},
optimizer_class=optim.Adam,
discriminator_lr=1e-3,
l2_reg=0,
discount=1.0,
fusion=False,
):
"""
Parameters
----------
env_spec (): Environment
expert_trajs (): The demonstration from experts, the trajectories sampled from
experts policy, positive samples used to train discriminator
discriminator_class (): Discriminator class
optimizer_class (): Optimizer class
discrmininator (float): learning rate for discriminator
discriminator_args (dict): dict of arguments for discriminator
l2_reg (float): L2 penalty for discriminator parameters
discount (float): discount rate for reward
fusion (boolean): whether use trajectories from old iterations to train.
"""
super(AIRL, self).__init__()
self.obs_dim = env_spec.observation_space.flat_dim
self.action_dim = env_spec.action_space.flat_dim
# Get expert's trajectories
self.expert_trajs = expert_trajs
# expert_trajs_extracted will be a single matrix with N * dim
# where N is the total sample number, and dim is the dimension of
# action or state
self.expert_trajs_extracted = self.extract_paths(expert_trajs)
# Build energy model
self.discriminator = discriminator_class(
self.obs_dim, self.action_dim, **discriminator_args)
self.optimizer = optimizer_class(self.discriminator.parameters(),
lr=discriminator_lr, weight_decay=l2_reg)
if fusion:
self.fusion = RamFusionDistr(100, subsample_ratio=0.5)
else:
self.fusion = None
def fit(self, trajs, policy=None, batch_size=32, max_itrs=100, logger=None, **kwargs):
"""
Train the AIRL Discriminator to distinguish expert from learner.
Parameters
----------
trajs (list): trajectories sample from current policy
batch_size (integer): How many positive sample or negative samples
max_iters (integer): max iteration number for training discriminator
kwargs (dict):
Returns
-------
mean_loss (numpy.ndarray): A scalar indicate the average discriminator
loss (Binary Cross Entropy Loss) of total max_iters iterations
"""
if self.fusion is not None:
# Get old trajectories
old_trajs = self.fusion.sample_paths(n=len(trajs))
# Add new trajectories for future use
self.fusion.add_paths(trajs)
# Mix old and new trajectories
trajs = trajs + old_trajs
# Eval the prob of the trajectories under current policy
# The result will be fill in part of the discriminator
self.eval_trajectory_probs(trajs, policy, insert=True)
self.eval_trajectory_probs(self.expert_trajs, policy, insert=True)
obs, acts, trajs_probs = self.extract_paths(trajs, keys=('observations', 'actions', 'a_logprobs'))
expert_obs, expert_acts, expert_probs = self.extract_paths(self.expert_trajs, keys=('observations', 'actions', 'a_logprobs'))
# Train discriminator
for it in TrainingIterator(max_itrs, heartbeat=5):
# lprobs_batch is the prob of obs and act under current policy
obs_batch, act_batch, lprobs_batch = \
self.sample_batch(obs, acts, trajs_probs, batch_size=batch_size)
# expert_lprobs_batch is the experts' obs and act under current policy
expert_obs_batch, expert_act_batch, expert_lprobs_batch = \
self.sample_batch(expert_obs, expert_acts, expert_probs, batch_size=batch_size)
labels = np.zeros((batch_size*2, 1))
labels[batch_size:] = 1.0
obs_batch = np.concatenate([obs_batch, expert_obs_batch], axis=0)
act_batch = np.concatenate([act_batch, expert_act_batch], axis=0)
# obs_batch is of size N * obs_dim, act_batch is of size N * act_dim
# where N is the batch size. However, lprobs_batch if of size N.
# Thus, we need to use expand_dims to reshape it to N * 1
lprobs_batch = np.expand_dims(
np.concatenate([lprobs_batch, expert_lprobs_batch], axis=0),
axis=1).astype(np.float32)
obs_var = Variable(torch.from_numpy(obs_batch)).type(torch.FloatTensor)
act_var = Variable(torch.from_numpy(act_batch)).type(torch.FloatTensor)
label_var = Variable(torch.from_numpy(labels)).type(torch.FloatTensor)
lprobs_var = Variable(torch.from_numpy(lprobs_batch)).type(torch.FloatTensor)
loss = self.discriminator(obs_var, act_var, lprobs_var, label_var)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
it.record('loss', loss.data.numpy())
if it.heartbeat:
print(it.itr_message())
mean_loss = it.pop_mean('loss')
print('\tLoss:%f' % mean_loss)
if logger:
reward = self.discriminator.prediction(obs, acts)
logger.record_tabular('IRLAverageReward', np.mean(reward))
logger.record_tabular('IRLAverageLogQtau', np.mean(trajs_probs))
logger.record_tabular('IRLMedianLogQtau', np.median(trajs_probs))
reward = self.discriminator.prediction(expert_obs, expert_acts)
logger.record_tabular('IRLAverageExpertReward', np.mean(reward))
logger.record_tabular('IRLAverageExpertLogQtau', np.mean(expert_probs))
logger.record_tabular('IRLMedianExpertLogQtau', np.median(expert_probs))
return mean_loss
def eval(self, paths, **kwargs):
"""
Return the estimate reward of the paths.
Parameters
----------
paths (list): See doc of eval_trajectory_probs method
Returns
-------
rewards (list): estimated reward arrange according to unpack method.
"""
obs, acts = self.extract_paths(paths)
rewards = self.discriminator.prediction(obs, acts)
rewards = rewards[:,0]
return self.unpack(rewards, paths)
def eval_trajectory_probs(self, paths, policy, insert=False):
"""
Evaluate probability of paths under current policy
Parameters
----------
paths (list): Each element is a dict. Each dict represent a whole
trajectory, contains observations, actions, rewards, env_infos,
agent_infos. observations and actions is of size T * dim, where T
is the length of the trajectory, and dim is the dimension of observation
or action. rewards is a vector of length T. agent_infos contains other
information about the policy. For example, when we have a Gaussian policy,
it may contain the means and log_stds of the Gaussian policy at each step.
policy (pytorchrl.policies.base.Policy): policy object used to evaluate
the probabilities of trajectories.
insert (boolean): Whether to insert the action probabilities back into
the paths
"""
for path in paths:
actions, agent_infos = policy.get_actions(path['observations'])
path['agent_infos'] = agent_infos
return self.compute_path_probs(paths, insert=insert)
@overrides
def get_params(self):
"""
Get the value of the model parameters in one flat Tensor
Returns
-------
params (torch.Tensor): A torch Tensor contains the parameter of
the module.
"""
return self.discriminator.get_param_values()
@overrides
def set_params(self, params):
"""
Set the value of model parameter using parameters.
Parameters
----------
params (torch.Tensor): A tensors, this new_parameters should
have the same format as the return value of get_param_values
method.
"""
self.discriminator.set_param_values(params)
|
(* Title: HOL/Auth/n_flash_lemma_on_inv__31.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_flash Protocol Case Study*}
theory n_flash_lemma_on_inv__31 imports n_flash_base
begin
section{*All lemmas on causal relation between inv__31 and some rule r*}
lemma n_PI_Remote_GetVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_PutXVsinv__31:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_PI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_ReplaceVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Replace src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__31:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__31:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__31:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_Put_HomeVsinv__31:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__31:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__31:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''HomeShrSet'')) (Const true)))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__31:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Dirty'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__31:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Local'')) (Const true))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__31:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__31:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') dst) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__31:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__31:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))\<or>((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))" by auto
moreover {
assume c1: "((formEval (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true)) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume c1: "((formEval (neg (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''InvMarked'')) (Const true))) s))"
have "?P1 s"
proof(cut_tac a1 a2 b1 c1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately have "invHoldForRule s f r (invariants N)" by satx
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__31:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_InvVsinv__31:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Inv dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__31 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Local_GetX_PutX__part__0Vsinv__31:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__31:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__31:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__31:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__31:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__31:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__31:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__31:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__31:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__31:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__31:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__31:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ShWbVsinv__31:
assumes a1: "r=n_NI_ShWb N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__31:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__31:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__31:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__31:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__31:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__31:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__31:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__31:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__31:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__31:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__31:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__31:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__31:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__31:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_FAckVsinv__31:
assumes a1: "r=n_NI_FAck " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__31 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
State Before: α : Type u
β : Type u_1
γ : Type u_2
δ : Type ?u.19964
ε : Type ?u.19967
f : α → β → γ
i : ℕ
l : List α
l' : List β
h : i < length (zipWith f l l')
⊢ i < length l' State After: α : Type u
β : Type u_1
γ : Type u_2
δ : Type ?u.19964
ε : Type ?u.19967
f : α → β → γ
i : ℕ
l : List α
l' : List β
h : i < length l ∧ i < length l'
⊢ i < length l' Tactic: rw [length_zipWith, lt_min_iff] at h State Before: α : Type u
β : Type u_1
γ : Type u_2
δ : Type ?u.19964
ε : Type ?u.19967
f : α → β → γ
i : ℕ
l : List α
l' : List β
h : i < length l ∧ i < length l'
⊢ i < length l' State After: no goals Tactic: exact h.right |
from stn import STN, loadSTNfromJSONfile
from LP import *
from relax import *
from util import *
from dispatch import *
from probability import *
import matplotlib.pyplot as plt
from scipy.stats import norm
import numpy as np
import glob
import json
import os
import random
import math
##
# \file empirical.py
# \brief perform empirical analysis on degree of controllability metrics.
# -------------------------------------------------------------------------
# Generating Results
# -------------------------------------------------------------------------
def generate_DDC_result(data_path, sim_num, out_name, gauss, relaxed):
data_list = glob.glob(os.path.join(data_path, '*.json'))
result = {}
for data in data_list:
dispatch = simulate_file(data, sim_num, False, gauss, relaxed)
ddc = prob_of_DC_file(data, gauss)
path, name = os.path.split(data)
result[name] = [ddc, dispatch]
#return result
# Save the results
with open(out_name, 'w') as f:
json.dump(result, f)
def generate_result_relax(data_path, out_name):
data_list = glob.glob(os.path.join(data_path, '*.json'))
result = {}
for data in data_list:
STN = loadSTNfromJSONfile(data)
_, count, _, _ = relaxSearch(STN)
path, name = os.path.split(data)
result[name] = count
# return result
# Save the results
with open(out_name, 'w') as f:
json.dump(result, f)
def compute_corr(values:dict):
pairs = list(values.items())
x_vals = [x[1][0] for x in pairs]
y_vals = [x[1][1] for x in pairs]
return np.corrcoef(x_vals,y_vals)
def identify_outliers(values:dict, threshold):
pairs = list(values.items())
x_vals = [x[1][0] for x in pairs]
y_vals = [x[1][1] for x in pairs]
outliers = []
for i in range(len(x_vals)):
if abs(x_vals[i] - y_vals[i]) > threshold:
outliers.append(pairs[i])
return outliers
def plot_from_dict(values:dict):
pairs = list(values.items())
x_vals = [x[1][0] for x in pairs]
y_vals = [x[1][1] for x in pairs]
plt.scatter(x_vals,y_vals)
plt.xlabel("Degree of Controllability")
plt.ylabel("Success Rate")
plt.xticks(np.arange(0, 1, step=0.2))
plt.show()
def sample_from_folder(folder_name, gauss=False, success='default', LP='original'):
results = {}
for filename in os.listdir(folder_name):
print(filename)
STN = loadSTNfromJSONfile(folder_name + filename)
degree, success_rate = sample(STN, success, LP, gauss)
results[filename] = (degree, success_rate)
return results
# -------------------------------------------------------------------------
# Strong controllability
# -------------------------------------------------------------------------
##
# \fn newInterval(STN, epsilons)
# \brief compute shrinked contingent intervals
#
# @param STN an input STN
# @param epsilons a dictionary of epsilons returned by our LP
#
# @return Return a list of original contingent intervals and a list of shrinked
# contingent intervals
def newInterval(STN, epsilons):
original = []
shrinked = []
for edge in list(STN.contingentEdges.values()):
orig = (-edge.Cji, edge.Cij)
original.append(orig)
low, high = epsilons[(edge.j, '-')].varValue, epsilons[(edge.j, '+')].varValue
new = (-edge.Cji+low, edge.Cij-high)
shrinked.append(new)
return original, shrinked
##
# \fn calculateMetric(original, shrinked)
# \brief Compute our degree of strong controllability
#
# @param original A list of original contingent intervals
# @param shrinked A list of shrinked contingent intervals
#
# @return the value of degree of strong controllability
def calculateMetric(original, shrinked, gauss=False):
if not gauss:
orig = 1
new = 1
for i in range(len(original)):
x, y = original[i]
orig *= y-x
a, b = shrinked[i]
new *= b-a
return new, orig, float(new/orig)
else:
total = 1
for i in range(len(original)):
x, y = original[i]
mean = (x + y)/2
sd = (y - mean)/2
a, b = shrinked[i]
prob_contained = norm.cdf(b, mean, sd) - norm.cdf(a, mean, sd)
total *= prob_contained
return total
##
# \fn scheduleIsValid(network: STN, schedule: dict) -> STN
# \brief Given an STNU and schedule, checks if the schedule is valid or not.
#
# @param network An input STNU
#
# @param schedule A dictionary whose keys are vertex IDs and whose values
# are the times selected for those events.
#
# @return True/False if the schedule is valid/invalid.
def scheduleIsValid(network: STN, schedule: dict) -> STN:
## Check that the schedule is actually defined on all relevant vertices
# This number is arbitrary - any sufficiently small, positive constant works
epsilon = 0.001
vertices = network.getAllVerts()
for vertex in vertices:
vertexID = vertex.nodeID
assert vertexID in schedule
# Check that the schedule is valid
edges = network.getAllEdges()
for edge in edges:
# Loop through the constraints
start = edge.i
fin = edge.j
uBound = edge.Cij
lBound = -edge.Cji
boundedAbove = (schedule[fin] - schedule[start]) <= uBound + epsilon
boundedBelow = (schedule[fin] - schedule[start]) >= lBound - epsilon
# Check if constraint is not satisfied
if ((not boundedAbove) or (not boundedBelow)):
return False
return True
# -------------------------------------------------------------------------
# Sample to get success rate
# -------------------------------------------------------------------------
##
# \fn sampleOnce(original, shrinked)
# \brief Check whether a randomly generated realization is inside strong
# controllable region
#
# @param original A list of original contingent intervals
# @param shrinked A list of shrinked contingent intervals
#
# @return Return True if the random realization falls into the strongly
# controllable region. Return False otherwise
def sampleOnce(original, shrinked, gauss=False):
for i in range(len(original)):
x,y = original[i]
a,b = shrinked[i]
if not gauss:
real = random.uniform(x, y)
else:
real = random.normalvariate((x+y)/2, (y-x)/4)
if real < a or real > b:
return False
return True
##
# \fn getSchedule(STN, schedule)
# \brief Construct a possible schedule for an STN given a fixed decision
#
# @param STN An STNU we want to test
# @param schedule A dictionary with the fixed decision
#
# @return a schedule for the given STNU
def getSchedule(STN, schedule, gauss):
for edge in list(STN.contingentEdges.values()):
start_time = schedule[edge.i]
x = -edge.Cji
y = edge.Cij
if gauss:
real = random.normalvariate((x+y)/2, (y-x)/4)
else:
real = random.uniform(x, y)
time = start_time + real
schedule[edge.j] = time
return schedule
##
# \fn altSampleOnce(STN, schedule)
# \brief Another strategy of sampling to test strong controllability
#
# @param STN An STNU we want to test
# @param schedule A dictionary with the fixed decision
#
# @return Return True if the schedule generate is valid. Return False otherwise
def altSampleOnce(STN, schedule, gauss):
s = getSchedule(STN, schedule, gauss)
if scheduleIsValid(STN, s):
return True
return False
##
# \fn sample(STN, success='default', LP='original')
# \brief Compute the success rate of an STNU by randomly sample 50000 times
#
# \note There are three kinds of LPs we can use to compute the amount of
# uncertainty removed from each contingent interval
#
# @param STN An STN to test
# @param LP The type of LP we want to use
#
# @return The degree of controllability and the success rate for input STN
def sample(STN, success='default', LP='original', gauss=False):
if LP == 'original':
_, bounds, epsilons = originalLP(STN.copy(), naiveObj=False)
elif LP == 'proportion':
_, _, bounds, epsilons = proportionLP(STN.copy())
else:
_, _, bounds, epsilons = maxminLP(STN.copy())
original, shrinked = newInterval(STN, epsilons)
if not gauss:
degree = calculateMetric(original, shrinked)[2]
else:
degree = calculateMetric(original, shrinked, gauss)
schedule = {}
for i in list(STN.verts.keys()):
if i not in STN.uncontrollables:
time = (bounds[(i, '-')].varValue + bounds[(i, '+')].varValue)/2
schedule[i] = time
# Collect the sample data.
count = 0
for i in range(10000):
if success=='default':
result = sampleOnce(original, shrinked, gauss)
else:
result = altSampleOnce(STN, schedule.copy(), gauss)
if result:
count += 1
success = float(count/10000)
return degree, success
##
# \fn sampleAll(listOfFile, success='default', LP='original')
# \brief Compute the success rate for a list of STNUs
#
# @param STN An STN to test
# @param LP The type of LP we want to use
#
# @return a list of (degree, success) tuple for STNUs in the list
def sampleAll(listOfFile, success='default', LP='original'):
result = {}
for fname in listOfFile:
p, f = os.path.split(fname)
print("Processing file: ", f)
STN = loadSTNfromJSONfile(fname)
degree, success = sample(STN, success=success, LP=LP)
result[f] = (degree, success)
return result
# ---------------------------------
# Analyze result from the solver
# ---------------------------------
##
# \fn actual_vol(result_name)
# \brief Calculate the actual volume from solver's result
#
# @param result_name The path to json file that contains solver's result
#
# @return A dictionary in which keys are the name of the network and values are
# the maximized volume that guarantees strong controllability
def actual_vol(result_name):
with open(result_name, 'r') as f:
result = json.loads(f.read())
actual_Dict = {}
for x in list(result.keys()):
v = result[x]
actual = math.exp(v)
actual_Dict[x] = actual
return actual_Dict
##
# \fn compare(actual_Dict)
# \brief Compute the actual and approximated degree of strong controllability
#
# @param actual_Dict A dictionary containing actual volume
#
# @return A dictionary in which keys are the name of the network and values are
# (approximation, actual degree)
def compare(actual_Dict):
dynamic_folder = input("Please input directory with DC STNUs:\n")
uncertain_folder = input("Please input directory with uncertain STNUs:\n")
compare_Dict = {}
for x in list(actual_Dict.keys()):
actual_volume = actual_Dict[x]
if x[:7] == 'dynamic':
fname = os.path.join(dynamic_folder, x + '.json')
else:
fname = os.path.join(uncertain_folder, x + '.json')
STN = loadSTNfromJSONfile(fname)
_, _, epsilons = originalLP(STN.copy())
original, shrinked = newInterval(STN, epsilons)
old, new, degree = calculateMetric(original, shrinked)
actual = float(actual_volume / old)
compare_Dict[x] = (degree, actual)
return compare_Dict
def plot():
# Plot actual vs approximated
result_name = input("Please input path to result json file: \n")
actual_Dict = actual_vol(result_name)
compare_Dict = compare(actual_Dict)
L = list(compare_Dict.values())
x = [d[0] for d in L]
y = [d[1] for d in L]
plt.plot(x,y,'o')
plt.xlim(-0.04, 1.04)
plt.ylim(-0.04, 1.04)
plt.xlabel('Approximated degree of strong controllability')
plt.ylabel('Actual degree of strong controllability')
plt.title('Accuracy of Approximation Using DSC LP')
out_folder = input("Please input the output directory:\n")
fname = os.path.join(out_folder, 'accuracy.png')
plt.savefig(fname, format='png')
plt.close()
# Plot success rate
dynamic_folder = input("Please input directory with DC STNUs:\n")
uncertain_folder = input("Please input directory with uncertain STNUs:\n")
listOfFile = []
listOfFile += glob.glob(os.path.join(dynamic_folder, '*.json'))
listOfFile += glob.glob(os.path.join(uncertain_folder, '*.json'))
resultD_1= sampleAll(listOfFile, success='new')
result_1 = list(resultD_1.values())
x_1 = [d[0] for d in result_1]
y_1 = [d[1] for d in result_1]
plt.plot(x_1, y_1, 'o')
plt.xlim(-0.04, 1.04)
plt.ylim(-0.04, 1.04)
plt.xlabel("Approximated degree of strong controllability")
plt.ylabel("Probabiliy of success")
plt.title("Success rate of ...")
out_folder = input("Please input the output directory:\n")
fname = os.path.join(out_folder, 'success_rate.png')
plt.savefig(fname, format='png')
plt.close()
# -------------------------------------------------------------------------
# Dynamic controllability
# -------------------------------------------------------------------------
##
# \fn dynamicMetric(STN, new_STN)
# \brief compute the degree of controllability
#
# @param STN An input STNU
# @param new_STN Original STNU with contingent intervals shrinked to be DC
#
# @return degree of dynamic controllability
def dynamicMetric(STN, new_STN):
original = [(-e.Cji, e.Cij) for e in list(STN.contingentEdges.values())]
shrinked = [(-e.Cji, e.Cij) for e in list(new_STN.contingentEdges.values())]
return calculateMetric(original, shrinked)
##
# \fn computeDynamic(nlp=True)
# \brief compute degree of controllability for all uncontrollable STNUs we have
#
# @param nlp Flag indicating whether we want to use NLP
#
# @return A dictionary in which keys are names of the STNU json file and value
# is the degree of controllability
def computeDynamic(nlp=False):
uncertain_folder = input("Please input uncertain STNUs folder:\n")
chain_folder = input("Please input chain STNUs folde:\n")
listOfFile = []
listOfFile += glob.glob(os.path.join(uncertain_folder, '*.json'))
listOfFile += glob.glob(os.path.join(chain_folder, '*.json'))
degree = {}
for fname in listOfFile:
p, f = os.path.split(fname)
print("Processing: ", f)
STN = loadSTNfromJSONfile(fname)
new_STN, count = relaxSearch(STN.copy(), nlp=nlp)
if not new_STN:
degree[f] = 0
else:
degree[f] = dynamicMetric(STN.copy(), new_STN.copy())[2]
return degree
##
# \fn generateData(num)
# \brief generate uncontrollable STNUs with decent degree of dynamic
# controllability
#
# @param num number of STNUs we want to generate
def generateData(num):
data_folder = input("Please input destination directory:\n")
while num != 0:
new = generateChain(50, 2500)
result, conflicts, bounds, weight = DC_Checker(new.copy(), report=False)
if result:
print("Failed. Dynamically controllable...")
continue
new_STN, count = relaxSearch(new.copy(), nlp=False)
if not new_STN:
print("Failed. Not able to resolve conflict...")
continue
degree = dynamicMetric(new.copy(), new_STN.copy())[2]
if degree >= 0.2:
fname = 'new' + str(num) + '.json'
print("\nGENERATED ONE SUCCESSFUL CHAIN!!!!!!\n")
new.toJSON(fname, data_folder)
num -= 1
else:
print("Failed. Degree is too small....")
##
# \fn readNeos(filename, json_folder)
# \brief compute degree of dynamic controllability from the output file of
# Neos Server
#
# @param filename The name of the input txt file
# @json_folder The directory containing STNUs we generated
#
# @return an STNU's volume of Omega and Omega' and the computed degree of DC
def readNeos(filename, json_folder):
f = open(filename, 'r')
for i in range(3):
line = f.readline()
obj_value = float(line[17:])
actual = math.exp(obj_value)
p, f = os.path.split(filename)
fname = f[:-4] + '.json'
json_file = os.path.join(json_folder, fname)
STN = loadSTNfromJSONfile(json_file)
result, conflicts, bounds, weight = DC_Checker(STN.copy(), report=False)
contingent = bounds['contingent']
total = 1
for (i,j) in list(STN.contingentEdges.keys()):
edge = STN.contingentEdges[(i,j)]
length = edge.Cij + edge.Cji
total *= length
if (i,j) not in contingent:
actual *= length
return actual, total, float(actual/total)
##
# \fn processNeos()
# \brief compute degree of dynamic controllability from the output file of
# Neos Server for all new chains we generated
#
# @return A dictionary of dictionary with information about an STNU's
# volume of Omega and Omega', and the computed degree of DC
def processNeos():
txt_folder = input("Please input folder with txt Neos file:\n")
json_folder = input("Please input folder with json file:\n")
result = {}
text_L = glob.glob(os.path.join(txt_folder, '*.txt'))
for filename in text_L:
p, f = os.path.split(filename)
fname = f[:-4] + '.json'
print("Processing: ", fname)
new, orig, degree = readNeos(filename, json_folder)
result[fname] = {}
result[fname]['shrinked'] = new
result[fname]['original'] = orig
result[fname]['degree'] = degree
output_folder = input("Please input output folder:\n")
filename = os.path.join(output_folder, 'result_neos.json')
with open(filename, 'w') as f:
json.dump(result, f)
return result
##
# \fn processOptimal()
# \brief compute degree of dynamic controllability using the optimal solution
# for all new chains we generated
#
# @return A dictionary of dictionary with information about an STNU's
# volume of Omega and Omega', and the computed degree of DC
def processOptimal():
json_folder = input("Please input folder with json file:\n")
json_list = glob.glob(os.path.join(json_folder, '*.json'))
result = {}
for fname in json_list:
p, f = os.path.split(fname)
print("Processing: ", f)
STN = loadSTNfromJSONfile(fname)
new_STN, count = relaxSearch(STN.copy())
new, orig, degree = dynamicMetric(STN.copy(), new_STN.copy())
result[f] = {}
result[f]['shrinked'] = new
result[f]['original'] = orig
result[f]['degree'] = degree
output_folder = input("Please input output folder:\n")
filename = os.path.join(output_folder, 'result_optimal.json')
with open(filename, 'w') as f:
json.dump(result, f)
return result
# -------------------------------------------------------------------------
# Generate STNU
# -------------------------------------------------------------------------
##
# \fn generateChain(task, free)
# \brief generate a consistent STNUs in a chainlike structure
#
# \details The chainlike STNU is very common in real life application, such as
# AUV need to drive to different sites and complete task at each site.
# Driving to different cite is contingent, but the agent can decide
# how long it takes to complete the task.
#
# @param task The number of tasks need to be completed
# @param free The total length of the free constraint intervals we want
# in the generated STNU
#
# @return Return the generated STNU
def generateChain(task, free):
totalEvent = 2 * (task+1)
while True:
new = STN()
for i in range(totalEvent):
new.addVertex(i)
L = [random.randint(0, 100) for i in range(task)]
s = sum(L)
L = [int(x/s*free) for x in L]
diff = free - sum(L)
L[-1] += diff
bounds = []
for i in range(totalEvent-1):
type = 'stcu' if i % 2==0 else 'stc'
if type == 'stcu':
lowBound = random.randint(0,50)
length = random.randint(1,50)
bounds.append((lowBound, lowBound+length))
new.addEdge(i, i+1, lowBound, lowBound+length, type='stcu')
else:
lowBound = random.randint(0,100)
length = L[int((i-1)/2)]
bounds.append((lowBound, lowBound+length))
new.addEdge(i, i+1, lowBound, lowBound+length)
low = sum([x[0] for x in bounds])
high = sum([x[1] for x in bounds])
S = sum([e.Cij+e.Cji for e in list(new.contingentEdges.values())])
# makespan = random.randint(int(0.5*low), low)
makespan = low + int(0.6*S)
print(low, makespan, high)
new.addEdge(0,task*2+1, 0, makespan)
if new.isConsistent():
return new
def generateParallelChain(agent, task):
total_event = ((2 * task) + 1) * agent + 1
while True:
new = STN()
new.addVertex(0)
for i in range(total_event):
new.addVertex(i+1)
contingent = True
for i in range(agent):
start = ((2 * task) + 1) * i + 1
end = ((2 * task) + 1) * (i + 1)
new.addEdge(0, start, 0, 15)
for j in range(start, end):
type = 'stcu' if contingent else 'stc'
contingent = not contingent
if type == 'stcu':
# low = round(random.uniform(10, 20), 2)
# high = round(random.uniform(30, 40), 2)
low = random.randint(10, 20)
high = random.randint(30, 40)
new.addEdge(j, j+1, low, high, type='stcu')
else:
# low = round(random.uniform(5, 10), 2)
# high = round(random.uniform(30, 35), 2)
low = random.randint(5, 10)
high = random.randint(35, 40)
new.addEdge(j, j+1, low, high)
new.addEdge(end, total_event, -10, 10)
num_activity = (2 * task) + 1
max_length = max([e.Cij + e.Cji for e in list(new.edges.values())])
up_bound = max_length * num_activity
# low = round(random.uniform(0.35*up_bound, 0.45*up_bound), 2)
# high = round(random.uniform(0.5*up_bound, 0.6*up_bound), 2)
low = random.randint(int(0.45*up_bound), int(0.53*up_bound))
high = random.randint(int(0.55*up_bound), int(0.65*up_bound))
new.addEdge(0, total_event, low, high)
print("\n\nChecking consistensy...")
if not new.isConsistent():
continue
print("Checking Dynamic Controllability...")
try:
result, conflicts, bounds, weight = DC_Checker(new.copy(), report=False)
except Exception:
continue
if result:
return new
# -------------------------------------------------------------------------
# Main function
# -------------------------------------------------------------------------
if __name__ == '__main__':
#plot()
print("ran") |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Statistics.Distribution.Beta
-- Copyright : (C) 2012 Edward Kmett,
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : DeriveDataTypeable
--
----------------------------------------------------------------------------
module Statistics.Distribution.Beta
( BetaDistribution
-- * Constructor
, betaDistr
, betaDistrE
, improperBetaDistr
, improperBetaDistrE
-- * Accessors
, bdAlpha
, bdBeta
) where
import Control.Applicative
import Data.Aeson (FromJSON(..), ToJSON, Value(..), (.:))
import Data.Binary (Binary(..))
import Data.Data (Data, Typeable)
import GHC.Generics (Generic)
import Numeric.SpecFunctions (
incompleteBeta, invIncompleteBeta, logBeta, digamma, log1p)
import Numeric.MathFunctions.Constants (m_NaN,m_neg_inf)
import qualified Statistics.Distribution as D
import Statistics.Internal
-- | The beta distribution
data BetaDistribution = BD
{ bdAlpha :: {-# UNPACK #-} !Double
-- ^ Alpha shape parameter
, bdBeta :: {-# UNPACK #-} !Double
-- ^ Beta shape parameter
} deriving (Eq, Typeable, Data, Generic)
instance Show BetaDistribution where
showsPrec n (BD a b) = defaultShow2 "improperBetaDistr" a b n
instance Read BetaDistribution where
readPrec = defaultReadPrecM2 "improperBetaDistr" improperBetaDistrE
instance ToJSON BetaDistribution
instance FromJSON BetaDistribution where
parseJSON (Object v) = do
a <- v .: "bdAlpha"
b <- v .: "bdBeta"
maybe (fail $ errMsgI a b) return $ improperBetaDistrE a b
parseJSON _ = empty
instance Binary BetaDistribution where
put (BD a b) = put a >> put b
get = do
a <- get
b <- get
maybe (fail $ errMsgI a b) return $ improperBetaDistrE a b
-- | Create beta distribution. Both shape parameters must be positive.
betaDistr :: Double -- ^ Shape parameter alpha
-> Double -- ^ Shape parameter beta
-> BetaDistribution
betaDistr a b = maybe (error $ errMsg a b) id $ betaDistrE a b
-- | Create beta distribution. Both shape parameters must be positive.
betaDistrE :: Double -- ^ Shape parameter alpha
-> Double -- ^ Shape parameter beta
-> Maybe BetaDistribution
betaDistrE a b
| a > 0 && b > 0 = Just (BD a b)
| otherwise = Nothing
errMsg :: Double -> Double -> String
errMsg a b = "Statistics.Distribution.Beta.betaDistr: "
++ "shape parameters must be positive. Got a = "
++ show a
++ " b = "
++ show b
-- | Create beta distribution. Both shape parameters must be
-- non-negative. So it allows to construct improper beta distribution
-- which could be used as improper prior.
improperBetaDistr :: Double -- ^ Shape parameter alpha
-> Double -- ^ Shape parameter beta
-> BetaDistribution
improperBetaDistr a b
= maybe (error $ errMsgI a b) id $ improperBetaDistrE a b
-- | Create beta distribution. Both shape parameters must be
-- non-negative. So it allows to construct improper beta distribution
-- which could be used as improper prior.
improperBetaDistrE :: Double -- ^ Shape parameter alpha
-> Double -- ^ Shape parameter beta
-> Maybe BetaDistribution
improperBetaDistrE a b
| a >= 0 && b >= 0 = Just (BD a b)
| otherwise = Nothing
errMsgI :: Double -> Double -> String
errMsgI a b
= "Statistics.Distribution.Beta.betaDistr: "
++ "shape parameters must be non-negative. Got a = " ++ show a
++ " b = " ++ show b
instance D.Distribution BetaDistribution where
cumulative (BD a b) x
| x <= 0 = 0
| x >= 1 = 1
| otherwise = incompleteBeta a b x
complCumulative (BD a b) x
| x <= 0 = 1
| x >= 1 = 0
-- For small x we use direct computation to avoid precision loss
-- when computing (1-x)
| x < 0.5 = 1 - incompleteBeta a b x
-- Otherwise we use property of incomplete beta:
-- > I(x,a,b) = 1 - I(1-x,b,a)
| otherwise = incompleteBeta b a (1-x)
instance D.Mean BetaDistribution where
mean (BD a b) = a / (a + b)
instance D.MaybeMean BetaDistribution where
maybeMean = Just . D.mean
instance D.Variance BetaDistribution where
variance (BD a b) = a*b / (apb*apb*(apb+1))
where apb = a + b
instance D.MaybeVariance BetaDistribution where
maybeVariance = Just . D.variance
instance D.Entropy BetaDistribution where
entropy (BD a b) =
logBeta a b
- (a-1) * digamma a
- (b-1) * digamma b
+ (a+b-2) * digamma (a+b)
instance D.MaybeEntropy BetaDistribution where
maybeEntropy = Just . D.entropy
instance D.ContDistr BetaDistribution where
density (BD a b) x
| a <= 0 || b <= 0 = m_NaN
| x <= 0 = 0
| x >= 1 = 0
| otherwise = exp $ (a-1)*log x + (b-1) * log1p (-x) - logBeta a b
logDensity (BD a b) x
| a <= 0 || b <= 0 = m_NaN
| x <= 0 = m_neg_inf
| x >= 1 = m_neg_inf
| otherwise = (a-1)*log x + (b-1)*log1p (-x) - logBeta a b
quantile (BD a b) p
| p == 0 = 0
| p == 1 = 1
| p > 0 && p < 1 = invIncompleteBeta a b p
| otherwise =
error $ "Statistics.Distribution.Gamma.quantile: p must be in [0,1] range. Got: "++show p
instance D.ContGen BetaDistribution where
genContVar = D.genContinuous
|
If $c \neq 0$, then the order of the monomial $cx^n$ is $n$. |
#include <boost/mpl/aux_/push_back_impl.hpp>
|
#' hot.to.df
#'
#' Converts the table data passed from the client-side into a data.frame
#'
#' @param b The input$hotable_id value.
#'
#' @export
hot.to.df <- function(b) {
# if theres is no data
if (length(b$data) == 0)
return()
col.names <- unlist(b$colHeaders)
i = 0
f <- function(x) {
i <<- i + 1
#
null.pos <- sapply(x,is.null)
x[null.pos] <- NA
xx <- data.frame(x, stringsAsFactors = F)
colnames(xx) <- col.names
xx
}
bb <- ldply(b$data, f)
colnames(bb) <- col.names
bb
}
#' hotable
#'
#' Creates a hotable (handsontable)
#'
#' @param id The id used to refer to the table input$id or output$id
#'
#' @export
hotable <- function(id) {
tagList(
singleton(tags$head(tags$link(href = "shinysky/handsontable/0.10.3/jquery.handsontable.full.css", rel = "stylesheet"))),
singleton(tags$head(tags$script(src = "shinysky/handsontable/0.10.3/jquery.handsontable.full.js"))),
singleton(tags$head(tags$script(src = "shinysky/hotable.js"))),
div(id = id, class = "hotable")
)
}
#' renderHotable
#'
#' Renders the hotable.
#'
#' @param expr The computation that leads to an output
#' @param env The R environment in which to create the dataset
#' @param quoted Pass to the exprToFunction
#' @param options Pass to the exprToFunction
#' @param readOnly A vector of TRUE/FALSE values to indicate which of the
#' columns should be readonly.
#'
#' @export
renderHotable <- function(expr, env = parent.frame(), quoted = FALSE,
options = NULL, readOnly = TRUE) {
func <- shiny::exprToFunction(expr, env, quoted)
function() {
df <- func() # the dataframe returned
if (is.null(df)) {
return()
}
if (nrow(df) == 0) {
return()
}
json <- NULL
json$colHeaders <- colnames(df)
columns <- NULL
types <- sapply(df, typeof)
l <- length(types)
readOnly <- rep(readOnly,length.out = l)
for (i in 1:l) {
if (i == 1) {
columns[[i]] <- list(readOnly = readOnly[i])
} else if (types[i] == "double") {
columns[[i]] <- list(type = "numeric", format = "0,0.00", readOnly = readOnly[i])
} else if (types[i] == "logical") {
columns[[i]] <- list(type = "checkbox", readOnly = readOnly[i])
} else {
columns[[i]] <- list(readOnly = readOnly[i])
}
}
json$columns <- columns
json$data <- df
json
}
}
|
module Control.Kan
||| left kan extension
data Lan : (Type -> Type) -> Type -> Type where
FMap : (x -> a) -> g x -> Lan g a
||| 'free' functor for any *->*
Functor (Lan f) where
map func (FMap g y) = FMap (func . g) y
|
/-
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
|
module SocialSystems
using StatsBase: weights, sample
using Distributions: MvNormal, rand, Normal, cdf, pdf
import Base: +, -, *, length, size, getindex, setindex!, start, done, next, show, dot
# Utils Export
export randSphere, gammasoc, phi, G
# Types Export
export MoralVector, Society, BasicSociety, DistrustSociety
export agents, interactions, insertagent!, hamiltonian, magnetization, believeness, quadrupole, consensus
export epssoc, rhosoc, gammasoc, cogcost
# Dynamics Export
export metropolisStep!, metropolis!,
discreteStep!, discreteEvol!, societyHistory!,
computeDeltas
include("constants.jl")
include("utils.jl")
include("types/MoralVector.jl")
include("types/Society.jl")
include("types/BasicSociety.jl")
include("types/DistrustSociety.jl")
include("dynamics.jl")
end #module
|
[STATEMENT]
lemma conductor_le_iff: "conductor \<le> a \<longleftrightarrow> (\<exists>d\<le>a. induced_modulus d)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (conductor \<le> a) = (\<exists>d\<le>a. induced_modulus d)
[PROOF STEP]
unfolding conductor_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (Min (Collect induced_modulus) \<le> a) = (\<exists>d\<le>a. induced_modulus d)
[PROOF STEP]
using conductor_fin induced_modulus_modulus
[PROOF STATE]
proof (prove)
using this:
finite (Collect induced_modulus)
induced_modulus n
goal (1 subgoal):
1. (Min (Collect induced_modulus) \<le> a) = (\<exists>d\<le>a. induced_modulus d)
[PROOF STEP]
by (subst Min_le_iff) auto |
The enumeration of the empty set is the empty sequence. |
###
# transforms concs and dirality
###
import NumericExtensions.negate!, NumericExtensions.divide!, NumericExtensions.add!, NumericExtensions.exp!
function flow(Pot :: Matrix)
d1, d2 = size(Pot)
Flow = Array(Number8, d1, d2)
for j in 1:d2
for i in 1:d1
west = j == 1 ? d2 : j-1
east = j == d2 ? 1 : j+1
north = i == d1 ? 1 : i+1
south = i == 1 ? d1 : i-1
###
# Calculate the probability of flow out of a cell based on the pot differnece
p = Pot[i , j] ;
psw = Pot[south,west] - p;
psj = Pot[south,j ] - p;
pse = Pot[south,east] - p;
pie = Pot[i ,east] - p;
pne = Pot[north,east] - p;
pnj = Pot[north,j ] - p;
pnw = Pot[north,west] - p;
piw = Pot[i ,west] - p;
ge = [psw, psj, pse, pie, pne, pnj, pnw, piw]
ge2 = [psw, psj, pse, pie, pne, pnj, pnw, piw]
ge = negate!(divide!(ge2, add!(negate!(exp!(ge)), 1))) #
###
# Remove NaN
###
ge_wo_na = Number8([isnan(x) ? 1.0 / 8.0 : x/8.0 for x in ge])
###
# Normalize by eight.
###
Flow[i,j] = ge_wo_na
end
end
return Flow
end
function diffusionJl!(Conc :: Matrix, pot :: Matrix, p_move :: Matrix) #concentration and direction
d1, d2 = size(Conc)
Flow = flow(pot)
for j in 1:d2
for i in 1:d1
west = j == 1 ? d2 : j-1
east = j == d2 ? 1 : j+1
north = i == d1 ? 1 : i+1
south = i == 1 ? d1 : i-1
###
# Get the flow out of cell ij
###
outflow = Conc[i,j] * sum(Flow[i,j])
###
# Calculate the inflow based on the outflow from other cells into this on.
###
inflow = Conc[south, west] * Flow[south, west].s4 +
Conc[south, j ] * Flow[south, j ].s5 +
Conc[south, east] * Flow[south, east].s6 +
Conc[i , east] * Flow[i , east].s7 +
Conc[north, east] * Flow[north, east].s0 +
Conc[north, j ] * Flow[north, j ].s1 +
Conc[north, west] * Flow[north, west].s2 +
Conc[i , west] * Flow[i , west].s3 ;
###
# Inflow - outflow = change
###
p_move[i,j] = inflow - outflow
end
end
end |
{-# OPTIONS --without-K --safe #-}
open import Categories.Category
open import Categories.Functor hiding (id)
-- Cone over a Functor F (from shape category J into category C)
module Categories.Diagram.Cone
{o ℓ e} {o′ ℓ′ e′} {C : Category o ℓ e} {J : Category o′ ℓ′ e′} (F : Functor J C) where
open Category C
open Functor F
open import Level
record Apex (N : Obj) : Set (ℓ′ ⊔ o′ ⊔ e ⊔ ℓ) where
field
ψ : (X : Category.Obj J) → (N ⇒ F₀ X)
commute : ∀ {X Y} (f : J [ X , Y ]) → F₁ f ∘ ψ X ≈ ψ Y
record Cone : Set (o ⊔ ℓ′ ⊔ o′ ⊔ e ⊔ ℓ) where
field
{N} : Obj
apex : Apex N
open Apex apex public
open Apex
open Cone
record Cone⇒ (c c′ : Cone) : Set (ℓ ⊔ e ⊔ o′) where
field
arr : N c ⇒ N c′
commute : ∀ {X} → ψ c′ X ∘ arr ≈ ψ c X
open Cone⇒
|
(* Property from Case-Analysis for Rippling and Inductive Proof,
Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
This Isabelle theory is produced using the TIP tool offered at the following website:
https://github.com/tip-org/tools
This file was originally provided as part of TIP benchmark at the following website:
https://github.com/tip-org/benchmarks
Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
to make it compatible with Isabelle2017.*)
theory TIP_prop_33
imports "../../Test_Base"
begin
datatype Nat = Z | S "Nat"
fun x :: "Nat => Nat => bool" where
"x (Z) (Z) = True"
| "x (Z) (S z2) = False"
| "x (S x2) (Z) = False"
| "x (S x2) (S y2) = x x2 y2"
fun min :: "Nat => Nat => Nat" where
"min (Z) z = Z"
| "min (S z2) (Z) = Z"
| "min (S z2) (S y1) = S (min z2 y1)"
fun t2 :: "Nat => Nat => bool" where
"t2 (Z) z = True"
| "t2 (S z2) (Z) = False"
| "t2 (S z2) (S x2) = t2 z2 x2"
theorem property0 :
"((x (min a b) a) = (t2 a b))"
oops
end
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Loop-unrolling. *)
Require Import Coqlib.
Require Import Errors.
Require Import Maps.
Require Import Compopts.
Require Import AST.
Require Import Integers.
Require Import Globalenvs.
Require Import Switch.
Require Import Op.
Require Import Registers.
Require Cminor.
Require Import CminorSel.
Require Compopts.
Local Open Scope error_monad_scope.
(** * iterated sequence *)
Fixpoint iterseq (count: nat) (s1 s2:stmt) : stmt :=
match count with
| 0%nat => s2
| S n => Sseq s1 (iterseq n s1 s2)
end.
(** * Loop-unrolling
We perform loop-unrolling based on an external oracle that assigns
the number of loop-unfolds for each loop. The transformation fails
whenever one attempts to unfold a loop whose body has any label (but
succeeds if the oracle leave those loop untouched).
*)
Definition unroll_flag n := andb (NPeano.Nat.eqb n O).
Fixpoint unroll_stmt b (guess: positive -> nat) (s: stmt) (pos:positive): res stmt:=
match s with
| Sseq s1 s2 => do s1' <- unroll_stmt b guess s1 (xO pos);
do s2' <- unroll_stmt b guess s2 (xI pos);
OK (Sseq s1' s2')
| Sifthenelse c s1 s2 => do s1' <- unroll_stmt b guess s1 (xO pos);
do s2' <- unroll_stmt b guess s2 (xI pos);
OK (Sifthenelse c s1' s2')
| Sloop s => let guess_pos := guess pos in
do s' <- unroll_stmt (unroll_flag guess_pos b) guess s (xO pos);
OK (iterseq guess_pos s' (Sloop s'))
| Sblock s => do s' <- unroll_stmt b guess s pos;
OK (Sblock s')
| Slabel i s => if b
then (do s' <- unroll_stmt b guess s pos;
OK (Slabel i s'))
else Error (msg "LoopUnroll: trying to unfold loop body with labels")
| _ => OK s
end.
(* [optim_loop_unroll_estimates] is the external oracle that assigns the
number of unfolds for each loop (declared in [Compopts.v]) *)
Definition unroll_function (ge: genv) (f: function) : res function :=
do body' <- unroll_stmt true (optim_loop_unroll_estimates f.(fn_body))
f.(fn_body) xH;
OK (mkfunction
f.(fn_sig)
f.(fn_params)
f.(fn_vars)
f.(fn_stackspace)
body').
Definition unroll_fundef (ge: genv) (f: fundef) : res fundef :=
transf_partial_fundef (unroll_function ge) f.
(** Conversion of programs. *)
Definition unroll_program (p: program) : res program :=
let ge := Genv.globalenv p in
transform_partial_program (unroll_fundef ge) p.
|
Coot is for macromolecular model building, model completion and validation, particularly suitable for protein modelling using X-ray data. Coot displays maps and models and allows model manipulations such as idealization, real space refinement, manual rotation/translation, rigid-body fitting, ligand search, solvation, mutations, rotamers, Ramachandran plots, skeletonization, non-crystallographic symmetry and more.
Mostly GPLv3, some GLPv2+, some LGPLv3. |
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal4.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Derive Show for lst.
Derive Arbitrary for lst.
Instance Dec_Eq_lst : Dec_Eq lst.
Proof. dec_eq. Qed.
Lemma conj8synthconj5 : forall (lv0 : lst), (@eq natural (Succ (len (append lv0 lv0))) (Succ (len (append lv0 lv0)))).
Admitted.
QuickChick conj8synthconj5.
|
import Data.List
import Data.Vect
import Data.String.Parser
import System.File
Vec3 : Type
Vec3 = Vect 3 Integer
minusV : Vec3 -> Vec3 -> Vec3
minusV [x1,y1,z1] [x2,y2,z2] = [x1-x2,y1-y2,z1-z2]
maxV : Vec3 -> Vec3 -> Vec3
maxV [x1,y1,z1] [x2,y2,z2] = [max x1 x2, max y1 y2, max z1 z2]
minV : Vec3 -> Vec3 -> Vec3
minV [x1,y1,z1] [x2,y2,z2] = [min x1 x2, min y1 y2, min z1 z2]
Cube : Type
Cube = (Vec3, Vec3)
isCorrect : Cube -> Maybe Cube
isCorrect c@([x1,y1,z1], [x2,y2,z2]) =
if x1 < x2 && y1 < y2 && z1 < z2
then Just c
else Nothing
intersect : Cube -> Cube -> Maybe Cube
intersect (min1, max1) (min2, max2) = isCorrect (maxV min1 min2, minV max1 max2)
volume : Cube -> Integer
volume (min, max) = product $ (abs <$> minusV max min)
data Command = On Cube | Off Cube
isOn : Command -> Bool
isOn (On _) = True
isOn _ = False
invert : Command -> Command
invert (On c) = Off c
invert (Off c) = On c
getCube : Command -> Cube
getCube (On c) = c
getCube (Off c) = c
Input : Type
Input = List Command
rangeParser : Parser (Integer, Integer)
rangeParser = do skip letter
skip $ char '='
min <- integer
token ".."
max <- integer
pure (min, max + 1)
commandParser : Parser Command
commandParser = do cmd <- (token "on" $> On) <|> (token "off" $> Off)
[(xmin, xmax),(ymin,ymax),(zmin,zmax)] <- commaSep rangeParser
| _ => fail "no ranges"
pure $ cmd ([xmin,ymin,zmin],[xmax,ymax,zmax])
parser : Parser Input
parser = some (commandParser <* spaces)
Cubes : Type
Cubes = List Cube
addCube' : List Command -> Cube -> (Integer, List Command)
addCube' [] c = (0, [])
addCube' ((On c) :: cs) b = case intersect b c of
Nothing => addCube' cs b
(Just overlap) => let (v, os) = addCube' cs b in
(v - volume overlap, (Off overlap) :: os)
addCube' ((Off c) :: cs) b = case intersect b c of
Nothing => addCube' cs b
(Just overlap) => let (v, os) = addCube' cs b in
(v + volume overlap, (On overlap) :: os)
addCube : List Command -> Cube -> (Integer, List Command)
addCube cs c = case addCube' cs c of
(vol, []) => (vol, cs)
(vol, os) => (vol, os ++ cs)
doCmd : (Integer, List Command) -> Command -> (Integer, List Command)
doCmd (vol, cs) c@(On b) = let (v, cs) = addCube cs b in
(v + vol + volume b, c :: cs)
doCmd (vol, cs) (Off b) = mapFst ((+) vol) $ addCube cs b
cmdInBounds : Cube -> Command -> Maybe Command
cmdInBounds b (On c) = On <$> intersect b c
cmdInBounds b (Off c) = Off <$> intersect b c
part1 : Input -> IO String
part1 a = let bound : Cube = ([-50,-50,-50], [51,51,51])
cs = catMaybes $ cmdInBounds bound <$> a in
pure $ show $ fst $ foldl doCmd (0, []) cs
part2 : Input -> IO String
part2 a = pure $ show $ fst $ foldl doCmd (0, []) a
main : IO ()
main = do Right input <- readFile "input.txt"
| Left err => printLn err
Right (a, _) <- pure $ parse parser input
| Left err => printLn err
part1 a >>= putStrLn
part2 a >>= putStrLn
|
lemma tendsto_at_topI_sequentially_real: fixes f :: "real \<Rightarrow> real" assumes mono: "mono f" and limseq: "(\<lambda>n. f (real n)) \<longlonglongrightarrow> y" shows "(f \<longlongrightarrow> y) at_top" |
(* Title: HOL/Auth/n_germanSymIndex_lemma_on_inv__46.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanSymIndex Protocol Case Study*}
theory n_germanSymIndex_lemma_on_inv__46 imports n_germanSymIndex_base
begin
section{*All lemmas on causal relation between inv__46 and some rule r*}
lemma n_SendInv__part__0Vsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__0 i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendInv__part__1Vsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__1 i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendInvAckVsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_RecvInvAckVsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvInvAck i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendGntSVsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''ExGntd'')) (Const false)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv0) ''Cmd'')) (Const GntE))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendGntEVsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''ExGntd'')) (Const false)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv0) ''Cmd'')) (Const GntE))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_RecvGntSVsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntS i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_RecvGntEVsinv__46:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntE i" apply fastforce done
from a2 obtain p__Inv0 p__Inv2 where a2:"p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv0)\<or>(i~=p__Inv0\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv0)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv0\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendReqE__part__1Vsinv__46:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__46:
assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_RecvReqEVsinv__46:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE N i" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendReqE__part__0Vsinv__46:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendReqSVsinv__46:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_RecvReqSVsinv__46:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqS N i" and
a2: "(\<exists> p__Inv0 p__Inv2. p__Inv0\<le>N\<and>p__Inv2\<le>N\<and>p__Inv0~=p__Inv2\<and>f=inv__46 p__Inv0 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
[STATEMENT]
lemma get_child_nodes_new_shadow_root:
"ptr' \<noteq> cast new_shadow_root_ptr \<Longrightarrow> h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr
\<Longrightarrow> h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h' \<Longrightarrow> r \<in> get_child_nodes_locs ptr' \<Longrightarrow> r h h'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> get_child_nodes_locs ptr'\<rbrakk> \<Longrightarrow> r h h'
[PROOF STEP]
apply(auto simp add: get_child_nodes_locs_def)[1]
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_shadow_root_ptr_kind ptr' then {preserved (get_M\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) RShadowRoot.child_nodes)} else {})\<rbrakk> \<Longrightarrow> r h h'
2. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> get_child_nodes_locs\<^sub>C\<^sub>o\<^sub>r\<^sub>e\<^sub>_\<^sub>D\<^sub>O\<^sub>M ptr'\<rbrakk> \<Longrightarrow> r h h'
[PROOF STEP]
apply (metis document_ptr_casts_commute3 insert_absorb insert_not_empty is_document_ptr_kind_none
new_shadow_root_get_M\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t option.case_eq_if shadow_root_ptr_casts_commute3 singletonD)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> get_child_nodes_locs\<^sub>C\<^sub>o\<^sub>r\<^sub>e\<^sub>_\<^sub>D\<^sub>O\<^sub>M ptr'\<rbrakk> \<Longrightarrow> r h h'
[PROOF STEP]
apply(auto simp add: CD.get_child_nodes_locs_def)[1]
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r = preserved (get_M\<^sub>O\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t ptr' RObject.nothing)\<rbrakk> \<Longrightarrow> preserved (get_M\<^sub>O\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t ptr' RObject.nothing) h h'
2. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_element_ptr_kind\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr' then {preserved (get_M\<^sub>E\<^sub>l\<^sub>e\<^sub>m\<^sub>e\<^sub>n\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>e\<^sub>l\<^sub>e\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) RElement.child_nodes)} else {})\<rbrakk> \<Longrightarrow> r h h'
3. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_document_ptr_kind ptr' then {preserved (get_M\<^sub>D\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>d\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) document_element)} else {})\<rbrakk> \<Longrightarrow> r h h'
[PROOF STEP]
using new_shadow_root_get_M\<^sub>O\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h ?h'; ?h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r ?new_shadow_root_ptr; ?ptr \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ?new_shadow_root_ptr\<rbrakk> \<Longrightarrow> preserved (get_M\<^sub>O\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t ?ptr ?getter) ?h ?h'
goal (3 subgoals):
1. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r = preserved (get_M\<^sub>O\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t ptr' RObject.nothing)\<rbrakk> \<Longrightarrow> preserved (get_M\<^sub>O\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t ptr' RObject.nothing) h h'
2. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_element_ptr_kind\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr' then {preserved (get_M\<^sub>E\<^sub>l\<^sub>e\<^sub>m\<^sub>e\<^sub>n\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>e\<^sub>l\<^sub>e\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) RElement.child_nodes)} else {})\<rbrakk> \<Longrightarrow> r h h'
3. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_document_ptr_kind ptr' then {preserved (get_M\<^sub>D\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>d\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) document_element)} else {})\<rbrakk> \<Longrightarrow> r h h'
[PROOF STEP]
apply blast
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_element_ptr_kind\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr' then {preserved (get_M\<^sub>E\<^sub>l\<^sub>e\<^sub>m\<^sub>e\<^sub>n\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>e\<^sub>l\<^sub>e\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) RElement.child_nodes)} else {})\<rbrakk> \<Longrightarrow> r h h'
2. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_document_ptr_kind ptr' then {preserved (get_M\<^sub>D\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>d\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) document_element)} else {})\<rbrakk> \<Longrightarrow> r h h'
[PROOF STEP]
apply (metis empty_iff insertE new_shadow_root_get_M\<^sub>E\<^sub>l\<^sub>e\<^sub>m\<^sub>e\<^sub>n\<^sub>t)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>ptr' \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>r new_shadow_root_ptr; h \<turnstile> new\<^sub>S\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>R\<^sub>o\<^sub>o\<^sub>t_M \<rightarrow>\<^sub>h h'; r \<in> (if is_document_ptr_kind ptr' then {preserved (get_M\<^sub>D\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t (the (cast\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>d\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ptr')) document_element)} else {})\<rbrakk> \<Longrightarrow> r h h'
[PROOF STEP]
apply (metis empty_iff new_shadow_root_get_M\<^sub>D\<^sub>o\<^sub>c\<^sub>u\<^sub>m\<^sub>e\<^sub>n\<^sub>t singletonD)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
library(dslabs)
data(olive)
head(olive)
palmatic <- olive$palmitic
palmitoleic <- olive$palmitoleic
plot(palmatic, palmitoleic)
boxplot(palmatic, palmitoleic)
boxplot(palmatic~region, data=olive)
|
module Vsurfac13
use Vmeshes
real(rprec), dimension(:), allocatable :: snx1, sny1, snz1,
1 dsur1
real(rprec) :: fla
end module Vsurfac13
|
Updation of Child info along with Aadhaar number in child info website during 2016-17.
All the DEOs in the state are informed that new admissions for the academic year 2016-17 are going on in all schools under all managements. in this connection, the following guidelines are issued for recording Aadhaar number of students in Admission Register and Transfer Certificate by the Headmaster of schools. |
module Text.CSS.Declaration
import Text.CSS.Color
import Text.CSS.ListStyleType
import Text.CSS.Property
%default total
public export
record Declaration where
constructor MkDeclaration
property : Property tpe
value : tpe
infixl 8 .=
export %inline
(.=) : Property t -> t -> Declaration
(.=) = MkDeclaration
export %inline
render : Declaration -> String
render (MkDeclaration p v) = renderProp p v ++ ";"
|
Here are your morning links!
Janczak looked solid in his second start since returning from injury.
TCU broke through in the sixth inning with a pair of run. Jake Guenther and Alex Isola singled to open the inning. A wild pitch had both runners in scoring position and Johnny Rizer delivered a two-run single up the middle to make it a 6-2 ballgame. The Frogs didn’t go quietly, scoring a run on a Zach Humphreys groundout in the eighth. With two outs in the ninth, the Frogs put the tying run on base with walks to Josh Watson and Isola around a Guenther base hit. UTA closer Andrew Gross wiggled off the hook with a ground out to end the game. Jared Janczak (0-2) tossed 4 1/3 innings. He allowed six runs (two earned) on six hits, walked one and struck out two. Haylen Green and Matt Rudis allowed one combined runner over the last 3 2/3 innings of the game. The pair fanned seven.
The defensive end position is loaded, name-wise, but not very experienced.
This is a spot with a ton of turnover and, in turn, opportunities for new faces. Mathis, who some have compared to Jerry Hughes when it comes to potential, appears to be on his way to a starting role after continuing to earn rave reviews through spring. Patterson hinted that 2019 could finally be Bowen’s time too, so don’t take your eyes off the 6-foot-4 Byron Nelson High School product when fall camp arrives down the stretch.
The cornerback would fill a massive need with Jeff Gladney and Julius Lewis set to graduate.
Jenkins is getting recruited by Jeremy Modkins mostly because he’s the cornerbacks coach for the Frogs. However, Jenkins says he’s built a strong relationship with each of the coaches on staff.
Jenkins was hosted on his visit by redshirt freshman Atanza Vongor. The four-star says he got along with the defensive back as well as the rest of the team.
Equestrian has put together a solid season.
TCU News: Joe Broadnax’s career is over, will Justin Rogers play this year? |
The real number corresponding to an integer is the integer itself. |
State Before: l : Type ?u.197342
m : Type ?u.197345
n : Type ?u.197348
o : Type u_5
p : Type ?u.197354
q : Type ?u.197357
m' : o → Type u_1
n' : o → Type u_2
p' : o → Type ?u.197372
R : Type ?u.197375
S : Type ?u.197378
α : Type u_3
β : Type u_4
inst✝² : DecidableEq o
inst✝¹ : Zero α
inst✝ : Zero β
M : (i : o) → Matrix (m' i) (n' i) α
f : α → β
hf : f 0 = 0
⊢ map (blockDiagonal' M) f = blockDiagonal' fun k => map (M k) f State After: case a.h
l : Type ?u.197342
m : Type ?u.197345
n : Type ?u.197348
o : Type u_5
p : Type ?u.197354
q : Type ?u.197357
m' : o → Type u_1
n' : o → Type u_2
p' : o → Type ?u.197372
R : Type ?u.197375
S : Type ?u.197378
α : Type u_3
β : Type u_4
inst✝² : DecidableEq o
inst✝¹ : Zero α
inst✝ : Zero β
M : (i : o) → Matrix (m' i) (n' i) α
f : α → β
hf : f 0 = 0
i✝ : (i : o) × m' i
x✝ : (i : o) × n' i
⊢ map (blockDiagonal' M) f i✝ x✝ = blockDiagonal' (fun k => map (M k) f) i✝ x✝ Tactic: ext State Before: case a.h
l : Type ?u.197342
m : Type ?u.197345
n : Type ?u.197348
o : Type u_5
p : Type ?u.197354
q : Type ?u.197357
m' : o → Type u_1
n' : o → Type u_2
p' : o → Type ?u.197372
R : Type ?u.197375
S : Type ?u.197378
α : Type u_3
β : Type u_4
inst✝² : DecidableEq o
inst✝¹ : Zero α
inst✝ : Zero β
M : (i : o) → Matrix (m' i) (n' i) α
f : α → β
hf : f 0 = 0
i✝ : (i : o) × m' i
x✝ : (i : o) × n' i
⊢ map (blockDiagonal' M) f i✝ x✝ = blockDiagonal' (fun k => map (M k) f) i✝ x✝ State After: case a.h
l : Type ?u.197342
m : Type ?u.197345
n : Type ?u.197348
o : Type u_5
p : Type ?u.197354
q : Type ?u.197357
m' : o → Type u_1
n' : o → Type u_2
p' : o → Type ?u.197372
R : Type ?u.197375
S : Type ?u.197378
α : Type u_3
β : Type u_4
inst✝² : DecidableEq o
inst✝¹ : Zero α
inst✝ : Zero β
M : (i : o) → Matrix (m' i) (n' i) α
f : α → β
hf : f 0 = 0
i✝ : (i : o) × m' i
x✝ : (i : o) × n' i
⊢ f (if h : i✝.fst = x✝.fst then M i✝.fst i✝.snd (cast (_ : n' x✝.fst = n' i✝.fst) x✝.snd) else 0) =
if h : i✝.fst = x✝.fst then f (M i✝.fst i✝.snd (cast (_ : n' x✝.fst = n' i✝.fst) x✝.snd)) else 0 Tactic: simp only [map_apply, blockDiagonal'_apply, eq_comm] State Before: case a.h
l : Type ?u.197342
m : Type ?u.197345
n : Type ?u.197348
o : Type u_5
p : Type ?u.197354
q : Type ?u.197357
m' : o → Type u_1
n' : o → Type u_2
p' : o → Type ?u.197372
R : Type ?u.197375
S : Type ?u.197378
α : Type u_3
β : Type u_4
inst✝² : DecidableEq o
inst✝¹ : Zero α
inst✝ : Zero β
M : (i : o) → Matrix (m' i) (n' i) α
f : α → β
hf : f 0 = 0
i✝ : (i : o) × m' i
x✝ : (i : o) × n' i
⊢ f (if h : i✝.fst = x✝.fst then M i✝.fst i✝.snd (cast (_ : n' x✝.fst = n' i✝.fst) x✝.snd) else 0) =
if h : i✝.fst = x✝.fst then f (M i✝.fst i✝.snd (cast (_ : n' x✝.fst = n' i✝.fst) x✝.snd)) else 0 State After: no goals Tactic: rw [apply_dite f, hf] |
lemma interior_open: "open S \<Longrightarrow> interior S = S" |
/- 2018-10-12T21:52:34 Locally nameless formulas, built off Floris' preterms
---Jesse
I wanted to avoid the headache over shifts (at the cost of needing to define a well-formedness predicate on terms); my implementation of locally nameless formulas is based off Chargueraud's paper (thanks for the pointer Jeremy!).
TODO:
- finish writing the coercion for variable lists
- finish writing the substitution functions
- add a well-formedness predicate
-/
structure Language :=
(relations : Π n : nat, Type) (functions : Π n : nat, Type)
section
parameter L : Language
/- preterm n is a partially applied term. if applied to n terms, it becomes a term -/
inductive preterm : ℕ → Type
| bvar : ℕ → preterm 0
| fvar : string → preterm 0
| func : ∀ {n : nat}, L.functions n → preterm n
| apply : ∀ {n : nat}, preterm (n + 1) → preterm 0 → preterm n
open preterm
def term := preterm 0
-- /- raise_depth_term _ t n m raises variables in t which are at least m by n -/
-- def raise_depth_term : ∀ {l}, preterm l → ℕ → ℕ → preterm l
-- | _ (var L k) n m := if m ≤ k then var (k+m) else var k
-- | _ (func f) n m := func f
-- | _ (apply t1 t2) n m := apply (raise_depth_term t1 n m) (raise_depth_term t2 n m)
-- /- substitute_term t s n substitutes s for (var n) and reduces the level of all variables above n by 1 -/
-- def substitute_term : ∀ {l}, preterm l → term → ℕ → preterm l
-- | _ (var L k) s n := if k < n then var k else if k > n then var (k-1) else s
-- | _ (func f) s n := func f
-- | _ (apply t1 t2) s n := apply (substitute_term t1 s n) (substitute_term t2 s n)
/-- Given a preterm, return a list of free variables which occur in it--/
def free_vars_preterm : Π n : ℕ, preterm n → list string
| _ (bvar L k) := []
| _ (fvar L s) := [s]
| _ (@func L _ f) := []
| _ (@apply L n t1 t2) := (free_vars_preterm (n+1) t1 ∪ free_vars_preterm 0 t2)
def free_vars_term : term → list string := free_vars_preterm 0
lemma free_var_preterm_coercionl (n : ℕ) (t1 : preterm (n+1)) (t2 : term) : {x : string // x ∈ (free_vars_preterm (n+1) t1)} → {x : string // x ∈ (free_vars_preterm n (apply t1 t2))} := sorry
def substitute_preterm : Π n : ℕ, Π (t : preterm n), term → {x : string // x ∈ (free_vars_preterm n t)} → preterm n
| _ (bvar L k) t x := (bvar k)
| _ (fvar L s) t x := sorry
| _ (@func L _ f) t x := (func f)
| _ (@apply L n t1 t2) t x := sorry
end
section
parameter L : Language
/- preformula n is a partially applied formula. if applied to n terms, it becomes a formula -/
inductive preformula : ℕ → Type
| true : preformula 0
| false : preformula 0
| equal : (term L) → (term L) → preformula 0
| rel : ∀ {n : nat}, L.relations n → preformula n
| apprel : ∀ {n : nat}, preformula (n + 1) → (term L) → preformula n
| imp : preformula 0 → preformula 0 → preformula 0
| all : preformula 0 → preformula 0
open preformula
def formula := preformula 0
def free_vars_preformula : Π n : ℕ, preformula n → list string
| _ (true L) := []
| _ (false L) := []
| _ (equal t1 t2) := free_vars_term L t1 ∪ free_vars_term L t2
| _ (@rel L n R) := []
| _ (@apprel L n ψ t) := free_vars_preformula _ ψ ∪ free_vars_term L t
| _ (imp ϕ ψ) := free_vars_preformula _ ϕ ∪ free_vars_preformula _ ψ
| _ (all ψ) := free_vars_preformula _ ψ
def free_vars_formula : formula → list string := free_vars_preformula 0
-- def raise_depth_formula : ∀ {l}, preformula l → ℕ → ℕ → preformula l
-- | _ (true L) n m := true
-- | _ (false L) n m := false
-- | _ (equal t1 t2) n m := equal (raise_depth_term t1 n m) (raise_depth_term t2 n m)
-- | _ (rel R) n m := rel R
-- | _ (apprel f t) n m := apprel (raise_depth_formula f n m) (raise_depth_term t n m)
-- | _ (imp f1 f2) n m := imp (raise_depth_formula f1 n m) (raise_depth_formula f2 n m)
-- | _ (all f) n m := all (raise_depth_formula f n (m+1))
def substitute_formula : ∀ {l}, preformula l → (term L) → ℕ → preformula l
| _ (true L) s n := true
| _ (false L) s n := false
| _ (equal t1 t2) s n := equal (substitute_term L t1 s n) (substitute_term L t2 s n)
| _ (rel R) s n := rel R
| _ (apprel f t) s n := apprel (substitute_formula f s n) (substitute_term t s n)
| _ (imp f1 f2) s n := imp (substitute_formula f1 s n) (substitute_formula f2 s n)
| _ (all f) s n := all (substitute_formula f s (n+1))
def substitute_preformula : Π n : ℕ, Π (ψ : preformula n), term → {x : string // x ∈ (free_vars_preformula _ ψ)} → preformula n
| _ (true L) t x := true
| _ (false L) t x := false
| _ (equal t1 t2) := equal (substitute_preformula _ _ _ _ t1) (substitute_preformula _ _ _ _ t2)
end
|
Formal statement is: lemma convergent_LIMSEQ_iff: "convergent X \<longleftrightarrow> X \<longlonglongrightarrow> lim X" Informal statement is: A sequence $X$ converges if and only if $X$ converges to its limit. |
\section{\module{token} ---
Constants used with Python parse trees}
\declaremodule{standard}{token}
\modulesynopsis{Constants representing terminal nodes of the parse tree.}
\sectionauthor{Fred L. Drake, Jr.}{[email protected]}
This module provides constants which represent the numeric values of
leaf nodes of the parse tree (terminal tokens). Refer to the file
\file{Grammar/Grammar} in the Python distribution for the definitions
of the names in the context of the language grammar. The specific
numeric values which the names map to may change between Python
versions.
This module also provides one data object and some functions. The
functions mirror definitions in the Python C header files.
\begin{datadesc}{tok_name}
Dictionary mapping the numeric values of the constants defined in this
module back to name strings, allowing more human-readable
representation of parse trees to be generated.
\end{datadesc}
\begin{funcdesc}{ISTERMINAL}{x}
Return true for terminal token values.
\end{funcdesc}
\begin{funcdesc}{ISNONTERMINAL}{x}
Return true for non-terminal token values.
\end{funcdesc}
\begin{funcdesc}{ISEOF}{x}
Return true if \var{x} is the marker indicating the end of input.
\end{funcdesc}
\begin{seealso}
\seemodule{parser}{The second example for the \refmodule{parser}
module shows how to use the \module{symbol}
module.}
\end{seealso}
|
(* Title: HOL/Auth/Guard/Guard_Public.thy
Author: Frederic Blanqui, University of Cambridge Computer Laboratory
Copyright 2002 University of Cambridge
Lemmas on guarded messages for public protocols.
*)
theory Guard_Public imports Guard "../Public" Extensions begin
subsection\<open>Extensions to Theory \<open>Public\<close>\<close>
declare initState.simps [simp del]
subsubsection\<open>signature\<close>
definition sign :: "agent => msg => msg" where
"sign A X == \<lbrace>Agent A, X, Crypt (priK A) (Hash X)\<rbrace>"
lemma sign_inj [iff]: "(sign A X = sign A' X') = (A=A' & X=X')"
by (auto simp: sign_def)
subsubsection\<open>agent associated to a key\<close>
definition agt :: "key => agent" where
"agt K == @A. K = priK A | K = pubK A"
lemma agt_priK [simp]: "agt (priK A) = A"
by (simp add: agt_def)
lemma agt_pubK [simp]: "agt (pubK A) = A"
by (simp add: agt_def)
subsubsection\<open>basic facts about @{term initState}\<close>
lemma no_Crypt_in_parts_init [simp]: "Crypt K X ~:parts (initState A)"
by (cases A, auto simp: initState.simps)
lemma no_Crypt_in_analz_init [simp]: "Crypt K X ~:analz (initState A)"
by auto
lemma no_priK_in_analz_init [simp]: "A ~:bad
==> Key (priK A) ~:analz (initState Spy)"
by (auto simp: initState.simps)
lemma priK_notin_initState_Friend [simp]: "A ~= Friend C
==> Key (priK A) ~: parts (initState (Friend C))"
by (auto simp: initState.simps)
lemma keyset_init [iff]: "keyset (initState A)"
by (cases A, auto simp: keyset_def initState.simps)
subsubsection\<open>sets of private keys\<close>
definition priK_set :: "key set => bool" where
"priK_set Ks == ALL K. K:Ks --> (EX A. K = priK A)"
lemma in_priK_set: "[| priK_set Ks; K:Ks |] ==> EX A. K = priK A"
by (simp add: priK_set_def)
lemma priK_set1 [iff]: "priK_set {priK A}"
by (simp add: priK_set_def)
lemma priK_set2 [iff]: "priK_set {priK A, priK B}"
by (simp add: priK_set_def)
subsubsection\<open>sets of good keys\<close>
definition good :: "key set => bool" where
"good Ks == ALL K. K:Ks --> agt K ~:bad"
lemma in_good: "[| good Ks; K:Ks |] ==> agt K ~:bad"
by (simp add: good_def)
lemma good1 [simp]: "A ~:bad ==> good {priK A}"
by (simp add: good_def)
lemma good2 [simp]: "[| A ~:bad; B ~:bad |] ==> good {priK A, priK B}"
by (simp add: good_def)
subsubsection\<open>greatest nonce used in a trace, 0 if there is no nonce\<close>
primrec greatest :: "event list => nat"
where
"greatest [] = 0"
| "greatest (ev # evs) = max (greatest_msg (msg ev)) (greatest evs)"
lemma greatest_is_greatest: "Nonce n:used evs ==> n <= greatest evs"
apply (induct evs, auto simp: initState.simps)
apply (drule used_sub_parts_used, safe)
apply (drule greatest_msg_is_greatest, arith)
by simp
subsubsection\<open>function giving a new nonce\<close>
definition new :: "event list => nat" where
"new evs == Suc (greatest evs)"
lemma new_isnt_used [iff]: "Nonce (new evs) ~:used evs"
by (clarify, drule greatest_is_greatest, auto simp: new_def)
subsection\<open>Proofs About Guarded Messages\<close>
subsubsection\<open>small hack necessary because priK is defined as the inverse of pubK\<close>
lemma pubK_is_invKey_priK: "pubK A = invKey (priK A)"
by simp
lemmas pubK_is_invKey_priK_substI = pubK_is_invKey_priK [THEN ssubst]
lemmas invKey_invKey_substI = invKey [THEN ssubst]
lemma "Nonce n:parts {X} ==> Crypt (pubK A) X:guard n {priK A}"
apply (rule pubK_is_invKey_priK_substI, rule invKey_invKey_substI)
by (rule Guard_Nonce, simp+)
subsubsection\<open>guardedness results\<close>
lemma sign_guard [intro]: "X:guard n Ks ==> sign A X:guard n Ks"
by (auto simp: sign_def)
lemma Guard_init [iff]: "Guard n Ks (initState B)"
by (induct B, auto simp: Guard_def initState.simps)
lemma Guard_knows_max': "Guard n Ks (knows_max' C evs)
==> Guard n Ks (knows_max C evs)"
by (simp add: knows_max_def)
lemma Nonce_not_used_Guard_spies [dest]: "Nonce n ~:used evs
==> Guard n Ks (spies evs)"
by (auto simp: Guard_def dest: not_used_not_known parts_sub)
lemma Nonce_not_used_Guard [dest]: "[| evs:p; Nonce n ~:used evs;
Gets_correct p; one_step p |] ==> Guard n Ks (knows (Friend C) evs)"
by (auto simp: Guard_def dest: known_used parts_trans)
lemma Nonce_not_used_Guard_max [dest]: "[| evs:p; Nonce n ~:used evs;
Gets_correct p; one_step p |] ==> Guard n Ks (knows_max (Friend C) evs)"
by (auto simp: Guard_def dest: known_max_used parts_trans)
lemma Nonce_not_used_Guard_max' [dest]: "[| evs:p; Nonce n ~:used evs;
Gets_correct p; one_step p |] ==> Guard n Ks (knows_max' (Friend C) evs)"
apply (rule_tac H="knows_max (Friend C) evs" in Guard_mono)
by (auto simp: knows_max_def)
subsubsection\<open>regular protocols\<close>
definition regular :: "event list set => bool" where
"regular p == ALL evs A. evs:p --> (Key (priK A):parts (spies evs)) = (A:bad)"
lemma priK_parts_iff_bad [simp]: "[| evs:p; regular p |] ==>
(Key (priK A):parts (spies evs)) = (A:bad)"
by (auto simp: regular_def)
lemma priK_analz_iff_bad [simp]: "[| evs:p; regular p |] ==>
(Key (priK A):analz (spies evs)) = (A:bad)"
by auto
lemma Guard_Nonce_analz: "[| Guard n Ks (spies evs); evs:p;
priK_set Ks; good Ks; regular p |] ==> Nonce n ~:analz (spies evs)"
apply (clarify, simp only: knows_decomp)
apply (drule Guard_invKey_keyset, simp+, safe)
apply (drule in_good, simp)
apply (drule in_priK_set, simp+, clarify)
apply (frule_tac A=A in priK_analz_iff_bad)
by (simp add: knows_decomp)+
end
|
-- @@stderr --
dtrace: failed to compile script test/unittest/probes/err.D_SYNTAX.declarein.d: [D_SYNTAX] line 21: expected predicate and/or actions following probe description
|
function cmp = MS_complexity(x,n,binHow)
% Calculate the Lempel-Ziv complexity of the n-bit encoding of x.
%
% cmp is the normalised complexity, that is the number of distinct
% symbol sequences in x, divided by the expected number of distinct
% symbols for a noise sequence.
%
% Algorithm is implemented in complexitybs.c
%
% Michael Small
% [email protected], http://school.maths.uwa.edu.au/~small/
% 7/10/04
% For further details, please see M. Small. Applied Nonlinear Time Series
% Analysis: Applications in Physics, Physiology and Finance. Nonlinear Science
% Series A, vol. 52. World Scientific, 2005. (ISBN 981-256-117-X) and the
% references therein.
if nargin < 2
n = 2;
end
if nargin < 3
binHow = 'equiprobable';
end
%-------------------------------------------------------------------------------
if length(n) > 1
% Can run with multiple values of the number of symbols, n:
for ni = 1:length(n)
cmp(ni) = MS_complexity(x,n(ni),binHow);
end
else
% do the binning, with equiprobable bins
switch binHow
case 'equiprobable'
x=x(:);
nx=length(x);
[xn,xi]=sort(x+eps*randn(size(x))); %introduce randomness for ties
y=zeros(nx,1);
y=1:nx;
y=floor(y.*(n/(nx+1)));
x(xi)=y;
case 'equiwidth'
% else,
% %do binning with equal width bins
x=x(:);
nx=length(x);
minx=min(x);
maxx=max(x);
stepx=(maxx-minx)/n;
y=zeros(nx,1);
while minx<maxx
minx=minx+stepx;
y=y+double(x<minx);
end
x=floor(y);
end
%compute complexity with complexitybs
cmp = MS_complexitybs(x);
end
end
|
If $S$ is locally connected, then the connected component of $S$ containing $x$ is open in $S$. |
(* Title: HOL/Auth/n_german_lemma_on_inv__23.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_german Protocol Case Study*}
theory n_german_lemma_on_inv__23 imports n_german_base
begin
section{*All lemmas on causal relation between inv__23 and some rule r*}
lemma n_SendInv__part__0Vsinv__23:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__0 i" apply fastforce done
from a2 obtain p__Inv1 p__Inv2 where a2:"p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv1)\<or>(i~=p__Inv1\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv1)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv1\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendInv__part__1Vsinv__23:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInv__part__1 i" apply fastforce done
from a2 obtain p__Inv1 p__Inv2 where a2:"p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv1)\<or>(i~=p__Inv1\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv1)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv1\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendInvAckVsinv__23:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendInvAck i" apply fastforce done
from a2 obtain p__Inv1 p__Inv2 where a2:"p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv1)\<or>(i~=p__Inv1\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv1)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv1\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendGntSVsinv__23:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntS i" apply fastforce done
from a2 obtain p__Inv1 p__Inv2 where a2:"p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv1)\<or>(i~=p__Inv1\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv1)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Ident ''ExGntd'')) (Const false)) (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv2) ''Cmd'')) (Const GntE))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv1\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendGntEVsinv__23:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_SendGntE N i" apply fastforce done
from a2 obtain p__Inv1 p__Inv2 where a2:"p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv1)\<or>(i~=p__Inv1\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Ident ''Chan2'') p__Inv1) ''Cmd'')) (Const GntS)) (eqn (IVar (Para (Ident ''ShrSet'') p__Inv1)) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv1)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv1\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_RecvGntSVsinv__23:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntS i" apply fastforce done
from a2 obtain p__Inv1 p__Inv2 where a2:"p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv1)\<or>(i~=p__Inv1\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv1)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv1\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_RecvGntEVsinv__23:
assumes a1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain i where a1:"i\<le>N\<and>r=n_RecvGntE i" apply fastforce done
from a2 obtain p__Inv1 p__Inv2 where a2:"p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2" apply fastforce done
have "(i=p__Inv2)\<or>(i=p__Inv1)\<or>(i~=p__Inv1\<and>i~=p__Inv2)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(i=p__Inv2)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i=p__Inv1)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(i~=p__Inv1\<and>i~=p__Inv2)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_SendReqE__part__1Vsinv__23:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__23:
assumes a1: "\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_RecvInvAckVsinv__23:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvInvAck i" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_RecvReqEVsinv__23:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqE N i" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendReqE__part__0Vsinv__23:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_SendReqSVsinv__23:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_SendReqS i" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_RecvReqSVsinv__23:
assumes a1: "\<exists> i. i\<le>N\<and>r=n_RecvReqS N i" and
a2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
section \<open>Operational Semantics\<close>
theory RG_Tran
imports RG_Com
begin
subsection \<open>Semantics of Component Programs\<close>
subsubsection \<open>Environment transitions\<close>
type_synonym 'a conf = "(('a com) option) \<times> 'a"
inductive_set
etran :: "('a conf \<times> 'a conf) set"
and etran' :: "'a conf \<Rightarrow> 'a conf \<Rightarrow> bool" ("_ -e\<rightarrow> _" [81,81] 80)
where
"P -e\<rightarrow> Q \<equiv> (P,Q) \<in> etran"
| Env: "(P, s) -e\<rightarrow> (P, t)"
lemma etranE: "c -e\<rightarrow> c' \<Longrightarrow> (\<And>P s t. c = (P, s) \<Longrightarrow> c' = (P, t) \<Longrightarrow> Q) \<Longrightarrow> Q"
by (induct c, induct c', erule etran.cases, blast)
subsubsection \<open>Component transitions\<close>
inductive_set
ctran :: "('a conf \<times> 'a conf) set"
and ctran' :: "'a conf \<Rightarrow> 'a conf \<Rightarrow> bool" ("_ -c\<rightarrow> _" [81,81] 80)
and ctrans :: "'a conf \<Rightarrow> 'a conf \<Rightarrow> bool" ("_ -c*\<rightarrow> _" [81,81] 80)
where
"P -c\<rightarrow> Q \<equiv> (P,Q) \<in> ctran"
| "P -c*\<rightarrow> Q \<equiv> (P,Q) \<in> ctran\<^sup>*"
| Basic: "(Some(Basic f), s) -c\<rightarrow> (None, f s)"
| Seq1: "(Some P0, s) -c\<rightarrow> (None, t) \<Longrightarrow> (Some(Seq P0 P1), s) -c\<rightarrow> (Some P1, t)"
| Seq2: "(Some P0, s) -c\<rightarrow> (Some P2, t) \<Longrightarrow> (Some(Seq P0 P1), s) -c\<rightarrow> (Some(Seq P2 P1), t)"
| CondT: "s\<in>b \<Longrightarrow> (Some(Cond b P1 P2), s) -c\<rightarrow> (Some P1, s)"
| CondF: "s\<notin>b \<Longrightarrow> (Some(Cond b P1 P2), s) -c\<rightarrow> (Some P2, s)"
| WhileF: "s\<notin>b \<Longrightarrow> (Some(While b P), s) -c\<rightarrow> (None, s)"
| WhileT: "s\<in>b \<Longrightarrow> (Some(While b P), s) -c\<rightarrow> (Some(Seq P (While b P)), s)"
| Await: "\<lbrakk>s\<in>b; (Some P, s) -c*\<rightarrow> (None, t)\<rbrakk> \<Longrightarrow> (Some(Await b P), s) -c\<rightarrow> (None, t)"
monos "rtrancl_mono"
subsection \<open>Semantics of Parallel Programs\<close>
type_synonym 'a par_conf = "('a par_com) \<times> 'a"
inductive_set
par_etran :: "('a par_conf \<times> 'a par_conf) set"
and par_etran' :: "['a par_conf,'a par_conf] \<Rightarrow> bool" ("_ -pe\<rightarrow> _" [81,81] 80)
where
"P -pe\<rightarrow> Q \<equiv> (P,Q) \<in> par_etran"
| ParEnv: "(Ps, s) -pe\<rightarrow> (Ps, t)"
inductive_set
par_ctran :: "('a par_conf \<times> 'a par_conf) set"
and par_ctran' :: "['a par_conf,'a par_conf] \<Rightarrow> bool" ("_ -pc\<rightarrow> _" [81,81] 80)
where
"P -pc\<rightarrow> Q \<equiv> (P,Q) \<in> par_ctran"
| ParComp: "\<lbrakk>i<length Ps; (Ps!i, s) -c\<rightarrow> (r, t)\<rbrakk> \<Longrightarrow> (Ps, s) -pc\<rightarrow> (Ps[i:=r], t)"
lemma par_ctranE: "c -pc\<rightarrow> c' \<Longrightarrow>
(\<And>i Ps s r t. c = (Ps, s) \<Longrightarrow> c' = (Ps[i := r], t) \<Longrightarrow> i < length Ps \<Longrightarrow>
(Ps ! i, s) -c\<rightarrow> (r, t) \<Longrightarrow> P) \<Longrightarrow> P"
by (induct c, induct c', erule par_ctran.cases, blast)
subsection \<open>Computations\<close>
subsubsection \<open>Sequential computations\<close>
type_synonym 'a confs = "'a conf list"
inductive_set cptn :: "'a confs set"
where
CptnOne: "[(P,s)] \<in> cptn"
| CptnEnv: "(P, t)#xs \<in> cptn \<Longrightarrow> (P,s)#(P,t)#xs \<in> cptn"
| CptnComp: "\<lbrakk>(P,s) -c\<rightarrow> (Q,t); (Q, t)#xs \<in> cptn \<rbrakk> \<Longrightarrow> (P,s)#(Q,t)#xs \<in> cptn"
definition cp :: "('a com) option \<Rightarrow> 'a \<Rightarrow> ('a confs) set" where
"cp P s \<equiv> {l. l!0=(P,s) \<and> l \<in> cptn}"
subsubsection \<open>Parallel computations\<close>
type_synonym 'a par_confs = "'a par_conf list"
inductive_set par_cptn :: "'a par_confs set"
where
ParCptnOne: "[(P,s)] \<in> par_cptn"
| ParCptnEnv: "(P,t)#xs \<in> par_cptn \<Longrightarrow> (P,s)#(P,t)#xs \<in> par_cptn"
| ParCptnComp: "\<lbrakk> (P,s) -pc\<rightarrow> (Q,t); (Q,t)#xs \<in> par_cptn \<rbrakk> \<Longrightarrow> (P,s)#(Q,t)#xs \<in> par_cptn"
definition par_cp :: "'a par_com \<Rightarrow> 'a \<Rightarrow> ('a par_confs) set" where
"par_cp P s \<equiv> {l. l!0=(P,s) \<and> l \<in> par_cptn}"
subsection\<open>Modular Definition of Computation\<close>
definition lift :: "'a com \<Rightarrow> 'a conf \<Rightarrow> 'a conf" where
"lift Q \<equiv> \<lambda>(P, s). (if P=None then (Some Q,s) else (Some(Seq (the P) Q), s))"
inductive_set cptn_mod :: "('a confs) set"
where
CptnModOne: "[(P, s)] \<in> cptn_mod"
| CptnModEnv: "(P, t)#xs \<in> cptn_mod \<Longrightarrow> (P, s)#(P, t)#xs \<in> cptn_mod"
| CptnModNone: "\<lbrakk>(Some P, s) -c\<rightarrow> (None, t); (None, t)#xs \<in> cptn_mod \<rbrakk> \<Longrightarrow> (Some P,s)#(None, t)#xs \<in>cptn_mod"
| CptnModCondT: "\<lbrakk>(Some P0, s)#ys \<in> cptn_mod; s \<in> b \<rbrakk> \<Longrightarrow> (Some(Cond b P0 P1), s)#(Some P0, s)#ys \<in> cptn_mod"
| CptnModCondF: "\<lbrakk>(Some P1, s)#ys \<in> cptn_mod; s \<notin> b \<rbrakk> \<Longrightarrow> (Some(Cond b P0 P1), s)#(Some P1, s)#ys \<in> cptn_mod"
| CptnModSeq1: "\<lbrakk>(Some P0, s)#xs \<in> cptn_mod; zs=map (lift P1) xs \<rbrakk>
\<Longrightarrow> (Some(Seq P0 P1), s)#zs \<in> cptn_mod"
| CptnModSeq2:
"\<lbrakk>(Some P0, s)#xs \<in> cptn_mod; fst(last ((Some P0, s)#xs)) = None;
(Some P1, snd(last ((Some P0, s)#xs)))#ys \<in> cptn_mod;
zs=(map (lift P1) xs)@ys \<rbrakk> \<Longrightarrow> (Some(Seq P0 P1), s)#zs \<in> cptn_mod"
| CptnModWhile1:
"\<lbrakk> (Some P, s)#xs \<in> cptn_mod; s \<in> b; zs=map (lift (While b P)) xs \<rbrakk>
\<Longrightarrow> (Some(While b P), s)#(Some(Seq P (While b P)), s)#zs \<in> cptn_mod"
| CptnModWhile2:
"\<lbrakk> (Some P, s)#xs \<in> cptn_mod; fst(last ((Some P, s)#xs))=None; s \<in> b;
zs=(map (lift (While b P)) xs)@ys;
(Some(While b P), snd(last ((Some P, s)#xs)))#ys \<in> cptn_mod\<rbrakk>
\<Longrightarrow> (Some(While b P), s)#(Some(Seq P (While b P)), s)#zs \<in> cptn_mod"
subsection \<open>Equivalence of Both Definitions.\<close>
lemma last_length: "((a#xs)!(length xs))=last (a#xs)"
by (induct xs) auto
lemma div_seq [rule_format]: "list \<in> cptn_mod \<Longrightarrow>
(\<forall>s P Q zs. list=(Some (Seq P Q), s)#zs \<longrightarrow>
(\<exists>xs. (Some P, s)#xs \<in> cptn_mod \<and> (zs=(map (lift Q) xs) \<or>
( fst(((Some P, s)#xs)!length xs)=None \<and>
(\<exists>ys. (Some Q, snd(((Some P, s)#xs)!length xs))#ys \<in> cptn_mod
\<and> zs=(map (lift (Q)) xs)@ys)))))"
apply(erule cptn_mod.induct)
apply simp_all
apply clarify
apply(force intro:CptnModOne)
apply clarify
apply(erule_tac x=Pa in allE)
apply(erule_tac x=Q in allE)
apply simp
apply clarify
apply(erule disjE)
apply(rule_tac x="(Some Pa,t)#xsa" in exI)
apply(rule conjI)
apply clarify
apply(erule CptnModEnv)
apply(rule disjI1)
apply(simp add:lift_def)
apply clarify
apply(rule_tac x="(Some Pa,t)#xsa" in exI)
apply(rule conjI)
apply(erule CptnModEnv)
apply(rule disjI2)
apply(rule conjI)
apply(case_tac xsa,simp,simp)
apply(rule_tac x="ys" in exI)
apply(rule conjI)
apply simp
apply(simp add:lift_def)
apply clarify
apply(erule ctran.cases,simp_all)
apply clarify
apply(rule_tac x="xs" in exI)
apply simp
apply clarify
apply(rule_tac x="xs" in exI)
apply(simp add: last_length)
done
lemma cptn_onlyif_cptn_mod_aux [rule_format]:
"\<forall>s Q t xs.((Some a, s), Q, t) \<in> ctran \<longrightarrow> (Q, t) # xs \<in> cptn_mod
\<longrightarrow> (Some a, s) # (Q, t) # xs \<in> cptn_mod"
supply [[simproc del: defined_all]]
apply(induct a)
apply simp_all
\<comment> \<open>basic\<close>
apply clarify
apply(erule ctran.cases,simp_all)
apply(rule CptnModNone,rule Basic,simp)
apply clarify
apply(erule ctran.cases,simp_all)
\<comment> \<open>Seq1\<close>
apply(rule_tac xs="[(None,ta)]" in CptnModSeq2)
apply(erule CptnModNone)
apply(rule CptnModOne)
apply simp
apply simp
apply(simp add:lift_def)
\<comment> \<open>Seq2\<close>
apply(erule_tac x=sa in allE)
apply(erule_tac x="Some P2" in allE)
apply(erule allE,erule impE, assumption)
apply(drule div_seq,simp)
apply clarify
apply(erule disjE)
apply clarify
apply(erule allE,erule impE, assumption)
apply(erule_tac CptnModSeq1)
apply(simp add:lift_def)
apply clarify
apply(erule allE,erule impE, assumption)
apply(erule_tac CptnModSeq2)
apply (simp add:last_length)
apply (simp add:last_length)
apply(simp add:lift_def)
\<comment> \<open>Cond\<close>
apply clarify
apply(erule ctran.cases,simp_all)
apply(force elim: CptnModCondT)
apply(force elim: CptnModCondF)
\<comment> \<open>While\<close>
apply clarify
apply(erule ctran.cases,simp_all)
apply(rule CptnModNone,erule WhileF,simp)
apply(drule div_seq,force)
apply clarify
apply (erule disjE)
apply(force elim:CptnModWhile1)
apply clarify
apply(force simp add:last_length elim:CptnModWhile2)
\<comment> \<open>await\<close>
apply clarify
apply(erule ctran.cases,simp_all)
apply(rule CptnModNone,erule Await,simp+)
done
lemma cptn_onlyif_cptn_mod [rule_format]: "c \<in> cptn \<Longrightarrow> c \<in> cptn_mod"
apply(erule cptn.induct)
apply(rule CptnModOne)
apply(erule CptnModEnv)
apply(case_tac P)
apply simp
apply(erule ctran.cases,simp_all)
apply(force elim:cptn_onlyif_cptn_mod_aux)
done
lemma lift_is_cptn: "c\<in>cptn \<Longrightarrow> map (lift P) c \<in> cptn"
apply(erule cptn.induct)
apply(force simp add:lift_def CptnOne)
apply(force intro:CptnEnv simp add:lift_def)
apply(force simp add:lift_def intro:CptnComp Seq2 Seq1 elim:ctran.cases)
done
lemma cptn_append_is_cptn [rule_format]:
"\<forall>b a. b#c1\<in>cptn \<longrightarrow> a#c2\<in>cptn \<longrightarrow> (b#c1)!length c1=a \<longrightarrow> b#c1@c2\<in>cptn"
apply(induct c1)
apply simp
apply clarify
apply(erule cptn.cases,simp_all)
apply(force intro:CptnEnv)
apply(force elim:CptnComp)
done
lemma last_lift: "\<lbrakk>xs\<noteq>[]; fst(xs!(length xs - (Suc 0)))=None\<rbrakk>
\<Longrightarrow> fst((map (lift P) xs)!(length (map (lift P) xs)- (Suc 0)))=(Some P)"
by (cases "(xs ! (length xs - (Suc 0)))") (simp add:lift_def)
lemma last_fst [rule_format]: "P((a#x)!length x) \<longrightarrow> \<not>P a \<longrightarrow> P (x!(length x - (Suc 0)))"
by (induct x) simp_all
lemma last_fst_esp:
"fst(((Some a,s)#xs)!(length xs))=None \<Longrightarrow> fst(xs!(length xs - (Suc 0)))=None"
apply(erule last_fst)
apply simp
done
lemma last_snd: "xs\<noteq>[] \<Longrightarrow>
snd(((map (lift P) xs))!(length (map (lift P) xs) - (Suc 0)))=snd(xs!(length xs - (Suc 0)))"
by (cases "(xs ! (length xs - (Suc 0)))") (simp_all add:lift_def)
lemma Cons_lift: "(Some (Seq P Q), s) # (map (lift Q) xs) = map (lift Q) ((Some P, s) # xs)"
by (simp add:lift_def)
lemma Cons_lift_append:
"(Some (Seq P Q), s) # (map (lift Q) xs) @ ys = map (lift Q) ((Some P, s) # xs)@ ys "
by (simp add:lift_def)
lemma lift_nth: "i<length xs \<Longrightarrow> map (lift Q) xs ! i = lift Q (xs! i)"
by (simp add:lift_def)
lemma snd_lift: "i< length xs \<Longrightarrow> snd(lift Q (xs ! i))= snd (xs ! i)"
by (cases "xs!i") (simp add:lift_def)
lemma cptn_if_cptn_mod: "c \<in> cptn_mod \<Longrightarrow> c \<in> cptn"
apply(erule cptn_mod.induct)
apply(rule CptnOne)
apply(erule CptnEnv)
apply(erule CptnComp,simp)
apply(rule CptnComp)
apply(erule CondT,simp)
apply(rule CptnComp)
apply(erule CondF,simp)
\<comment> \<open>Seq1\<close>
apply(erule cptn.cases,simp_all)
apply(rule CptnOne)
apply clarify
apply(drule_tac P=P1 in lift_is_cptn)
apply(simp add:lift_def)
apply(rule CptnEnv,simp)
apply clarify
apply(simp add:lift_def)
apply(rule conjI)
apply clarify
apply(rule CptnComp)
apply(rule Seq1,simp)
apply(drule_tac P=P1 in lift_is_cptn)
apply(simp add:lift_def)
apply clarify
apply(rule CptnComp)
apply(rule Seq2,simp)
apply(drule_tac P=P1 in lift_is_cptn)
apply(simp add:lift_def)
\<comment> \<open>Seq2\<close>
apply(rule cptn_append_is_cptn)
apply(drule_tac P=P1 in lift_is_cptn)
apply(simp add:lift_def)
apply simp
apply(simp split: if_split_asm)
apply(frule_tac P=P1 in last_lift)
apply(rule last_fst_esp)
apply (simp add:last_length)
apply(simp add:Cons_lift lift_def split_def last_conv_nth)
\<comment> \<open>While1\<close>
apply(rule CptnComp)
apply(rule WhileT,simp)
apply(drule_tac P="While b P" in lift_is_cptn)
apply(simp add:lift_def)
\<comment> \<open>While2\<close>
apply(rule CptnComp)
apply(rule WhileT,simp)
apply(rule cptn_append_is_cptn)
apply(drule_tac P="While b P" in lift_is_cptn)
apply(simp add:lift_def)
apply simp
apply(simp split: if_split_asm)
apply(frule_tac P="While b P" in last_lift)
apply(rule last_fst_esp,simp add:last_length)
apply(simp add:Cons_lift lift_def split_def last_conv_nth)
done
theorem cptn_iff_cptn_mod: "(c \<in> cptn) = (c \<in> cptn_mod)"
apply(rule iffI)
apply(erule cptn_onlyif_cptn_mod)
apply(erule cptn_if_cptn_mod)
done
section \<open>Validity of Correctness Formulas\<close>
subsection \<open>Validity for Component Programs.\<close>
type_synonym 'a rgformula =
"'a com \<times> 'a set \<times> ('a \<times> 'a) set \<times> ('a \<times> 'a) set \<times> 'a set"
definition assum :: "('a set \<times> ('a \<times> 'a) set) \<Rightarrow> ('a confs) set" where
"assum \<equiv> \<lambda>(pre, rely). {c. snd(c!0) \<in> pre \<and> (\<forall>i. Suc i<length c \<longrightarrow>
c!i -e\<rightarrow> c!(Suc i) \<longrightarrow> (snd(c!i), snd(c!Suc i)) \<in> rely)}"
definition comm :: "(('a \<times> 'a) set \<times> 'a set) \<Rightarrow> ('a confs) set" where
"comm \<equiv> \<lambda>(guar, post). {c. (\<forall>i. Suc i<length c \<longrightarrow>
c!i -c\<rightarrow> c!(Suc i) \<longrightarrow> (snd(c!i), snd(c!Suc i)) \<in> guar) \<and>
(fst (last c) = None \<longrightarrow> snd (last c) \<in> post)}"
definition com_validity :: "'a com \<Rightarrow> 'a set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> 'a set \<Rightarrow> bool"
("\<Turnstile> _ sat [_, _, _, _]" [60,0,0,0,0] 45) where
"\<Turnstile> P sat [pre, rely, guar, post] \<equiv>
\<forall>s. cp (Some P) s \<inter> assum(pre, rely) \<subseteq> comm(guar, post)"
subsection \<open>Validity for Parallel Programs.\<close>
definition All_None :: "(('a com) option) list \<Rightarrow> bool" where
"All_None xs \<equiv> \<forall>c\<in>set xs. c=None"
definition par_assum :: "('a set \<times> ('a \<times> 'a) set) \<Rightarrow> ('a par_confs) set" where
"par_assum \<equiv> \<lambda>(pre, rely). {c. snd(c!0) \<in> pre \<and> (\<forall>i. Suc i<length c \<longrightarrow>
c!i -pe\<rightarrow> c!Suc i \<longrightarrow> (snd(c!i), snd(c!Suc i)) \<in> rely)}"
definition par_comm :: "(('a \<times> 'a) set \<times> 'a set) \<Rightarrow> ('a par_confs) set" where
"par_comm \<equiv> \<lambda>(guar, post). {c. (\<forall>i. Suc i<length c \<longrightarrow>
c!i -pc\<rightarrow> c!Suc i \<longrightarrow> (snd(c!i), snd(c!Suc i)) \<in> guar) \<and>
(All_None (fst (last c)) \<longrightarrow> snd( last c) \<in> post)}"
definition par_com_validity :: "'a par_com \<Rightarrow> 'a set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set
\<Rightarrow> 'a set \<Rightarrow> bool" ("\<Turnstile> _ SAT [_, _, _, _]" [60,0,0,0,0] 45) where
"\<Turnstile> Ps SAT [pre, rely, guar, post] \<equiv>
\<forall>s. par_cp Ps s \<inter> par_assum(pre, rely) \<subseteq> par_comm(guar, post)"
subsection \<open>Compositionality of the Semantics\<close>
subsubsection \<open>Definition of the conjoin operator\<close>
definition same_length :: "'a par_confs \<Rightarrow> ('a confs) list \<Rightarrow> bool" where
"same_length c clist \<equiv> (\<forall>i<length clist. length(clist!i)=length c)"
definition same_state :: "'a par_confs \<Rightarrow> ('a confs) list \<Rightarrow> bool" where
"same_state c clist \<equiv> (\<forall>i <length clist. \<forall>j<length c. snd(c!j) = snd((clist!i)!j))"
definition same_program :: "'a par_confs \<Rightarrow> ('a confs) list \<Rightarrow> bool" where
"same_program c clist \<equiv> (\<forall>j<length c. fst(c!j) = map (\<lambda>x. fst(nth x j)) clist)"
definition compat_label :: "'a par_confs \<Rightarrow> ('a confs) list \<Rightarrow> bool" where
"compat_label c clist \<equiv> (\<forall>j. Suc j<length c \<longrightarrow>
(c!j -pc\<rightarrow> c!Suc j \<and> (\<exists>i<length clist. (clist!i)!j -c\<rightarrow> (clist!i)! Suc j \<and>
(\<forall>l<length clist. l\<noteq>i \<longrightarrow> (clist!l)!j -e\<rightarrow> (clist!l)! Suc j))) \<or>
(c!j -pe\<rightarrow> c!Suc j \<and> (\<forall>i<length clist. (clist!i)!j -e\<rightarrow> (clist!i)! Suc j)))"
definition conjoin :: "'a par_confs \<Rightarrow> ('a confs) list \<Rightarrow> bool" ("_ \<propto> _" [65,65] 64) where
"c \<propto> clist \<equiv> (same_length c clist) \<and> (same_state c clist) \<and> (same_program c clist) \<and> (compat_label c clist)"
subsubsection \<open>Some previous lemmas\<close>
lemma list_eq_if [rule_format]:
"\<forall>ys. xs=ys \<longrightarrow> (length xs = length ys) \<longrightarrow> (\<forall>i<length xs. xs!i=ys!i)"
by (induct xs) auto
lemma list_eq: "(length xs = length ys \<and> (\<forall>i<length xs. xs!i=ys!i)) = (xs=ys)"
apply(rule iffI)
apply clarify
apply(erule nth_equalityI)
apply simp+
done
lemma nth_tl: "\<lbrakk> ys!0=a; ys\<noteq>[] \<rbrakk> \<Longrightarrow> ys=(a#(tl ys))"
by (cases ys) simp_all
lemma nth_tl_if [rule_format]: "ys\<noteq>[] \<longrightarrow> ys!0=a \<longrightarrow> P ys \<longrightarrow> P (a#(tl ys))"
by (induct ys) simp_all
lemma nth_tl_onlyif [rule_format]: "ys\<noteq>[] \<longrightarrow> ys!0=a \<longrightarrow> P (a#(tl ys)) \<longrightarrow> P ys"
by (induct ys) simp_all
lemma seq_not_eq1: "Seq c1 c2\<noteq>c1"
by (induct c1) auto
lemma seq_not_eq2: "Seq c1 c2\<noteq>c2"
by (induct c2) auto
lemma if_not_eq1: "Cond b c1 c2 \<noteq>c1"
by (induct c1) auto
lemma if_not_eq2: "Cond b c1 c2\<noteq>c2"
by (induct c2) auto
lemmas seq_and_if_not_eq [simp] = seq_not_eq1 seq_not_eq2
seq_not_eq1 [THEN not_sym] seq_not_eq2 [THEN not_sym]
if_not_eq1 if_not_eq2 if_not_eq1 [THEN not_sym] if_not_eq2 [THEN not_sym]
lemma prog_not_eq_in_ctran_aux:
assumes c: "(P,s) -c\<rightarrow> (Q,t)"
shows "P\<noteq>Q" using c
by (induct x1 \<equiv> "(P,s)" x2 \<equiv> "(Q,t)" arbitrary: P s Q t) auto
lemma prog_not_eq_in_ctran [simp]: "\<not> (P,s) -c\<rightarrow> (P,t)"
apply clarify
apply(drule prog_not_eq_in_ctran_aux)
apply simp
done
lemma prog_not_eq_in_par_ctran_aux [rule_format]: "(P,s) -pc\<rightarrow> (Q,t) \<Longrightarrow> (P\<noteq>Q)"
apply(erule par_ctran.induct)
apply(drule prog_not_eq_in_ctran_aux)
apply clarify
apply(drule list_eq_if)
apply simp_all
apply force
done
lemma prog_not_eq_in_par_ctran [simp]: "\<not> (P,s) -pc\<rightarrow> (P,t)"
apply clarify
apply(drule prog_not_eq_in_par_ctran_aux)
apply simp
done
lemma tl_in_cptn: "\<lbrakk> a#xs \<in>cptn; xs\<noteq>[] \<rbrakk> \<Longrightarrow> xs\<in>cptn"
by (force elim: cptn.cases)
lemma tl_zero[rule_format]:
"P (ys!Suc j) \<longrightarrow> Suc j<length ys \<longrightarrow> ys\<noteq>[] \<longrightarrow> P (tl(ys)!j)"
by (induct ys) simp_all
subsection \<open>The Semantics is Compositional\<close>
lemma aux_if [rule_format]:
"\<forall>xs s clist. (length clist = length xs \<and> (\<forall>i<length xs. (xs!i,s)#clist!i \<in> cptn)
\<and> ((xs, s)#ys \<propto> map (\<lambda>i. (fst i,s)#snd i) (zip xs clist))
\<longrightarrow> (xs, s)#ys \<in> par_cptn)"
apply(induct ys)
apply(clarify)
apply(rule ParCptnOne)
apply(clarify)
apply(simp add:conjoin_def compat_label_def)
apply clarify
apply(erule_tac x="0" and P="\<lambda>j. H j \<longrightarrow> (P j \<or> Q j)" for H P Q in all_dupE, simp)
apply(erule disjE)
\<comment> \<open>first step is a Component step\<close>
apply clarify
apply simp
apply(subgoal_tac "a=(xs[i:=(fst(clist!i!0))])")
apply(subgoal_tac "b=snd(clist!i!0)",simp)
prefer 2
apply(simp add: same_state_def)
apply(erule_tac x=i in allE,erule impE,assumption,
erule_tac x=1 and P="\<lambda>j. (H j) \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE, simp)
prefer 2
apply(simp add:same_program_def)
apply(erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (fst (s j))=(t j)" for H s t in allE,simp)
apply(rule nth_equalityI,simp)
apply clarify
apply(case_tac "i=ia",simp,simp)
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE)
apply(drule_tac t=i in not_sym,simp)
apply(erule etranE,simp)
apply(rule ParCptnComp)
apply(erule ParComp,simp)
\<comment> \<open>applying the induction hypothesis\<close>
apply(erule_tac x="xs[i := fst (clist ! i ! 0)]" in allE)
apply(erule_tac x="snd (clist ! i ! 0)" in allE)
apply(erule mp)
apply(rule_tac x="map tl clist" in exI,simp)
apply(rule conjI,clarify)
apply(case_tac "i=ia",simp)
apply(rule nth_tl_if)
apply(force simp add:same_length_def length_Suc_conv)
apply simp
apply(erule allE,erule impE,assumption,erule tl_in_cptn)
apply(force simp add:same_length_def length_Suc_conv)
apply(rule nth_tl_if)
apply(force simp add:same_length_def length_Suc_conv)
apply(simp add:same_state_def)
apply(erule_tac x=ia in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE)
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE)
apply(drule_tac t=i in not_sym,simp)
apply(erule etranE,simp)
apply(erule allE,erule impE,assumption,erule tl_in_cptn)
apply(force simp add:same_length_def length_Suc_conv)
apply(simp add:same_length_def same_state_def)
apply(rule conjI)
apply clarify
apply(case_tac j,simp,simp)
apply(erule_tac x=ia in allE, erule impE, assumption,
erule_tac x="Suc(Suc nat)" and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(force simp add:same_length_def length_Suc_conv)
apply(rule conjI)
apply(simp add:same_program_def)
apply clarify
apply(case_tac j,simp)
apply(rule nth_equalityI,simp)
apply clarify
apply(case_tac "i=ia",simp,simp)
apply(erule_tac x="Suc(Suc nat)" and P="\<lambda>j. H j \<longrightarrow> (fst (s j))=(t j)" for H s t in allE,simp)
apply(rule nth_equalityI,simp,simp)
apply(force simp add:length_Suc_conv)
apply(rule allI,rule impI)
apply(erule_tac x="Suc j" and P="\<lambda>j. H j \<longrightarrow> (I j \<or> J j)" for H I J in allE,simp)
apply(erule disjE)
apply clarify
apply(rule_tac x=ia in exI,simp)
apply(case_tac "i=ia",simp)
apply(rule conjI)
apply(force simp add: length_Suc_conv)
apply clarify
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE,erule impE,assumption)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE,erule impE,assumption)
apply simp
apply(case_tac j,simp)
apply(rule tl_zero)
apply(erule_tac x=l in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. (H j) \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(force elim:etranE intro:Env)
apply force
apply force
apply simp
apply(rule tl_zero)
apply(erule tl_zero)
apply force
apply force
apply force
apply force
apply(rule conjI,simp)
apply(rule nth_tl_if)
apply force
apply(erule_tac x=ia in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE)
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE)
apply(drule_tac t=i in not_sym,simp)
apply(erule etranE,simp)
apply(erule tl_zero)
apply force
apply force
apply clarify
apply(case_tac "i=l",simp)
apply(rule nth_tl_if)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply simp
apply(erule_tac P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE,erule impE,assumption,erule impE,assumption)
apply(erule tl_zero,force)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply(rule nth_tl_if)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply(erule_tac x=l in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE,erule impE, assumption,simp)
apply(erule etranE,simp)
apply(rule tl_zero)
apply force
apply force
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply(rule disjI2)
apply(case_tac j,simp)
apply clarify
apply(rule tl_zero)
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> I j\<in>etran" for H I in allE,erule impE, assumption)
apply(case_tac "i=ia",simp,simp)
apply(erule_tac x=ia in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE)
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE,erule impE, assumption,simp)
apply(force elim:etranE intro:Env)
apply force
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply simp
apply clarify
apply(rule tl_zero)
apply(rule tl_zero,force)
apply force
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply force
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
\<comment> \<open>first step is an environmental step\<close>
apply clarify
apply(erule par_etran.cases)
apply simp
apply(rule ParCptnEnv)
apply(erule_tac x="Ps" in allE)
apply(erule_tac x="t" in allE)
apply(erule mp)
apply(rule_tac x="map tl clist" in exI,simp)
apply(rule conjI)
apply clarify
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> I j \<in> cptn" for H I in allE,simp)
apply(erule cptn.cases)
apply(simp add:same_length_def)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply(simp add:same_state_def)
apply(erule_tac x=i in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> J j \<in>etran" for H J in allE,simp)
apply(erule etranE,simp)
apply(simp add:same_state_def same_length_def)
apply(rule conjI,clarify)
apply(case_tac j,simp,simp)
apply(erule_tac x=i in allE, erule impE, assumption,
erule_tac x="Suc(Suc nat)" and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(rule tl_zero)
apply(simp)
apply force
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply(rule conjI)
apply(simp add:same_program_def)
apply clarify
apply(case_tac j,simp)
apply(rule nth_equalityI,simp)
apply clarify
apply simp
apply(erule_tac x="Suc(Suc nat)" and P="\<lambda>j. H j \<longrightarrow> (fst (s j))=(t j)" for H s t in allE,simp)
apply(rule nth_equalityI,simp,simp)
apply(force simp add:length_Suc_conv)
apply(rule allI,rule impI)
apply(erule_tac x="Suc j" and P="\<lambda>j. H j \<longrightarrow> (I j \<or> J j)" for H I J in allE,simp)
apply(erule disjE)
apply clarify
apply(rule_tac x=i in exI,simp)
apply(rule conjI)
apply(erule_tac x=i and P="\<lambda>i. H i \<longrightarrow> J i \<in>etran" for H J in allE, erule impE, assumption)
apply(erule etranE,simp)
apply(erule_tac x=i in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(rule nth_tl_if)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply simp
apply(erule tl_zero,force)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply clarify
apply(erule_tac x=l and P="\<lambda>i. H i \<longrightarrow> J i \<in>etran" for H J in allE, erule impE, assumption)
apply(erule etranE,simp)
apply(erule_tac x=l in allE, erule impE, assumption,
erule_tac x=1 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(rule nth_tl_if)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply simp
apply(rule tl_zero,force)
apply force
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply(rule disjI2)
apply simp
apply clarify
apply(case_tac j,simp)
apply(rule tl_zero)
apply(erule_tac x=i and P="\<lambda>i. H i \<longrightarrow> J i \<in>etran" for H J in allE, erule impE, assumption)
apply(erule_tac x=i and P="\<lambda>i. H i \<longrightarrow> J i \<in>etran" for H J in allE, erule impE, assumption)
apply(force elim:etranE intro:Env)
apply force
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply simp
apply(rule tl_zero)
apply(rule tl_zero,force)
apply force
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply force
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
done
lemma aux_onlyif [rule_format]: "\<forall>xs s. (xs, s)#ys \<in> par_cptn \<longrightarrow>
(\<exists>clist. (length clist = length xs) \<and>
(xs, s)#ys \<propto> map (\<lambda>i. (fst i,s)#(snd i)) (zip xs clist) \<and>
(\<forall>i<length xs. (xs!i,s)#(clist!i) \<in> cptn))"
supply [[simproc del: defined_all]]
apply(induct ys)
apply(clarify)
apply(rule_tac x="map (\<lambda>i. []) [0..<length xs]" in exI)
apply(simp add: conjoin_def same_length_def same_state_def same_program_def compat_label_def)
apply(rule conjI)
apply(rule nth_equalityI,simp,simp)
apply(force intro: cptn.intros)
apply(clarify)
apply(erule par_cptn.cases,simp)
apply simp
apply(erule_tac x="xs" in allE)
apply(erule_tac x="t" in allE,simp)
apply clarify
apply(rule_tac x="(map (\<lambda>j. (P!j, t)#(clist!j)) [0..<length P])" in exI,simp)
apply(rule conjI)
prefer 2
apply clarify
apply(rule CptnEnv,simp)
apply(simp add:conjoin_def same_length_def same_state_def)
apply (rule conjI)
apply clarify
apply(case_tac j,simp,simp)
apply(rule conjI)
apply(simp add:same_program_def)
apply clarify
apply(case_tac j,simp)
apply(rule nth_equalityI,simp,simp)
apply simp
apply(rule nth_equalityI,simp,simp)
apply(simp add:compat_label_def)
apply clarify
apply(case_tac j,simp)
apply(simp add:ParEnv)
apply clarify
apply(simp add:Env)
apply simp
apply(erule_tac x=nat in allE,erule impE, assumption)
apply(erule disjE,simp)
apply clarify
apply(rule_tac x=i in exI,simp)
apply force
apply(erule par_ctran.cases,simp)
apply(erule_tac x="Ps[i:=r]" in allE)
apply(erule_tac x="ta" in allE,simp)
apply clarify
apply(rule_tac x="(map (\<lambda>j. (Ps!j, ta)#(clist!j)) [0..<length Ps]) [i:=((r, ta)#(clist!i))]" in exI,simp)
apply(rule conjI)
prefer 2
apply clarify
apply(case_tac "i=ia",simp)
apply(erule CptnComp)
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> (I j \<in> cptn)" for H I in allE,simp)
apply simp
apply(erule_tac x=ia in allE)
apply(rule CptnEnv,simp)
apply(simp add:conjoin_def)
apply (rule conjI)
apply(simp add:same_length_def)
apply clarify
apply(case_tac "i=ia",simp,simp)
apply(rule conjI)
apply(simp add:same_state_def)
apply clarify
apply(case_tac j, simp, simp (no_asm_simp))
apply(case_tac "i=ia",simp,simp)
apply(rule conjI)
apply(simp add:same_program_def)
apply clarify
apply(case_tac j,simp)
apply(rule nth_equalityI,simp,simp)
apply simp
apply(rule nth_equalityI,simp,simp)
apply(erule_tac x=nat and P="\<lambda>j. H j \<longrightarrow> (fst (a j))=((b j))" for H a b in allE)
apply(case_tac nat)
apply clarify
apply(case_tac "i=ia",simp,simp)
apply clarify
apply(case_tac "i=ia",simp,simp)
apply(simp add:compat_label_def)
apply clarify
apply(case_tac j)
apply(rule conjI,simp)
apply(erule ParComp,assumption)
apply clarify
apply(rule_tac x=i in exI,simp)
apply clarify
apply(rule Env)
apply simp
apply(erule_tac x=nat and P="\<lambda>j. H j \<longrightarrow> (P j \<or> Q j)" for H P Q in allE,simp)
apply(erule disjE)
apply clarify
apply(rule_tac x=ia in exI,simp)
apply(rule conjI)
apply(case_tac "i=ia",simp,simp)
apply clarify
apply(case_tac "i=l",simp)
apply(case_tac "l=ia",simp,simp)
apply(erule_tac x=l in allE,erule impE,assumption,erule impE, assumption,simp)
apply simp
apply(erule_tac x=l in allE,erule impE,assumption,erule impE, assumption,simp)
apply clarify
apply(erule_tac x=ia and P="\<lambda>j. H j \<longrightarrow> (P j)\<in>etran" for H P in allE, erule impE, assumption)
apply(case_tac "i=ia",simp,simp)
done
lemma one_iff_aux: "xs\<noteq>[] \<Longrightarrow> (\<forall>ys. ((xs, s)#ys \<in> par_cptn) =
(\<exists>clist. length clist= length xs \<and>
((xs, s)#ys \<propto> map (\<lambda>i. (fst i,s)#(snd i)) (zip xs clist)) \<and>
(\<forall>i<length xs. (xs!i,s)#(clist!i) \<in> cptn))) =
(par_cp (xs) s = {c. \<exists>clist. (length clist)=(length xs) \<and>
(\<forall>i<length clist. (clist!i) \<in> cp(xs!i) s) \<and> c \<propto> clist})"
apply (rule iffI)
apply(rule subset_antisym)
apply(rule subsetI)
apply(clarify)
apply(simp add:par_cp_def cp_def)
apply(case_tac x)
apply(force elim:par_cptn.cases)
apply simp
apply(rename_tac a list)
apply(erule_tac x="list" in allE)
apply clarify
apply simp
apply(rule_tac x="map (\<lambda>i. (fst i, s) # snd i) (zip xs clist)" in exI,simp)
apply(rule subsetI)
apply(clarify)
apply(case_tac x)
apply(erule_tac x=0 in allE)
apply(simp add:cp_def conjoin_def same_length_def same_program_def same_state_def compat_label_def)
apply clarify
apply(erule cptn.cases,force,force,force)
apply(simp add:par_cp_def conjoin_def same_length_def same_program_def same_state_def compat_label_def)
apply clarify
apply(erule_tac x=0 and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in all_dupE)
apply(subgoal_tac "a = xs")
apply(subgoal_tac "b = s",simp)
prefer 3
apply(erule_tac x=0 and P="\<lambda>j. H j \<longrightarrow> (fst (s j))=((t j))" for H s t in allE)
apply (simp add:cp_def)
apply(rule nth_equalityI,simp,simp)
prefer 2
apply(erule_tac x=0 in allE)
apply (simp add:cp_def)
apply(erule_tac x=0 and P="\<lambda>j. H j \<longrightarrow> (\<forall>i. T i \<longrightarrow> (snd (d j i))=(snd (e j i)))" for H T d e in allE,simp)
apply(erule_tac x=0 and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(erule_tac x=list in allE)
apply(rule_tac x="map tl clist" in exI,simp)
apply(rule conjI)
apply clarify
apply(case_tac j,simp)
apply(erule_tac x=i in allE, erule impE, assumption,
erule_tac x="0" and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE,simp)
apply(erule_tac x=i in allE, erule impE, assumption,
erule_tac x="Suc nat" and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply(rule conjI)
apply clarify
apply(rule nth_equalityI,simp,simp)
apply(case_tac j)
apply clarify
apply(erule_tac x=i in allE)
apply(simp add:cp_def)
apply clarify
apply simp
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply(thin_tac "H = (\<exists>i. J i)" for H J)
apply(rule conjI)
apply clarify
apply(erule_tac x=j in allE,erule impE, assumption,erule disjE)
apply clarify
apply(rule_tac x=i in exI,simp)
apply(case_tac j,simp)
apply(rule conjI)
apply(erule_tac x=i in allE)
apply(simp add:cp_def)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply clarify
apply(erule_tac x=l in allE)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE)
apply clarify
apply(simp add:cp_def)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!l",simp,simp)
apply simp
apply(rule conjI)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply clarify
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!l",simp,simp)
apply clarify
apply(erule_tac x=i in allE)
apply(simp add:cp_def)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp)
apply(rule nth_tl_if,simp,simp)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (P j)\<in>etran" for H P in allE, erule impE, assumption,simp)
apply(simp add:cp_def)
apply clarify
apply(rule nth_tl_if)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply force
apply force
apply clarify
apply(rule iffI)
apply(simp add:par_cp_def)
apply(erule_tac c="(xs, s) # ys" in equalityCE)
apply simp
apply clarify
apply(rule_tac x="map tl clist" in exI)
apply simp
apply (rule conjI)
apply(simp add:conjoin_def cp_def)
apply(rule conjI)
apply clarify
apply(unfold same_length_def)
apply clarify
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,simp)
apply(rule conjI)
apply(simp add:same_state_def)
apply clarify
apply(erule_tac x=i in allE, erule impE, assumption,
erule_tac x=j and P="\<lambda>j. H j \<longrightarrow> (snd (d j))=(snd (e j))" for H d e in allE)
apply(case_tac j,simp)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply(rule conjI)
apply(simp add:same_program_def)
apply clarify
apply(rule nth_equalityI,simp,simp)
apply(case_tac j,simp)
apply clarify
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply clarify
apply(simp add:compat_label_def)
apply(rule allI,rule impI)
apply(erule_tac x=j in allE,erule impE, assumption)
apply(erule disjE)
apply clarify
apply(rule_tac x=i in exI,simp)
apply(rule conjI)
apply(erule_tac x=i in allE)
apply(case_tac j,simp)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!i",simp,simp)
apply clarify
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> I j \<longrightarrow> J j" for H I J in allE)
apply(erule_tac x=l and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE)
apply(case_tac "clist!l",simp,simp)
apply(erule_tac x=l in allE,simp)
apply(rule disjI2)
apply clarify
apply(rule tl_zero)
apply(case_tac j,simp,simp)
apply(rule tl_zero,force)
apply force
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply force
apply(erule_tac x=i and P="\<lambda>j. H j \<longrightarrow> (length (s j) = t)" for H s t in allE,force)
apply clarify
apply(erule_tac x=i in allE)
apply(simp add:cp_def)
apply(rule nth_tl_if)
apply(simp add:conjoin_def)
apply clarify
apply(simp add:same_length_def)
apply(erule_tac x=i in allE,simp)
apply simp
apply simp
apply simp
apply clarify
apply(erule_tac c="(xs, s) # ys" in equalityCE)
apply(simp add:par_cp_def)
apply simp
apply(erule_tac x="map (\<lambda>i. (fst i, s) # snd i) (zip xs clist)" in allE)
apply simp
apply clarify
apply(simp add:cp_def)
done
theorem one: "xs\<noteq>[] \<Longrightarrow>
par_cp xs s = {c. \<exists>clist. (length clist)=(length xs) \<and>
(\<forall>i<length clist. (clist!i) \<in> cp(xs!i) s) \<and> c \<propto> clist}"
apply(frule one_iff_aux)
apply(drule sym)
apply(erule iffD2)
apply clarify
apply(rule iffI)
apply(erule aux_onlyif)
apply clarify
apply(force intro:aux_if)
done
end
|
n := 10;
for i in [1 .. n] do
Print(i);
if i < n then
Print(", ");
else
Print("\n");
fi;
od;
|
module Data.Optics.Iso
import Data.Optics.Prism
||| Isomorphism
data Iso s a =
||| create an isomorphism between s and a
MkIso (s -> a) (a -> s)
%name Iso iso, iso1, iso2
%default total
to: Iso s a -> s -> a
to (MkIso f g) s = f s
from: Iso s a -> a -> s
from (MkIso f g) a = g a
modify: (a -> a) -> (Iso s a) -> s -> s
modify f (MkIso to from) s = (from . f . to ) s
--
-- Compositions
--
infixr 9 -:+
||| compose two Isomorphisms
(-:+): Iso a b -> Iso s a -> Iso s b
x -:+ y = MkIso newTo newFrom
where
newTo: s -> b
newTo = (to x . to y)
newFrom: b -> s
newFrom = (from y . from x)
infixr 9 +:-
(+:-) : (Iso s a) -> (Iso a b) -> (Iso s b)
(+:-) = flip (-:+)
|
function T = tprod1(S, U, n)
%TPROD1 Tensor Product of a tensor and a matrix
% T = TPROD1(S, U, n)
%
% S - tensor (multidimensional array)
% U - matrix compatible with the nth size of S ie. size(S,n)==size(U,1)
% n - execute tprod in this dimension
%
% T - result of the product
%
% eg. tprod1(ones(2,3,4), [1 0 0; 0 1 0], 2)
%
% See also TPROD.
% TODO: n > dimensions of S -> ndim_expand
siz = size(S);
siz(n) = size(U,1);
H = ndim_unfold(S, n);
T = ndim_fold(U*H, n, siz);
|
%% LaTeX Beamer presentation template (requires beamer package)
%% see http://bitbucket.org/rivanvx/beamer/wiki/Home
%% idea contributed by H. Turgut Uyar
%% template based on a template by Till Tantau
%% this template is still evolving - it might differ in future releases!
\documentclass{beamer}
\mode<presentation>
{
\usetheme{Singapore}
\setbeamertemplate{footline}[frame number]
\usefonttheme{serif}
\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{caption}[numbered]
% \setbeamercovered{transparent}
}
\usepackage{cancel}
\usepackage{amsmath}
\usepackage{graphics}
\title{Tutorial for Mid-term Exam}
% \author{Hengfeng Wei}
\date{November 12, 2013}
% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
\AtBeginSubsection[]
{
\begin{frame}<beamer>
\frametitle{Outline}
\tableofcontents[currentsection]
\end{frame}
}
\AtBeginSection[]
{
\begin{frame}<beamer>
\frametitle{Outline}
\tableofcontents[currentsection]
\end{frame}
}
% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:
%\beamerdefaultoverlayspecification{<+->}
\begin{document}
\begin{frame}
\titlepage
\end{frame}
\begin{frame}
\frametitle{Outline}
\tableofcontents
% You might wish to add the option [pausesections]
\end{frame}
%%%%%%%%%%%%%%%%%%%
\section{A Warm-up Function}
\begin{frame}
\frametitle{Growth of Function}
\begin{Problem}[Growth of Function $\lbrack \textrm{\textbf{Test 1}}
\rbrack$]
$S(n) = 1^c + 2^c + 3^c + \ldots + n^c, c \in \mathbb{Z^{+}}.$
\begin{itemize}
\item $S(n) \in O(n^{c+1})$;
\item $S(n) \in \Omega(n^{c+1})$.
\end{itemize}
\end{Problem}
\vspace{0.30cm}
To prove: $\exists$ constants $a > 0, n_0 > 0$ such that $S(n) \geq a
n^{c+1}, \forall n \geq n_0$.
\[
S(n) \geq \underbrace{(\frac{n}{2})^{c} + (\frac{n}{2})^{c} + \ldots +
(\frac{n}{2})^{c}}_{\# = \frac{n}{2}}
= (\frac{n}{2})^{c} \cdot \frac{n}{2}
= \underbrace{\frac{1}{2^{c+1}}}_{a}n^{c+1}.
\]
\begin{block}{Remark:}
\begin{itemize}
\item inductive on \emph{constant} $c$
% \item $\int_{0}^{1} (1-x)^3 dx; (-x^3 + 3x^2 - 3x + 1); (x^4 - 4x^3 +
% 6x^2 - 4x + 1)$
\end{itemize}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%%%%%
\section{Recurrences}
\begin{frame}
\frametitle{List of Recurrences}
\begin{itemize}
\setlength{\itemsep}{8pt}
\item $T(n) = 2T(n-1) + O(1)$ \hfill $T(n) = O(2^n)$ Hanio tower
\item $T(n) = 7T(\frac{n}{2}) + O(n^2)$ \\ \hfill $T(n) = O(n^{2.81})$
Strassen matrix multiplication
\item $T(n) = 3T(\frac{n}{2}) + O(n)$ \\ \hfill $T(n) = O(n^{1.59})$ Gauss
integer multiplication
\item $T(n) = 2T(\frac{n}{2}) + O(n)$ \\ \hfill $T(n) = O(n \lg n)$ merge
sort, median-quicksort
\item $T(k) = 2T(\frac{k}{2}) + O(nk)$,
$T(n,k) = 2T(\frac{n}{2}, \frac{k}{2}) + O(n)$ \hfill in exam
\item $T(n) = T(\frac{n}{5}) + T(\frac{7n}{10}) + O(n)$ \hfill linear-time
selection
\item $T(n) = T(\frac{n}{2}) + O(1)$ \hfill $T(n) = O(\lg n)$ binary
search
\item $T(n) = 2T(\frac{n}{4}) + O(1)$ \hfill $T(n) = O(\sqrt{n})$ VLSI
layout
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Solving Recurrences}
\begin{Problem}[Solving Recurrences $\lbrack \textrm{\textbf{Test 2}}
\rbrack$]
\begin{itemize}
\item $T(n) = 5T(\frac{n}{2}) + \Theta(n)$ \hfill
\textcolor{blue}{$T(n) = \Theta(n^{\lg 5})$}
\item $T(n) = 9T(\frac{n}{3}) + \Theta(n^2)$ \hfill
\textcolor{blue}{$T(n) = \Theta(n^2 \lg n)$}
\item $T(n) = 2T(n-1) + O(1)$ \hfill
\textcolor{blue}{$T(n) = O(2^n)$}
\end{itemize}
\end{Problem}
\begin{block}{Remark:}
\begin{itemize}
\item $T(n) = 2T(n-1) + O(1)$: unfolding; recursion tree; \\
$(1 + 2 + \ldots + 2^{n-1}) O(1) = (2^{n}-1) O(1)$; \\
The Tower of Hanio.
\item which to choose?
\end{itemize}
\end{block}
\end{frame}
\begin{frame}
\frametitle{Merge Sort}
\begin{Problem}[Merge Sort $\lbrack \textrm{\textbf{Test 3}} \rbrack$]
$k$ sorted arrays, each with $n$ elements; merge-sort them.
\end{Problem}
\begin{itemize}
\item one by one: $2n + 3n + \ldots + kn = \frac{k^2 + k - 2}{2}n$
\item divide and conquer: $T(k) = 2T(\frac{k}{2}) + O(nk) = O(n \cdot k
\lg k)$; \\
unfolding the recursion; dfs (post-order); \\
layer by layer; recursion tree.
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{$k$-Sort}
\begin{Problem}[$k$-Sort $\lbrack \textrm{\textbf{Test 6}} \rbrack$]
$A[1 \ldots n]$, $k$ blocks, each of size $\frac{n}{k}$:
\begin{itemize}
\item sorted within each block
\item \emph{fuzzy} sorted among blocks
\end{itemize}
E.g., $1\; 2\; 4\; 3; 7\; 6\; 8\; 5; 10\; 11\; 9\; 12; 15\; 13\; 16\; 14$
\end{Problem}
\vspace{0.40cm}
It is a \emph{unfinished} median-quicksort.
\begin{itemize}
\item recursion of ``median + partition''
\item $T(n,k) = 2T(\frac{n}{2}, \frac{k}{2}) + O(n)$
\item recursion tree; $\lg k$ layers
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{VLSI Layout (1)}
\begin{Problem}[VLSI Layout]
Embed a complete binary tree with $n$ leaves into a grid with minimum area.
\begin{itemize}
\item VLSI: Very Large Scale Integration
\item complete binary tree circuit: $\#layer = 3,5,7,\ldots$
\item $n$ leaves (\textcolor{red}{why only leaves?})
\item grid; vertex + edge (no crossing)
\item area
\item take 5-layer complete binary tree as an example
\end{itemize}
\end{Problem}
\end{frame}
\begin{frame}
\frametitle{VLSI Layout (2)}
\begin{itemize}
\setlength{\itemsep}{0.50cm}
\item Na\"{\i}ve embedding
\[ H(n) = H(\frac{n}{2}) + \Theta(1) = \Theta(\lg n) \]
\[ W(n) = 2W(\frac{n}{2}) + \Theta(1) = \Theta(n) \]
\[ A(n) = \Theta(n \lg n) \]
\item Smart (H-Layout) embedding
\[ \Box \times \Box = n? \; 1 \times n;\; \frac{n}{\lg n} \times \lg n;\;
\textcolor{blue}{\sqrt{n} \times \sqrt{n}}
\]
Goal: $H(n) = \Theta(\sqrt{n}); W(n) = \Theta(\sqrt{n}); A(n) = \Theta(n).$
\[
H(n) = \Box H(\frac{n}{\Box}) + O(\Box); H(n) = 2 H(\frac{n}{4}) +
O(n^{\frac{1}{2} - \epsilon})
\]
\[ H(n) = 2H(\frac{n}{4}) + \Theta(1) \]
\centering \textcolor{blue}{Here it is: H-Layout}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Median of Two Sorted Arrays (1)}
\begin{Problem}[Median of Two Sorted Arrays $\lbrack {\bf P_{245}, 5.18}
\rbrack$]
$A[1 \ldots n], B[1 \ldots n]$; sorted, ascending order; distinct.
find the median of the combined set of $A$ and $B$ ($O(\lg n)$).
\end{Problem}
\[ T(n) = T(\frac{n}{2}) + \Theta(1) \]
\[A = 2,4,6,8,10 = \fbox{$A_1: (n-1)/2$}\; \fbox{$M_A: 1$}\; \fbox{$A_2:
(n-1)/2$} \]
\[B = 1,3,5,7,9 = \fbox{$B_1: (n-1)/2$}\; \fbox{$M_B: 1$}\; \fbox{$B_2:
(n-1)/2$} \]
\[
\fbox{$n$ \textrm{ is odd}} C = \fbox{$C_1: (n-1)$}\; \fbox{$M_C: 1$}\;
\fbox{$C_2: (n-1)$}
\]
\[
M_A > M_B \Rightarrow \cancel{M_A + A_2; B_1} \Rightarrow (A_1 + M_1, M_2 +
B_2)
\]
\textcolor{red}{why not $(A_1, M_2 + B_2)$?}
and not finished yet $\ldots$ (\textcolor{red}{why?})
\end{frame}
\begin{frame}
\frametitle{Median of Two Sorted Arrays (2)}
\textcolor{red}{To prove:} The median $M_C'$ of the subproblem $(A_1 + M_1,
M_2 + B_2)$ is also the median $M_C$ of the original problem $(A,B)$.
\vspace{0.50cm}
\textcolor{blue}{Proof: \textcolor{red}{why?}}
\[ M_C \in [M_B, M_A) \]
\[
M_C' \in [M_B, M_A)\; \fbox{$\frac{n+1}{2}-1$}\; \fbox{$M_C': 1$}\;
\fbox{$\frac{n+1}{2}-1$}
\]
\begin{block}{Extensions:}
\begin{itemize}
\item $A[1 \ldots n], B[1 \ldots n]$; not sorted;
\item $A[1 \ldots n], B[1 \ldots n], C[1 \ldots n]$; sorted; median
\item $A[1 \ldots n], B[1 \ldots n], \ldots$; sorted; median
\item $A[1 \ldots n], B[1 \ldots n], \ldots$; sorted; $k$-th smallest
\end{itemize}
\end{block}
\end{frame}
\begin{frame}
\frametitle{Two Stacks, One Queue (1)}
\begin{Problem}[Two Stacks, One Queue $\lbrack \textrm{\textbf{Test 4}}
\rbrack$]
two stacks $\Rightarrow$ one queue; correctness proof; amortized analysis
\begin{description}
\item[\textsc{Enqueue}$(x)$:] \textsc{Push}$(S_1, x)$;
\item[\textsc{Dequeue}$()$:] while $S_2 = \emptyset$,
\textsc{Push}$(S_2, \textsc{Pop}(S_1))$; \textsc{Pop}$(S_2)$;
\item[Ex:] \textsc{Enqueue}$(1,2,3)$, \textsc{Dequeue}$()$
\end{description}
\end{Problem}
\vspace{0.30cm}
Simple observation: \fbox{$S_1$ to push; $S_2$ to pop.}
\begin{align*}
FIFO &\Leftrightarrow \\
&\forall \textsc{De}_1 \prec \textsc{De}_2: a =
\textsc{De}_1, b = \textsc{De}_2 \Rightarrow \exists \textsc{En}_1(a) \prec
\textsc{En}_2(b).
\end{align*}
\begin{itemize}
\item Summation method: the sequence is (\uppercase{not}) known
\item Accounting method: $\hat{c_i} = c_i + a_i$; $\sum_i^n \hat{c_i} \geq
\sum_i^n c_i$; \fbox{$\sum_i^n a_i \geq 0, \forall n$}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Two Stacks, One Queue (2)}
\begin{table}
\begin{tabular}{ccccc}
item: & \textsc{Push} into $S_1$ & \textsc{Pop} from $S_1$ & \textsc{Push}
into $S_2$ & \textsc{Pop} from $S_2$ \\
& 1 & 1 & 1 & 1
\end{tabular}
\end{table}
\begin{table}
\begin{tabular}{cccc}
& $\hat{c_i}$ & $c_i$ & $a_i$ \\
\textsc{Enqueue} & 3 & 2 & 1 \\
\textsc{Dequeue} & 2 & 2 & 0
\end{tabular}
\end{table}
Ex: \textsc{Enqueue}$(1,2,3)$, \textsc{Dequeue}$()$
\[ \sum a_i = \#S_1 \times 2 \geq 0.\]
\end{frame}
\begin{frame}
\frametitle{Two Queues, One Stack (1)}
\begin{Problem}[Two Queues, One Stack]
implement/simulate a stack using two queues
\end{Problem}
Let's try [left: example; right: code]:
\begin{itemize}
\item push (1,2,3,4)
\item pop (4) $\Rightarrow Q_1 \xrightarrow{(1,2,3)} Q_2$
[\textcolor{blue}{transfer}]
\item pop (3) $\Rightarrow Q_2 \xrightarrow{(1,2)} Q_1$
\item push (5,6,7)
\item pop 7 $\Rightarrow Q_1 \xrightarrow{(1,2,5,6)} Q_2$
\end{itemize}
\vspace{0.50cm}
$Q_1$ for push; $Q_2$ for pop:
\begin{description}
\item[Push$(x)$:] Enqueue$(Q_1,x)$
\item[Pop$()$:] $Q_1 \xrightarrow{transfer} Q_2$; swap $Q_1 \leftrightarrow
Q_2$
\end{description}
\end{frame}
\begin{frame}
\frametitle{Two Queues, One Stack (2)}
Analysis:
\[ Push^{n}(Push^1 Pop^1)^{n/2} \]
\[
\sum c_i = n + (1 + (n+1)) \times \frac{n}{2} = n + (n+2) \times
\frac{n}{2} = (n^2 + 4n)/2
\]
\[ (\sum c_i)/n = (n+4)/2 = \Theta(n) \]
\begin{block}{Remark: \textcolor{red}{Why so bad?}}
\begin{itemize}
\item only use \emph{one} queue: push
(1,2,3,4); pop (4); [\textcolor{blue}{circulate}]
\item one queue + \textcolor{blue}{circulate}
\begin{description}
\item [\textsc{Push$(x)$}:] \textsc{Enqueue$(Q_1,x)$};
circulate$(Q_1)$
\item [\textsc{Pop$()$}:] \textsc{Dequeue$(Q_1)$}
\end{description}
\item review of ``array doubling'': expensive, cheap, cheap, $\ldots$,
expensive
\item \textsc{Push}: \textcolor{red}{expensive, cheap, cheap, $\ldots$,
expensive?}
\end{itemize}
\end{block}
\end{frame}
\begin{frame}
\frametitle{Two Queues, One Stack (3)}
Hey, $Q_2$:
\begin{itemize}
\item split the elements into $Q_2$ (cache vs. memory); \\
do not change \textsc{Pop} $\Rightarrow$ ``stack order''
\item $I_1$ [stack order]: $Q_1$ for top of stack; $Q_2$ for bottom of stack
\begin{description}
\item [\textsc{Push$(x)$}:] \textsc{Enqueue$(Q_1,x)$};
circulate$(Q_1)$
\item [\textsc{Pop$()$}:] if $Q_1 \neq \emptyset$
\textsc{Dequeue$(Q_1)$}; else \textsc{Dequeue$(Q_2)$}
\end{description}
\item $I_2$ [$\#Q_1 < \sqrt{\#Q_2}$]: keep $\#Q_1$ small
\end{itemize}
\vspace{0.50cm}
Ex:
\begin{itemize}
\item \textsc{Push$(1,2,3,4,5,6)$} :$Q_1: 6$; $Q_2: 5,4,3,2,1$
(\textcolor{red}{why?})
\item \textsc{Push$(7,8)$} \textcolor{red}{how to [transfer] now?}
\item $Q_2 \xrightarrow{transfer} Q_1$; swap $Q_1 \leftrightarrow Q_2$
\item \textsc{Push$(9,10,11)$}
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Two Queues, One Stack (4)}
\begin{itemize}
\setlength{\itemsep}{10pt}
\item ultimate code:
\begin{description}
\item [\textsc{Push$(x)$}:] \textsc{Enqueue$(Q_1,x)$};
circulate$(Q_1)$; \\
if $\#Q_1 \geq \sqrt{\#Q_2}$ \\
$Q_2 \xrightarrow{transfer} Q_1$; swap $Q_1 \leftrightarrow Q_2$;
\item [\textsc{Pop$()$}:] if $Q_1 \neq \emptyset$
\textsc{Dequeue$(Q_1)$}; else \textsc{Dequeue$(Q_2)$}
\end{description}
\item analysis: \textsc{Pop} ($O(1)$), \textsc{Push}:
\begin{description}
\item[cheap:] $\#Q_1 < \sqrt{\#Q_2} \Rightarrow O(\sqrt{n})$
\item[expensive:] $\#Q_1 \neq \sqrt{\#Q_2} \Rightarrow O(n)$
\item[amortized:] $E, \underbrace{C, C, \ldots, C}_{\# = O(\sqrt{n})}, E
\Rightarrow O(\sqrt{n})$
\end{description}
\end{itemize}
\end{frame}
%%%%%%%%%%%%%%%%%%%
% \section{A Spare Adversary}
%
% \begin{frame}
% \frametitle{01 Adversary}
%
% \begin{Problem}[01 Adversary $\lbrack {\bf P_{245}, 5.20} \rbrack$]
% bit array $A[1 \ldots n]$; if it contains the substring $01$? \\
% can we answer this question without looking at every bit?
% \end{Problem}
%
% \begin{itemize}
% \item $n$ is odd ($n=9$): check each \emph{even} bit $A[2], A[4], \ldots
% A[8]$
% \begin{itemize}
% \item all 1: $A[n]$
% \item all 0: $A[1]$
% \item all 1 come before 0 (1\;1\;0\;0): $A[4], A[6]$
% \item $\exists i < j, A[i] = 0, A[j] = 1\; (A[2], A[6])$
% \end{itemize}
% \item $n$ is even
% \begin{itemize}
% \item $1\;1\;1\;1\;1\;1\; \Box \Box \Box \Box \Box \Box\; 0\;0\;0\;0$
% \item Init: $l = 0; r = n + 1$
% \item Invariant: $r - l - 1$ is even
% \item \textsc{Look($i$):} $i \leq l \Rightarrow 1$; $i \geq r
% \Rightarrow 0$; \\
% $i-r$ is even $\Rightarrow (r \gets i; 0)$; \\
% $i-l$ is even $\Rightarrow (l \gets i; 1)$
% \end{itemize}
% \end{itemize}
% \end{frame}
% %%%%%%%%%%%%%%%%%%%
% \section*{Summary}
%%%%%%%%%%
\end{document}
|
library(readr)
library(lubridate)
library(chron)
library(reshape2)
grupos_municipios_prex11 <- MB_x11
View(grupos_municipios_prex11)
cnbv_muns<-grupos_municipios_prex11
cnbv_muns$ENT<-substr(cnbv_muns$CVEMUN,start = 0,stop = 2)
cnbv_muns_edo<-cnbv_muns %>% group_by(ENT,fecha) %>% summarise(bancomer=sum(bancomer),
banamex=sum(banamex),
valor=sum(valor),
otros=sum(otros)) %>%
filter(month(fecha)==12,year(fecha)>=2014)
ggplot(cnbv_muns_edo, aes(fecha, bancomer,color=ENT)) + geom_line()
ggplot(cnbv_muns_edo, aes(fecha, banamex,color=ENT)) + geom_line()
ggplot(cnbv_muns_edo, aes(fecha, valor,color=ENT)) + geom_line()
ggplot(cnbv_muns_edo, aes(fecha, otros,color=ENT)) + geom_line()
cnbv_edo_bancomer<-cnbv_muns_edo %>% select(ENT,fecha,bancomer) %>% dcast(ENT~fecha)
names(cnbv_edo_bancomer)<-c("CVEENT","bancomer_2014","bancomer_2015","bancomer_2016",
"bancomer_2017","bancomer_2018","bancomer_2019")
cnbv_edo_banamex<-cnbv_muns_edo %>% select(ENT,fecha,banamex) %>% dcast(ENT~fecha)
names(cnbv_edo_banamex)<-c("CVEENT","banamex_2014","banamex_2015","banamex_2016",
"banamex_2017","banamex_2018","banamex_2019")
cnbv_edo_valor<-cnbv_muns_edo %>% select(ENT,fecha,valor) %>% dcast(ENT~fecha)
names(cnbv_edo_valor)<-c("CVEENT","valor_2014","valor_2015","valor_2016",
"valor_2017","valor_2018","valor_2019")
cnbv_edo_otros<-cnbv_muns_edo %>% select(ENT,fecha,otros) %>% dcast(ENT~fecha)
names(cnbv_edo_otros)<-c("CVEENT","otros_2014","otros_2015","otros_2016",
"otros_2017","otros_2018","otros_2019")
#Por municipios
cnbv_muns<-cnbv_muns %>% group_by(ENT,CVEMUN,fecha) %>% summarise(bancomer=sum(bancomer),
banamex=sum(banamex),
valor=sum(valor),
otros=sum(otros)) %>%
filter(month(fecha)==12,year(fecha)>=2014)
cnbv_muns_bancomer<-cnbv_muns %>% select(ENT,CVEMUN,fecha,bancomer) %>% dcast(CVEMUN~fecha)
#names(cnbv_muns_bancomer)<-c("CVEENT","bancomer_2014","bancomer_2015","bancomer_2016")
cnbv_muns_banamex<-cnbv_muns %>% select(ENT,CVEMUN,fecha,banamex) %>% dcast(CVEMUN~fecha)
#names(cnbv_muns_banamex)<-c("CVEENT","banamex_2014","banamex_2015","banamex_2016")
cnbv_muns_valor<-cnbv_muns %>% select(ENT,CVEMUN,fecha,valor) %>% dcast(CVEMUN~fecha)
#names(cnbv_muns_valor)<-c("CVEENT","valor_2014","valor_2015","valor_2016")
cnbv_muns_otros<-cnbv_muns %>% select(ENT,CVEMUN,fecha,otros) %>% dcast(CVEMUN~fecha)
#names(cnbv_muns_otros)<-c("CVEENT","otros_2014","otros_2015","otros_2016")
|
Also serving communities of Stevens, Denver, New Holland.
There are 32 Assisted Living Facilities in the Ephrata area, with 4 in Ephrata and 28 nearby.
The average cost of assisted living in Ephrata is $4,137 per month. This is higher than the national median of $3,346. Cheaper nearby regions include Lititz with an average starting cost of $3,405.
To help you with your search, browse the 66 reviews below for assisted living facilities in Ephrata. On average, consumers rate assisted living in Ephrata 4.2 out of 5 stars. Better rated regions include Lititz with an average rating of 4.3 out of 5 stars.
Caring.com has helped thousands of families find high-quality senior care. To speak with one of our Family Advisors about assisted living options and costs in Ephrata, call (855) 863-8283.
Promotion ends in 58 days!
SPRING SPECIAL! $300 off rent for selected rooms & Community Fee discount for Veterans!!!
Ephrata is a borough of about 14,000 people in Lancaster County, 38 miles southeast of Harrisburg. Its population grew rapidly from 1970 to 2000, although it has remained stable since then. The city's senior population is currently at 13.8 percent. Ephrata seniors will find 32 assisted living facilities in the Ephrata area, with four in the borough itself and the other 28 in nearby areas such as Lancaster and Lititz. Title 55, Chapter 2800 of the Pennsylvania State Code regulates assisted living residences in the state. In addition to providing a residence, these living facilities also provide seniors with assistance in daily living activities.
Ephrata has mostly flat land with a moderate climate and steady rainfall throughout the year, making it suitable for farming. February has the most snow, with an average of 7.5 inches, although all months from November to April typically receive some snow. Seniors in Ephrata should be able to engage in outdoor activities throughout the majority of year.
Ephrata’s overall cost of living is about three percent higher than the national average. Utilities and groceries are the biggest contributors to the higher cost of living, at 23 percent and 11.5 percent of the national average respectively. Seniors living in Ephrata will need to budget their expenses more carefully than they would in many other U.S. locations.
The overall crime rate in Ephrata is lower than the average across the U.S. The crime rate in Ephrata is significantly lower than the rate for the entire state. This borough is therefore one of the safer areas for seniors in Pennsylvania.
Red Rose Transit provides public transportation for Lancaster, with Route 11 serving Ephrata. Seniors ride for free at all times with the Senior Free Ride Program sponsored by the state lottery. Disabled passengers pay half fare during non-peak hours.
The Ephrata Senior Center maintains a regular schedule for seniors which includes games, clubs, adult education and exercise. It also sponsors special events, including out-of-town trips. This senior center serves hot, buffet-style meals six days a week.
The Ephrata area is home to world-class medical facilities, including Ephrata Community Hospital and Lancaster General Health Urgent Care, in the event of medical emergencies or illness.
Assisted Living costs in Ephrata start around $4,137 per month on average, while the nationwide average cost of assisted living is $4,000 per month, according to the latest figures from Genworth’s Cost of Care Survey.
It’s important to note that assisted living rates in Ephrata and the surrounding suburbs can vary widely based on factors such as location, the level of care needed, apartment size and the types of amenities offered at each community.
Pennsylvania does not have any waivers to offset assisted living costs at this time, but the state does offer a supplement to SSI for residents in non-nursing residential care.
Ephrata and the surrounding area are home to numerous government agencies and non-profit organizations offering help for seniors searching for or currently residing in an assisted living community. These organizations can also provide assistance in a number of other eldercare services such as geriatric care management, elder law advice, estate planning, finding home care and health and wellness programs.
To see a list of free assisted living resources in Ephrata, please visit our Assisted Living in Pennsylvania page.
Ephrata-area assisted living communities must adhere to the comprehensive set of state laws and regulations that all assisted living communities in Pennsylvania are required to follow. Visit our Assisted Living in Pennsylvania page for more information about these laws. |
Formal statement is: corollary closed_vimage_Int[continuous_intros]: assumes "closed s" and "continuous_on t f" and t: "closed t" shows "closed (f -` s \<inter> t)" Informal statement is: If $f$ is a continuous function from a closed set $t$ to a topological space $X$, and $s$ is a closed subset of $X$, then $f^{-1}(s) \cap t$ is closed in $t$. |
Require Import
List
FJ.Base
FJ.Semantics.AuxiliarDefinitions
FJ.Syntax
FJ.Typing.Subtyping
FJ.Tactics.
(* type rules for expressions *)
Section TYPING.
Variable CT : ClassTable.
Reserved Notation "G '|--' e '::' C" (at level 58, e at next level).
Inductive StupidWarning : Set := StupidCast : StupidWarning.
Definition Gamma : Type := Map ClassName.
Inductive ExpHasType (G : Gamma) : Exp -> ClassName -> Prop :=
| T_Var : forall v C,
M.MapsTo v C G ->
G |-- (EVar v) :: C
| T_Field : forall e C fs fd fi n,
G |-- e :: C ->
fields CT n C fs ->
M.MapsTo fi fd fs ->
G |-- (EFieldAccess e fi) :: (fdtype fd)
| T_Invoc : forall e C0 Ds es m n mt,
G |-- e :: C0 ->
m_type_lookup CT n m C0 mt ->
Forall2 (ExpHasType G) es Ds ->
Forall2 (Subtype CT) Ds (mtparams mt) ->
G |-- EMethodInvoc e m es :: (mttype mt)
| T_New : forall C Ds Cs fs es n,
fields CT n C fs ->
Ds = map fdtype (values fs) ->
Forall2 (ExpHasType G) es Cs ->
Forall2 (Subtype CT) Cs Ds ->
G |-- (ENew C es) :: C
| T_UCast : forall e D C n,
G |-- e :: D ->
BoundedSubtype CT n D C ->
G |-- (ECast C e) :: C
| T_DCast : forall e C D n,
G |-- e :: D ->
BoundedSubtype CT n C D ->
C <> D ->
G |-- (ECast C e) :: C
| T_SCast : forall e D C n m,
G |-- e :: D ->
~ (BoundedSubtype CT n D C) ->
~ (BoundedSubtype CT m C D) ->
StupidWarning ->
G |-- (ECast C e) :: C
where "G '|--' e '::' C" := (ExpHasType G e C).
Definition mkGamma (fargs : list FormalArg) : Gamma :=
fold_left (fun ac f => M.add (get_name f) (ftype f) ac) fargs (M.empty _).
(* method typing *)
Inductive MethodOk : ClassName -> Method -> Prop :=
| T_Method
: forall CD C E0 MD n,
M.MapsTo C CD CT ->
mkGamma ((mkFormalArg this C) :: (margs MD)) |-- (mbody MD) :: E0 ->
Subtype CT E0 (mtype MD) ->
valid_override CT n (mname MD) (cextends CD)
(mkMethodType (map ftype (margs MD)) (mtype MD)) ->
MethodOk C MD.
(* class typing *)
Inductive ClassOk : ClassDecl -> Prop :=
| T_Class
: forall C CD D n dfds ms K fs,
M.MapsTo C CD CT ->
CD = mkClassDecl C D fs K ms ->
fields CT n D dfds ->
Forall (MethodOk C) (values ms) ->
ClassOk CD.
End TYPING.
Notation "CT ';' G '|--' e '::' C" := (ExpHasType CT G e C)(at level 58, e at next level).
Hint Constructors StupidWarning.
Hint Constructors ExpHasType.
Hint Constructors MethodOk.
|
lemma (in -) assumes "filterlim f (nhds L) F" shows tendsto_imp_filterlim_at_right: "eventually (\<lambda>x. f x > L) F \<Longrightarrow> filterlim f (at_right L) F" and tendsto_imp_filterlim_at_left: "eventually (\<lambda>x. f x < L) F \<Longrightarrow> filterlim f (at_left L) F" |
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <algorithm>
#include <boost/iterator/transform_iterator.hpp>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/TensorData.hpp"
#include "IO/H5/AccessType.hpp"
#include "IO/H5/File.hpp"
#include "IO/H5/VolumeData.hpp"
#include "NumericalAlgorithms/Spectral/Spectral.hpp"
#include "NumericalAlgorithms/SphericalHarmonics/Strahlkorper.hpp"
#include "NumericalAlgorithms/SphericalHarmonics/YlmSpherepack.hpp"
#include "Utilities/Algorithm.hpp"
#include "Utilities/ErrorHandling/Error.hpp"
#include "Utilities/FileSystem.hpp"
#include "Utilities/MakeString.hpp"
#include "Utilities/Numeric.hpp"
namespace {
template <typename T>
T multiply(const double obs_value, const T& component) {
T result = component;
for (auto& t : result) {
t *= obs_value;
}
return result;
}
// Check that the volume data is correct
template <typename DataType>
void check_volume_data(
const std::string& h5_file_name, const uint32_t version_number,
const size_t observation_id, const double observation_value,
const std::vector<DataType>& tensor_components_and_coords,
const std::vector<std::string>& grid_names,
const std::vector<std::vector<Spectral::Basis>>& bases,
const std::vector<std::vector<Spectral::Quadrature>>& quadratures,
const std::vector<std::vector<size_t>>& extents,
const std::vector<std::string>& expected_components,
const std::vector<std::vector<size_t>>& grid_data_orders) {
h5::H5File<h5::AccessType::ReadOnly> file_read{h5_file_name};
const auto& volume_file =
file_read.get<h5::VolumeData>("/element_data", version_number);
CHECK(extents == volume_file.get_extents(observation_id));
CHECK(volume_file.get_observation_value(observation_id) == observation_value);
// Check that all of the grid names were written correctly by checking their
// equality of elements
const std::vector<std::string> read_grid_names =
volume_file.get_grid_names(observation_id);
[&read_grid_names, &grid_names]() {
auto sortable_grid_names = grid_names;
auto sortable_read_grid_names = read_grid_names;
std::sort(sortable_grid_names.begin(), sortable_grid_names.end(),
std::less<>{});
std::sort(sortable_read_grid_names.begin(), sortable_read_grid_names.end(),
std::less<>{});
REQUIRE(sortable_read_grid_names == sortable_grid_names);
}();
// Find the order the grids were written in
std::vector<size_t> grid_positions(read_grid_names.size());
for (size_t i = 0; i < grid_positions.size(); i++) {
auto grid_name = grid_names[i];
auto position =
std::find(read_grid_names.begin(), read_grid_names.end(), grid_name);
// We know the grid name is in the read_grid_names because of the previous
// so we know `position` is an actual pointer to an element
grid_positions[i] =
static_cast<size_t>(std::distance(read_grid_names.begin(), position));
}
auto read_bases = volume_file.get_bases(observation_id);
alg::sort(read_bases, std::less<>{});
auto read_quadratures = volume_file.get_quadratures(observation_id);
alg::sort(read_quadratures, std::less<>{});
// We need non-const bases and quadratures in order to sort them, and we
// need them in their string form,
const auto& stringify = [](const auto& bases_or_quadratures) {
std::vector<std::vector<std::string>> local_target_data{};
local_target_data.reserve(bases_or_quadratures.size() + 1);
for (const auto& element_data : bases_or_quadratures) {
std::vector<std::string> target_axis_data{};
target_axis_data.reserve(element_data.size() + 1);
for (const auto& axis_datum : element_data) {
target_axis_data.emplace_back(MakeString{} << axis_datum);
}
local_target_data.push_back(target_axis_data);
}
return local_target_data;
};
auto target_bases = stringify(bases);
alg::sort(target_bases, std::less<>{});
auto target_quadratures = stringify(quadratures);
alg::sort(target_quadratures, std::less<>{});
CHECK(target_bases == read_bases);
CHECK(target_quadratures == read_quadratures);
const auto read_components =
volume_file.list_tensor_components(observation_id);
CHECK(alg::all_of(read_components,
[&expected_components](const std::string& id) {
return alg::found(expected_components, id);
}));
// Helper Function to get number of points on a particular grid
const auto accumulate_extents = [](const std::vector<size_t>& grid_extents) {
return alg::accumulate(grid_extents, 1, std::multiplies<>{});
};
const auto read_extents = volume_file.get_extents(observation_id);
std::vector<size_t> element_num_points(
boost::make_transform_iterator(read_extents.begin(), accumulate_extents),
boost::make_transform_iterator(read_extents.end(), accumulate_extents));
const auto read_points_by_element = [&element_num_points]() {
std::vector<size_t> read_points(element_num_points.size());
read_points[0] = 0;
for (size_t index = 1; index < element_num_points.size(); index++) {
read_points[index] =
read_points[index - 1] + element_num_points[index - 1];
}
return read_points;
}();
// Given a DataType, corresponding to contiguous data read out of a
// file, find the data which was written by the grid whose extents are
// found at position `grid_index` in the vector of extents.
const auto get_grid_data = [&element_num_points, &read_points_by_element](
const DataVector& all_data,
const size_t grid_index) {
DataType result(element_num_points[grid_index]);
// clang-tidy: do not use pointer arithmetic
std::copy(&all_data[read_points_by_element[grid_index]],
&all_data[read_points_by_element[grid_index]] + // NOLINT
element_num_points[grid_index],
result.begin());
return result;
};
// The tensor components can be written in any order to the file, we loop
// over the expected components rather than the read components because they
// are in a particular order.
for (size_t i = 0; i < expected_components.size(); i++) {
const auto& component = expected_components[i];
// for each grid
for (size_t j = 0; j < grid_names.size(); j++) {
CHECK(get_grid_data(
volume_file.get_tensor_component(observation_id, component),
grid_positions[j]) ==
multiply(observation_value,
tensor_components_and_coords[grid_data_orders[j][i]]));
}
}
}
void test_strahlkorper() {
constexpr size_t l_max = 12;
constexpr size_t m_max = 12;
constexpr double sphere_radius = 4.0;
constexpr std::array<double, 3> center{{5.0, 6.0, 7.0}};
const Strahlkorper<Frame::Inertial> strahlkorper{l_max, m_max, sphere_radius,
center};
const YlmSpherepack& ylm = strahlkorper.ylm_spherepack();
const std::array<DataVector, 2> theta_phi = ylm.theta_phi_points();
const DataVector theta = theta_phi[0];
const DataVector phi = theta_phi[1];
const DataVector sin_theta = sin(theta);
const DataVector radius = ylm.spec_to_phys(strahlkorper.coefficients());
const std::string grid_name{"AhA"};
const std::vector<DataVector> tensor_and_coord_data{
radius * sin_theta * cos(phi), radius * sin_theta * sin(phi),
radius * cos(theta), cos(2.0 * theta)};
const std::vector<TensorComponent> tensor_components{
{grid_name + "/InertialCoordinates_x", tensor_and_coord_data[0]},
{grid_name + "/InertialCoordinates_y", tensor_and_coord_data[1]},
{grid_name + "/InertialCoordinates_z", tensor_and_coord_data[2]},
{grid_name + "/TestScalar", tensor_and_coord_data[3]}};
const std::vector<size_t> observation_ids{4444};
const std::vector<double> observation_values{1.0};
const std::vector<Spectral::Basis> bases{2,
Spectral::Basis::SphericalHarmonic};
const std::vector<Spectral::Quadrature> quadratures{
{Spectral::Quadrature::Gauss, Spectral::Quadrature::Equiangular}};
const std::string h5_file_name{"Unit.IO.H5.VolumeData.Strahlkorper.h5"};
const uint32_t version_number = 4;
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
const std::vector<size_t> extents{
{ylm.physical_extents()[0], ylm.physical_extents()[1]}};
{
h5::H5File<h5::AccessType::ReadWrite> strahlkorper_file{h5_file_name};
auto& volume_file = strahlkorper_file.insert<h5::VolumeData>(
"/element_data", version_number);
volume_file.write_volume_data(
observation_ids[0], observation_values[0],
std::vector<ElementVolumeData>{
{extents, tensor_components, bases, quadratures}});
strahlkorper_file.close_current_object();
// Open the read volume file and check that the observation id and values
// are correct.
const auto& volume_file_read =
strahlkorper_file.get<h5::VolumeData>("/element_data", version_number);
const auto read_observation_ids = volume_file_read.list_observation_ids();
CHECK(read_observation_ids == std::vector<size_t>{4444});
CHECK(volume_file_read.get_observation_value(observation_ids[0]) ==
observation_values[0]);
}
check_volume_data(h5_file_name, version_number, observation_ids[0],
observation_values[0], tensor_and_coord_data, {{grid_name}},
{bases}, {quadratures}, {extents},
{"InertialCoordinates_x", "InertialCoordinates_y",
"InertialCoordinates_z", "TestScalar"},
{{0, 1, 2, 3}});
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
}
template <typename DataType>
void test() {
const std::string h5_file_name("Unit.IO.H5.VolumeData.h5");
const uint32_t version_number = 4;
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
h5::H5File<h5::AccessType::ReadWrite> my_file(h5_file_name);
const std::vector<DataType> tensor_components_and_coords{
{8.9, 7.6, 3.9, 2.1, 18.9, 17.6, 13.9, 12.1},
{0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0},
{0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0},
{0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0},
{-78.9, -7.6, -1.9, 8.1, 6.3, 8.7, 9.8, 0.2},
{-7.9, 7.6, 1.9, -8.1, -6.3, 2.7, 6.8, -0.2},
{17.9, 27.6, 21.9, -28.1, -26.3, 32.7, 26.8, -30.2}};
const std::vector<size_t> observation_ids{8435087234, size_t(-1)};
const std::vector<double> observation_values{8.0, 2.3};
const std::vector<std::string> grid_names{"[[2,3,4]]", "[[5,6,7]]"};
const std::vector<std::vector<Spectral::Basis>> bases{
{3, Spectral::Basis::Chebyshev}, {3, Spectral::Basis::Legendre}};
const std::vector<std::vector<Spectral::Quadrature>> quadratures{
{3, Spectral::Quadrature::Gauss},
{3, Spectral::Quadrature::GaussLobatto}};
{
auto& volume_file =
my_file.insert<h5::VolumeData>("/element_data", version_number);
const auto write_to_file = [&volume_file, &tensor_components_and_coords,
&grid_names, &bases,
&quadratures](const size_t observation_id,
const double observation_value) {
std::string first_grid = grid_names.front();
std::string last_grid = grid_names.back();
volume_file.write_volume_data(
observation_id, observation_value,
std::vector<ElementVolumeData>{
{{2, 2, 2},
{TensorComponent{first_grid + "/S",
multiply(observation_value,
tensor_components_and_coords[0])},
TensorComponent{first_grid + "/x-coord",
multiply(observation_value,
tensor_components_and_coords[1])},
TensorComponent{first_grid + "/y-coord",
multiply(observation_value,
tensor_components_and_coords[2])},
TensorComponent{first_grid + "/z-coord",
multiply(observation_value,
tensor_components_and_coords[3])},
TensorComponent{first_grid + "/T_x",
multiply(observation_value,
tensor_components_and_coords[4])},
TensorComponent{first_grid + "/T_y",
multiply(observation_value,
tensor_components_and_coords[5])},
TensorComponent{first_grid + "/T_z",
multiply(observation_value,
tensor_components_and_coords[6])}},
bases.front(),
quadratures.front()},
// Second Element Data
{{2, 2, 2},
{TensorComponent{last_grid + "/S",
multiply(observation_value,
tensor_components_and_coords[1])},
TensorComponent{last_grid + "/x-coord",
multiply(observation_value,
tensor_components_and_coords[0])},
TensorComponent{last_grid + "/y-coord",
multiply(observation_value,
tensor_components_and_coords[5])},
TensorComponent{last_grid + "/z-coord",
multiply(observation_value,
tensor_components_and_coords[3])},
TensorComponent{last_grid + "/T_x",
multiply(observation_value,
tensor_components_and_coords[6])},
TensorComponent{last_grid + "/T_y",
multiply(observation_value,
tensor_components_and_coords[4])},
TensorComponent{last_grid + "/T_z",
multiply(observation_value,
tensor_components_and_coords[2])}},
bases.back(),
quadratures.back()}});
};
for (size_t i = 0; i < observation_ids.size(); ++i) {
write_to_file(observation_ids[i], observation_values[i]);
}
}
// Open the read volume file and check that the observation id and values are
// correct.
const auto& volume_file =
my_file.get<h5::VolumeData>("/element_data", version_number);
const auto read_observation_ids = volume_file.list_observation_ids();
// The observation IDs should be sorted by their observation value
CHECK(read_observation_ids == std::vector<size_t>{size_t(-1), 8435087234});
{
INFO("Test find_observation_id");
std::vector<size_t> found_observation_ids(observation_values.size());
std::transform(observation_values.begin(), observation_values.end(),
found_observation_ids.begin(),
[&volume_file](const double observation_value) {
return volume_file.find_observation_id(observation_value);
});
CHECK(found_observation_ids == observation_ids);
}
for (size_t i = 0; i < observation_ids.size(); ++i) {
check_volume_data(
h5_file_name, version_number, observation_ids[i], observation_values[i],
tensor_components_and_coords, grid_names, bases, quadratures,
{{2, 2, 2}, {2, 2, 2}},
{"S", "x-coord", "y-coord", "z-coord", "T_x", "T_y", "T_z"},
{{0, 1, 2, 3, 4, 5, 6}, {1, 0, 5, 3, 6, 4, 2}});
}
{
INFO("offset_and_length_for_grid");
const size_t observation_id = observation_ids.front();
// [find_offset]
const auto all_grid_names = volume_file.get_grid_names(observation_id);
const auto all_extents = volume_file.get_extents(observation_id);
const auto first_grid_offset_and_length = h5::offset_and_length_for_grid(
grid_names.front(), all_grid_names, all_extents);
// [find_offset]
CHECK(first_grid_offset_and_length.first == 0);
CHECK(first_grid_offset_and_length.second == 8);
const auto last_grid_offset_and_length = h5::offset_and_length_for_grid(
grid_names.back(), all_grid_names, all_extents);
CHECK(last_grid_offset_and_length.first == 8);
CHECK(last_grid_offset_and_length.second == 8);
}
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
}
} // namespace
SPECTRE_TEST_CASE("Unit.IO.H5.VolumeData", "[Unit][IO][H5]") {
test<DataVector>();
test<std::vector<float>>();
test_strahlkorper();
#ifdef SPECTRE_DEBUG
CHECK_THROWS_WITH(
[]() {
const std::string h5_file_name(
"Unit.IO.H5.VolumeData.ComponentFormat.h5");
const uint32_t version_number = 4;
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
h5::H5File<h5::AccessType::ReadWrite> my_file(h5_file_name);
auto& volume_file =
my_file.insert<h5::VolumeData>("/element_data", version_number);
volume_file.write_volume_data(
100, 10.0,
{{{2},
{TensorComponent{"S", DataVector{1.0, 2.0}}},
{Spectral::Basis::Legendre},
{Spectral::Quadrature::Gauss}}});
}(),
Catch::Contains(
"The expected format of the tensor component names is "
"'GROUP_NAME/COMPONENT_NAME' but could not find a '/' in"));
CHECK_THROWS_WITH(
[]() {
const std::string h5_file_name(
"Unit.IO.H5.VolumeData.ComponentFormat1.h5");
const uint32_t version_number = 4;
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
h5::H5File<h5::AccessType::ReadWrite> my_file(h5_file_name);
auto& volume_file =
my_file.insert<h5::VolumeData>("/element_data", version_number);
volume_file.write_volume_data(
100, 10.0,
{{{2},
{TensorComponent{"A/S", DataVector{1.0, 2.0}},
TensorComponent{"S", DataVector{1.0, 2.0}}},
{Spectral::Basis::Legendre},
{Spectral::Quadrature::Gauss}}});
}(),
Catch::Contains(
"The expected format of the tensor component names is "
"'GROUP_NAME/COMPONENT_NAME' but could not find a '/' in"));
CHECK_THROWS_WITH(
[]() {
const std::string h5_file_name("Unit.IO.H5.VolumeData.WriteTwice.h5");
const uint32_t version_number = 4;
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
h5::H5File<h5::AccessType::ReadWrite> my_file(h5_file_name);
auto& volume_file =
my_file.insert<h5::VolumeData>("/element_data", version_number);
volume_file.write_volume_data(
100, 10.0,
{{{2},
{TensorComponent{"A/S", DataVector{1.0, 2.0}},
TensorComponent{"A/S", DataVector{1.0, 2.0}}},
{Spectral::Basis::Legendre},
{Spectral::Quadrature::Gauss}}});
}(),
Catch::Contains(
"Trying to write tensor component 'S' which already exists in HDF5 "
"file in group 'element_data.vol/ObservationId100'"));
#endif
CHECK_THROWS_WITH(
[]() {
const std::string h5_file_name(
"Unit.IO.H5.VolumeData.FindNoObservationId.h5");
const uint32_t version_number = 4;
if (file_system::check_if_file_exists(h5_file_name)) {
file_system::rm(h5_file_name, true);
}
h5::H5File<h5::AccessType::ReadWrite> h5_file(h5_file_name);
auto& volume_file =
h5_file.insert<h5::VolumeData>("/element_data", version_number);
volume_file.write_volume_data(
100, 10.0,
{{{2},
{TensorComponent{"A/S", DataVector{1.0, 2.0}}},
{Spectral::Basis::Legendre},
{Spectral::Quadrature::Gauss}}});
volume_file.find_observation_id(11.0);
}(),
Catch::Contains("No observation with value"));
}
|
import data.real.basic
import data.set.basic
open finset
-- We think of social states as type `σ` and inidividuals as type `ι`
variables {σ ι : Type*}
/-!
## Notes
* "All individuals rank" refers to the rankings of each and every individual.
* "Society ranks" refers to output of a social welfare function
(e.g. the final result of an election process).
* <Andrew: Can you please write something describing what a social welfare function is? Thanks!>
## Important Definitions
-/
/-- A social welfare function satisfies the Weak Pareto criterion if, for any two social states
`x` and `y`, every individual ranking `y` higher than `x` implies that society ranks `y` higher
than `x`. -/
def weak_pareto (f : (ι → σ → ℝ) → σ → ℝ) (X : finset σ) : Prop :=
∀ (x y ∈ X) (P : ι → σ → ℝ), (∀ i, P i x < P i y) → (f P) x < (f P) y
/-- Suppose that for any two social states `x` and `y`, every individual's ranking of `x` and `y`
remains unchanged between two rankings `P₁` and `P₂`. We say that a social welfare function is
*independent of irrelevant alternatives* if society's ranking of `x` and `y` also remains
unchanged between `P₁` and `P₂`. -/
def ind_of_irr_alts (f : (ι → σ → ℝ) → σ → ℝ) (X : finset σ) : Prop :=
∀ (x y ∈ X) (P₁ P₂ : ι → σ → ℝ),
(∀ i, P₁ i x < P₁ i y ↔ P₂ i x < P₂ i y) → (f P₁ x < f P₁ y ↔ f P₂ x < f P₂ y)
/-- An individual is a *dictator* with respect to a given social welfare function if their
ranking determines society's ranking of any two social states. -/
def is_dictator (f : (ι → σ → ℝ) → σ → ℝ) (X : finset σ) (i : ι) : Prop :=
∀ (x y ∈ X) (P : ι → σ → ℝ), P i x < P i y → f P x < f P y
/-- A social welfare function is called a *dictatorship* if there exists a dictator with respect to
that function. -/
def is_dictatorship (f : (ι → σ → ℝ) → σ → ℝ) (X : finset σ) : Prop :=
∃ i, is_dictator f X i
/-- An individual is a dictator over all social states in a given set *except* `b`
if they are a dictator over every pair of distinct alternatives not equal to `b`. -/
def is_dictator_except (f : (ι → σ → ℝ) → (σ → ℝ)) (X : finset σ) (i : ι) (b : σ) : Prop :=
∀ a c ∈ X, a ≠ b → c ≠ b → ∀ P : ι → σ → ℝ, P i a < P i c → f P a < f P c
/-- A social welfare function is called a dictatorship over all social states in a given set
*except* `b` if there exists a dictator over every pair of distinct alternatives not equal
to `b`. -/
def is_dictatorship_except (f : (ι → σ → ℝ) → (σ → ℝ)) (X : finset σ) (b : σ) : Prop :=
∃ i, is_dictator_except f X i b
/-- A social state `b` is *strictly worst* of a finite set of social states `X` with respect to
a ranking `p` if `b` is ranked strictly lower than every other `a ∈ X`. -/
def is_strictly_worst (b : σ) (p : σ → ℝ) (X : finset σ) : Prop :=
∀ a ∈ X, a ≠ b → p b < p a
/-- A social state `b` is *strictly best* of a finite set of social states `X` with respect to
a ranking `p` if `b` is ranked strictly higher than every other `a ∈ X`. -/
def is_strictly_best (b : σ) (p : σ → ℝ) (X : finset σ) : Prop :=
∀ a ∈ X, a ≠ b → p a < p b
/-- A social state `b` is *extremal* with respect to a finite set of social states `X`
and a ranking `p` if `b` is either bottom or top of `X`. -/
def is_extremal (b : σ) (p : σ → ℝ) (X : finset σ) : Prop :=
is_strictly_worst b p X ∨ is_strictly_best b p X
/-- Social sates `s₁`, `s₂`, `s₃`, and `s₄` have the *same order* with respect to two rankings
`p₁` and `p₂` if `s₁` and `s₂` have the same ranking in `p₁` as `s₃` and `s₄` have in `p₂`. -/
def same_order (p₁ p₂ : σ → ℝ) (s₁ s₂ s₃ s₄ : σ) : Prop :=
(p₁ s₁ < p₁ s₂ ↔ p₂ s₃ < p₂ s₄) ∧ (p₁ s₂ < p₁ s₁ ↔ p₂ s₄ < p₂ s₃)
/-- An individual `i` is *pivotal* with respect to a social welfare function and a social state `b`
if there exist rankings `P` and `P'` such that:
(1) all individuals except for `i` rank all social states in the same order in both rankings
(2) all individuals place `b` in an extremal position in both rankings
(3) `i` ranks `b` bottom of their rankings in `P`, but top of their rankings in `P'`
(4) society ranks `b` bottom of its rankings in `P`, but top of its rankings in `P'` -/
def is_pivotal (f : (ι → σ → ℝ) → (σ → ℝ)) (X : finset σ) (i : ι) (b : σ) : Prop :=
∃ (P P' : ι → σ → ℝ),
(∀ j : ι, j ≠ i → ∀ x y ∈ X, same_order (P j) (P' j) x y x y) ∧
(∀ j : ι, is_extremal b (P j) X) ∧ (∀ j : ι, is_extremal b (P' j) X) ∧
(is_strictly_worst b (P i) X) ∧ (is_strictly_best b (P' i) X) ∧
(is_strictly_worst b (f P) X) ∧ (is_strictly_best b (f P') X)
/-- A social welfare function has a *pivot* with respect to a social state `b` if there exists an
individual who is pivotal with respect to that function and `b`. -/
def has_pivot (f : (ι → σ → ℝ) → (σ → ℝ)) (X : finset σ) (b : σ) : Prop :=
∃ i, is_pivotal f X i b
open function
/-- Given an arbitary ranking `p`, social state `b`, and finite set of social states `X`,
`maketop b p X` updates `p` so that `b` is now ranked at the top of `X`. -/
noncomputable def maketop [decidable_eq σ]
(p : σ → ℝ) (b : σ) (X : finset σ) (hX : X.nonempty) : σ → ℝ :=
update p b $ ((X.image p).max' (hX.image p)) + 1
/-- Given an arbitary ranking `p`, social state `b`, and finite set of social states `X`,
`makebot b p X` updates `p` so that `b` is now ranked at the bottom of `X`. -/
noncomputable def makebot [decidable_eq σ]
(p : σ → ℝ) (b : σ) (X : finset σ) (hX : X.nonempty) : σ → ℝ :=
update p b $ ((X.image p).min' (hX.image p)) - 1
/-- Given an arbitary ranking `p` and social states `a`, `b`, and `c`,
`makebetween p a b c` updates `p` so that `b` is now ranked between `a` and `c`. -/
noncomputable def makebetween [decidable_eq σ]
(p : σ → ℝ) (a b c : σ) : σ → ℝ :=
update p b $ (p a + p c) / 2
-- ## Preliminary Lemmas
variables {a b c d : σ} {p : σ → ℝ} {P : ι → σ → ℝ} {f : (ι → σ → ℝ) → σ → ℝ} {X : finset σ}
lemma exists_second_distinct_mem (hX : 2 ≤ X.card) (a_in : a ∈ X) :
∃ b ∈ X, b ≠ a :=
begin
classical,
have hpos : 0 < (X.erase a).card,
{ rw card_erase_of_mem a_in,
exact zero_lt_one.trans_le (nat.pred_le_pred hX) },
cases card_pos.mp hpos with b hb,
cases mem_erase.mp hb with hne H,
exact ⟨b, H, hne⟩,
end
lemma exists_third_distinct_mem (hX : 2 < X.card) (a_in : a ∈ X) (b_in : b ∈ X) (h : a ≠ b) :
∃ c ∈ X, c ≠ a ∧ c ≠ b :=
begin
classical,
have hpos : 0 < ((X.erase b).erase a).card,
{ simpa only [card_erase_of_mem, mem_erase_of_ne_of_mem h a_in, b_in]
using nat.pred_le_pred (nat.pred_le_pred hX) },
cases card_pos.mp hpos with c hc,
simp_rw mem_erase at hc,
exact ⟨c, hc.2.2, hc.1, hc.2.1⟩,
end
lemma is_strictly_best.not_strictly_worst (htop : is_strictly_best b p X) (h : ∃ a ∈ X, a ≠ b) : ¬is_strictly_worst b p X :=
begin
simp only [is_strictly_worst, not_forall, not_lt, exists_prop],
rcases h with ⟨a, a_in, hab⟩,
exact ⟨a, a_in, hab, (htop a a_in hab).le⟩,
end
lemma is_strictly_best.not_strictly_worst' (htop : is_strictly_best b p X) (hX : 2 ≤ X.card) (hb : b ∈ X) : ¬is_strictly_worst b p X :=
htop.not_strictly_worst $ exists_second_distinct_mem hX hb
lemma is_strictly_worst.not_strictly_best (hbot : is_strictly_worst b p X) (h : ∃ a ∈ X, a ≠ b) : ¬is_strictly_best b p X :=
begin
simp only [is_strictly_best, not_forall, not_lt, exists_prop],
rcases h with ⟨a, a_in, hab⟩,
exact ⟨a, a_in, hab, (hbot a a_in hab).le⟩,
end
lemma is_strictly_worst.not_strictly_best' (hbot : is_strictly_worst b p X) (hX : 2 ≤ X.card) (hb : b ∈ X) : ¬is_strictly_best b p X :=
hbot.not_strictly_best $ exists_second_distinct_mem hX hb
lemma is_extremal.is_strictly_best (hextr : is_extremal b p X) (not_strictly_worst : ¬is_strictly_worst b p X) :
is_strictly_best b p X :=
hextr.resolve_left not_strictly_worst
lemma is_extremal.is_strictly_worst (hextr : is_extremal b p X) (not_strictly_best : ¬is_strictly_best b p X) :
is_strictly_worst b p X :=
hextr.resolve_right not_strictly_best
lemma is_strictly_worst.is_extremal (hbot : is_strictly_worst b p X) : is_extremal b p X :=
or.inl hbot
lemma is_strictly_best.is_extremal (hbot : is_strictly_best b p X) : is_extremal b p X :=
or.inr hbot
/-- If every individual ranks a social state `b` at the top of its rankings, then society must also
rank `b` at the top of its rankings. -/
theorem is_strictly_best_of_forall_is_strictly_best (b_in : b ∈ X) (hwp : weak_pareto f X)
(htop : ∀ i, is_strictly_best b (P i) X) :
is_strictly_best b (f P) X :=
λ a a_in hab, hwp a b a_in b_in P $ λ i, htop i a a_in hab
/-- If every individual ranks a social state `b` at the bottom of its rankings, then society must
also rank `b` at the bottom of its rankings. -/
theorem is_strictly_worst_of_forall_is_strictly_worst (b_in : b ∈ X) (hwp : weak_pareto f X)
(hbot : ∀ i, is_strictly_worst b (P i) X) :
is_strictly_worst b (f P) X :=
λ a a_in hab, hwp b a b_in a_in P $ λ i, hbot i a a_in hab
lemma exists_of_not_extremal (hX : 3 ≤ X.card) (hb : b ∈ X) (h : ¬ is_extremal b (f P) X):
∃ a c ∈ X, a ≠ b ∧ c ≠ b ∧ a ≠ c ∧ f P b ≤ f P a ∧ f P c ≤ f P b :=
begin
unfold is_extremal is_strictly_worst is_strictly_best at h, push_neg at h,
obtain ⟨⟨c, hc, hcb, hPc⟩, ⟨a, ha, hab, hPa⟩⟩ := h,
obtain hac | rfl := ne_or_eq a c, { exact ⟨a, c, ha, hc, hab, hcb, hac, hPa, hPc⟩ },
obtain ⟨d, hd, hda, hdb⟩ := exists_third_distinct_mem hX ha hb hab,
cases lt_or_le (f P b) (f P d),
{ exact ⟨d, a, hd, hc, hdb, hcb, hda, h.le, hPc⟩ },
{ exact ⟨a, d, ha, hd, hab, hdb, hda.symm, hPa, h⟩ },
end
lemma nonempty_of_mem {s : finset σ} {a : σ} (ha : a ∈ s) : s.nonempty :=
nonempty_of_ne_empty $ ne_empty_of_mem ha
section make
variable [decidable_eq σ]
lemma maketop_noteq (p) (hab : a ≠ b) (hX : X.nonempty) :
maketop p b X hX a = p a :=
update_noteq hab _ p
lemma makebot_noteq (p) (hab : a ≠ b) (hX : X.nonempty) :
makebot p b X hX a = p a :=
update_noteq hab _ p
lemma makebetween_noteq (p) (hdb : d ≠ b) :
makebetween p a b c d = p d :=
update_noteq hdb ((p a + p c) / 2) p
lemma makebetween_eq (a b c : σ) (p) :
makebetween p a b c b = (p a + p c) / 2 :=
update_same _ _ _
lemma maketop_lt_maketop (p) (hab : a ≠ b) (ha : a ∈ X) :
maketop p b X (nonempty_of_mem ha) a < maketop p b X (nonempty_of_mem ha) b :=
by simpa [maketop, hab] using
((X.image p).le_max' _ (mem_image_of_mem p ha)).trans_lt (lt_add_one _)
lemma makebot_lt_makebot (p) (hcb : c ≠ b) (hc : c ∈ X) :
makebot p b X (nonempty_of_mem hc) b < makebot p b X (nonempty_of_mem hc) c :=
by simpa [makebot, hcb] using sub_lt_iff_lt_add'.mpr
(((X.image p).min'_le (p c) (mem_image_of_mem p hc)).trans_lt (lt_one_add _))
lemma makebetween_lt_makebetween_top (hcb : c ≠ b) (hp : p a < p c) :
makebetween p a b c b < makebetween p a b c c :=
begin
simp only [makebetween, update_same, update_noteq hcb],
linarith,
end
lemma makebetween_lt_makebetween_bot (hab : a ≠ b) (hp : p a < p c) :
makebetween p a b c a < makebetween p a b c b :=
begin
simp only [makebetween, update_same, update_noteq hab],
linarith,
end
lemma top_of_maketop (b p) (hX : X.nonempty) :
is_strictly_best b (maketop p b X hX) X :=
λ a ha hab, maketop_lt_maketop p hab ha
end make
-- ## The Proof
/-- Let `f` be a SWF satisfying WP and IoIA, `P` be a preference ordering, `X` be a finite set
containing at least 3 social states, and `b` be one of those social states.
If every individial ranks `b` extremally, then society also ranks `b` extremally w.r.t. `f`. -/
lemma first_step (hwp : weak_pareto f X) (hind : ind_of_irr_alts f X)
(hX : 3 ≤ X.card) (hb : b ∈ X) (hextr : ∀ i, is_extremal b (P i) X) :
is_extremal b (f P) X :=
begin
classical,
by_contra hnot,
obtain ⟨a, c, ha, hc, hab, hcb, hac, hPa, hPc⟩ := exists_of_not_extremal hX hb hnot,
refine ((not_lt.mp ((not_congr (hind b c hb hc P _ (λ i, ⟨λ hP, _, λ hP', _⟩))).mp
hPc.not_lt)).trans (not_lt.mp ((not_congr (hind a b ha hb P _ (λ i, ⟨λ hP, _, λ hP', _⟩))).mp
hPa.not_lt))).not_lt (hwp a c ha hc _ (λ i, _)),
{ exact λ j, if is_strictly_best b (P j) X then makebetween (P j) a c b else update (P j) c (P j a + 1) },
{ have h : ¬ is_strictly_best b (P i) X := λ h, asymm hP (h c hc hcb),
convert lt_add_of_lt_of_pos ((hextr i).is_strictly_worst h a ha hab) _; simp [h, hcb.symm] },
{ by_contra hP,
have h : is_strictly_best b (P i) X := (hextr i).is_strictly_best (λ h, hP (h c hc hcb)),
simp only at hP', simp only [if_pos h, makebetween_noteq _ hcb.symm, makebetween_eq] at hP',
linarith [h a ha hab] },
{ by_cases h : is_strictly_best b (P i) X; simpa [h, makebetween_noteq, hac, hcb.symm] },
{ by_contra hP,
have h : ¬ is_strictly_best b (P i) X := λ h, hP (h a ha hab),
simp only at hP', simp [if_neg h, hac, hcb.symm] at hP',
exact hP hP' },
{ by_cases h : is_strictly_best b (P i) X,
{ simp [if_pos h, makebetween_lt_makebetween_bot hac (h a ha hab)] },
{ simp [if_neg h, hac] } },
end
/-- An auxiliary lemma for the second step, in which we perform induction on the finite set
`D' := {i ∈ univ | is_strictly_worst b (P i) X}`. Its statement is formulated so strangely (involving `D'`
and `P`) to allow for this induction.
Essentially, what we are doing here is showing that, for a social welfare function `f` under the
appropriate conditions, we can always a construct circumstances so that `f` has a pivot with
respect to a given social state. -/
lemma second_step_aux [fintype ι]
(hwp : weak_pareto f X) (hind : ind_of_irr_alts f X)
(hX : 2 < X.card) (b_in : b ∈ X) {D' : finset ι} :
∀ {P : ι → σ → ℝ}, D' = {i ∈ univ | is_strictly_worst b (P i) X} →
(∀ i, is_extremal b (P i) X) → is_strictly_worst b (f P) X → has_pivot f X b :=
begin
classical,
refine finset.induction_on D'
(λ P h hextr hbot, absurd (is_strictly_best_of_forall_is_strictly_best b_in hwp (λ j, (hextr j).is_strictly_best _))
(hbot.not_strictly_best (exists_second_distinct_mem hX.le b_in)))
(λ i D hi IH P h_insert hextr hbot, _),
{ simpa using eq_empty_iff_forall_not_mem.mp h.symm j },
{ have hX' := nonempty_of_mem b_in,
have hextr' : ∀ j, is_extremal b (ite (j = i) (maketop (P j) b X hX') (P j)) X,
{ intro j,
by_cases hji : j = i,
{ refine or.inr (λ a a_in hab, _),
simp only [if_pos hji, maketop_lt_maketop _ hab a_in] },
{ simp only [if_neg hji, hextr j] } },
by_cases hP' : is_strictly_best b (f (λ j, ite (j = i) (maketop (P j) b X hX') (P j))) X,
{ refine ⟨i, P, _, λ j hj x y _ _, _, hextr, hextr', _, _, hbot, hP'⟩,
{ simp [same_order, if_neg hj] },
{ have : i ∈ {j ∈ univ | is_strictly_worst b (P j) X}, { rw ← h_insert, exact mem_insert_self i D },
simpa },
{ simp [top_of_maketop, hX'] } },
{ refine IH _ hextr' ((first_step hwp hind hX b_in hextr').is_strictly_worst hP'),
ext j,
simp only [true_and, sep_def, mem_filter, mem_univ],
split; intro hj,
{ suffices : j ∈ insert i D,
{ have hji : j ≠ i, { rintro rfl, exact hi hj },
rw h_insert at this,
simpa [hji] },
exact mem_insert_of_mem hj },
{ have hji : j ≠ i,
{ rintro rfl,
obtain ⟨a, a_in, hab⟩ := exists_second_distinct_mem hX.le b_in,
apply asymm (top_of_maketop b (P j) hX' a a_in hab),
simpa using hj a a_in hab },
rw [← erase_insert hi, h_insert],
simpa [hji] using hj } } },
end
/-- Let `f` be a SWF satisfying WP and IoIA, and `X` be a finite set containing at least 3 social states.
Then `f` has a pivot w.r.t. every social state in `X`. -/
lemma second_step [fintype ι]
(hwp : weak_pareto f X) (hind : ind_of_irr_alts f X)
(hX : 3 ≤ X.card) (b) (b_in : b ∈ X) :
has_pivot f X b :=
begin
classical,
have hbot : is_strictly_worst b (λ x, ite (x = b) 0 1) X := λ _ _ h, by simp [h],
exact second_step_aux hwp hind hX b_in rfl (λ i, hbot.is_extremal)
(is_strictly_worst_of_forall_is_strictly_worst b_in hwp (λ i, hbot)),
end
/-- Let `f` be a SWF satisfying IoIA, `X` be a finite set of social states, and `b` be one of those
social states.
If an individual `i` is pivotal w.r.t. `f` and `b`, then `i` is a dictator over all social states
in `X` except `b`. -/
lemma third_step (hind : ind_of_irr_alts f X)
(hb : b ∈ X) {i : ι} (hpiv : is_pivotal f X i b) :
is_dictator_except f X i b :=
begin
intros a c ha hc hab hcb Q hyp,
obtain ⟨P, P', hpiv⟩ := hpiv,
have hX := nonempty_of_mem hb,
classical,
let Q' := λ j,
if j = i
then makebetween (Q j) a b c
else
if is_strictly_worst b (P j) X
then makebot (Q j) b X hX
else maketop (Q j) b X hX,
refine (hind a c ha hc Q Q' (λ j, _)).mpr
(((hind a b ha hb P' Q' (λ j, _)).mp (hpiv.2.2.2.2.2.2 a ha hab)).trans
((hind b c hb hc P Q' (λ j, _)).mp (hpiv.2.2.2.2.2.1 c hc hcb))),
{ suffices : ∀ d ≠ b, Q j d = Q' j d, { rw [this, this]; assumption },
intros d hdb,
by_cases hj : j = i; simp only [Q', if_pos, hj, dite_eq_ite],
{ exact (makebetween_noteq (Q i) hdb).symm },
{ by_cases hbot : is_strictly_worst b (P j) X; simp only [if_neg hj],
{ rw [← makebot_noteq (Q j) hdb hX, if_pos hbot] },
{ rw [← maketop_noteq (Q j) hdb hX, if_neg hbot] } } },
{ refine ⟨λ hP', _, λ hQ', _⟩; by_cases hj : j = i,
{ simpa [Q', if_pos, hj] using makebetween_lt_makebetween_bot hab hyp },
{ have hbot : ¬ is_strictly_worst b (P j) X := λ h, asymm ((hpiv.1 j hj a b ha hb).1.2 hP') (h a ha hab),
simpa [Q', if_neg, hj, hbot] using maketop_lt_maketop (Q j) hab ha },
{ convert hpiv.2.2.2.2.1 a ha hab },
{ refine (hpiv.1 j hj a b ha hb).1.1 ((hpiv.2.1 j).is_strictly_best
(λ hbot, asymm (makebot_lt_makebot (Q j) hab ha) _) a ha hab),
convert hQ'; simp [Q', if_neg hj, if_pos hbot] } },
{ refine ⟨λ hP, _, λ hQ', _⟩; by_cases hj : j = i,
{ simpa [Q', if_pos, hj] using makebetween_lt_makebetween_top hcb hyp },
{ have hbot : is_strictly_worst b (P j) X,
{ unfold is_strictly_worst,
by_contra hbot, push_neg at hbot,
obtain ⟨d, hd, hdb, h⟩ := hbot,
cases hpiv.2.1 j with hbot htop,
{ exact (hbot d hd hdb).not_le h },
{ exact (irrefl _) ((htop c hc hcb).trans hP) } },
simpa [Q', if_neg hj, if_pos hbot] using makebot_lt_makebot (Q j) hcb hc },
{ convert hpiv.2.2.2.1 c hc hcb },
{ by_contra hP,
have hbot : ¬ is_strictly_worst b (P j) X := λ h, hP (h c hc hcb),
apply asymm (maketop_lt_maketop (Q j) hcb hc),
convert hQ'; simp [Q', if_neg, hbot, hj] } },
end
/-- Let `f` be a SWF satisfying IoIA, and `X` be a finite set containing at least 3 social states.
If `f` has a pivot for every social state in `X`, then `f` is a dictatorship. -/
lemma fourth_step (hind : ind_of_irr_alts f X)
(hX : 3 ≤ X.card) (hpiv : ∀ b ∈ X, has_pivot f X b) :
is_dictatorship f X :=
begin
obtain ⟨b, hb⟩ := (card_pos.1 (zero_lt_two.trans hX)).bex,
obtain ⟨i, ipiv⟩ := hpiv b hb,
have h : ∀ a ∈ X, a ≠ b → ∀ Pᵢ : ι → σ → ℝ,
(Pᵢ i a < Pᵢ i b → f Pᵢ a < f Pᵢ b) ∧ (Pᵢ i b < Pᵢ i a → f Pᵢ b < f Pᵢ a), -- we should have a better way of stating this that doesn't require the and (i.e. stated WLOG)
{ intros a ha hab Pᵢ,
obtain ⟨c, hc, hca, hcb⟩ := exists_third_distinct_mem hX ha hb hab,
obtain ⟨hac, hbc⟩ := ⟨hca.symm, hcb.symm⟩,
obtain ⟨j, jpiv⟩ := hpiv c hc,
obtain hdict := third_step hind hc jpiv,
obtain rfl : j = i,
{ by_contra hji,
obtain ⟨R, R', hso, hextr, -, -, -, hbot, htop⟩ := ipiv,
refine asymm (htop a ha hab) (hdict b a hb ha hbc hac R' ((hso j hji a b ha hb).2.1 _)),
by_contra hnot,
have h := (hextr j).resolve_left,
simp only [is_strictly_best, is_strictly_worst, and_imp, exists_imp_distrib, not_forall] at h,
exact asymm (hbot a ha hab) (hdict a b ha hb hac hbc R (h a ha hab hnot a ha hab)) },
split; apply hdict; assumption },
refine ⟨i, λ x y hx hy Pᵢ hPᵢ, _⟩,
rcases eq_or_ne b x with rfl | hbx; rcases eq_or_ne b y with rfl | hby,
{ exact ((irrefl _) hPᵢ).rec _ },
{ exact (h y hy hby.symm Pᵢ).2 hPᵢ },
{ exact (h x hx hbx.symm Pᵢ).1 hPᵢ },
{ exact third_step hind hb ipiv x y hx hy hbx.symm hby.symm Pᵢ hPᵢ },
end
/-- Arrow's Impossibility Theorem: Any social welfare function involving at least three social
states that satisfies WP and IoIA is necessarily a dictatorship. -/
theorem arrow [fintype ι]
(hwp : weak_pareto f X) (hind : ind_of_irr_alts f X) (hX : 3 ≤ X.card) :
is_dictatorship f X :=
fourth_step hind hX $ second_step hwp hind hX
|
# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""export checkpoint file into air, onnx, mindir models
Suggest run as python export.py --file_name [file_name] --ckpt_files [ckpt path] --file_format [file format]
"""
import argparse
import numpy as np
import mindspore as ms
from mindspore import context, Tensor
from mindspore.train.serialization import export, load_checkpoint, load_param_into_net
parser = argparse.ArgumentParser(description='post process for 310 inference')
parser.add_argument("--backbone", type=str, required=True, default="densenet161", help="model backbone")
parser.add_argument("--ckpt_path", type=str, required=True, help="checkpoint file path")
parser.add_argument("--file_name", type=str, default="densenet161", help="file name")
parser.add_argument("--file_format", type=str, default="MINDIR", choices=["MINDIR", "AIR"], help="file format")
parser.add_argument("--device_target", type=str, default="Ascend", choices=["Ascend", "GPU"], help="device target")
parser.add_argument("--device_id", type=int, default=0, help="device target")
args = parser.parse_args()
context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
def model_export():
'''main export func'''
if args.device_target == "Ascend":
context.set_context(device_id=args.device_id)
if args.backbone == "densenet121":
from src.densenet121 import MainModel
elif args.backbone == "densenet161":
from src.densenet161 import MainModel
elif args.backbone == "densenet169":
from src.densenet169 import MainModel
elif args.backbone == "densenet201":
from src.densenet201 import MainModel
net = MainModel()
param_dict = load_checkpoint(args.ckpt_path)
load_param_into_net(net, param_dict)
input_arr = Tensor(np.zeros([1, 3, 224, 224]), ms.float32)
export(net, input_arr, file_name=args.file_name, file_format=args.file_format)
if __name__ == '__main__':
model_export()
|
setret = function(x, vec=FALSE)
{
if (is_cpumat(x))
{
if (vec)
ret = cpuvec(type=x$get_type_str())
else
ret = cpumat(type=x$get_type_str())
}
else if (is_gpumat(x))
{
if (vec)
ret = gpuvec(x$get_card(), type=x$get_type_str())
else
ret = gpumat(x$get_card(), type=x$get_type_str())
}
else if (is_mpimat(x))
{
if (vec)
ret = cpuvec(type=x$get_type_str())
else
{
bfdim = x$bfdim()
ret = mpimat(x$get_grid(), bf_rows=bfdim[1], bf_cols=bfdim[2], type=x$get_type_str())
}
}
ret
}
|
cc ------------ dpmjet3.4 - authors: S.Roesler, R.Engel, J.Ranft -------
cc -------- phojet1.12-40 - authors: S.Roesler, R.Engel, J.Ranft -------
cc - oct'13 -------
cc ----------- pythia-6.4 - authors: Torbjorn Sjostrand, Lund'10 -------
cc ---------------------------------------------------------------------
cc converted for use with FLUKA -------
cc - oct'13 -------
C...PYJOIN
C...Connects a sequence of partons with colour flow indices,
C...as required for subsequent shower evolution (or other operations).
SUBROUTINE PYJOIN(NJOIN,IJOIN)
C...Double precision and integer declarations.
IMPLICIT DOUBLE PRECISION(A-H, O-Z)
IMPLICIT INTEGER(I-N)
INTEGER PYCOMP
C...Commonblocks.
include 'inc/pyjets'
include 'inc/pydat1'
include 'inc/pydat2'
C...Local array.
DIMENSION IJOIN(*)
C...Check that partons are of right types to be connected.
IF(NJOIN.LT.2) GOTO 120
KQSUM=0
DO 100 IJN=1,NJOIN
I=IJOIN(IJN)
IF(I.LE.0.OR.I.GT.N) GOTO 120
IF(K(I,1).LT.1.OR.K(I,1).GT.3) GOTO 120
KC=PYCOMP(K(I,2))
IF(KC.EQ.0) GOTO 120
KQ=KCHG(KC,2)*SIGN(1,K(I,2))
IF(KQ.EQ.0) GOTO 120
IF(IJN.NE.1.AND.IJN.NE.NJOIN.AND.KQ.NE.2) GOTO 120
IF(KQ.NE.2) KQSUM=KQSUM+KQ
IF(IJN.EQ.1) KQS=KQ
100 CONTINUE
IF(KQSUM.NE.0) GOTO 120
C...Connect the partons sequentially (closing for gluon loop).
KCS=(9-KQS)/2
IF(KQS.EQ.2) KCS=INT(4.5D0+PYR(0))
DO 110 IJN=1,NJOIN
I=IJOIN(IJN)
K(I,1)=3
IF(IJN.NE.1) IP=IJOIN(IJN-1)
IF(IJN.EQ.1) IP=IJOIN(NJOIN)
IF(IJN.NE.NJOIN) IN=IJOIN(IJN+1)
IF(IJN.EQ.NJOIN) IN=IJOIN(1)
K(I,KCS)=MSTU(5)*IN
K(I,9-KCS)=MSTU(5)*IP
IF(IJN.EQ.1.AND.KQS.NE.2) K(I,9-KCS)=0
IF(IJN.EQ.NJOIN.AND.KQS.NE.2) K(I,KCS)=0
110 CONTINUE
C...Error exit: no action taken.
RETURN
120 CALL PYERRM(12,
&'(PYJOIN:) given entries can not be joined by one string')
RETURN
END
|
Watson concludes that ( a ) " most moves have disadvantages as well as advantages , so an extra move is not always an unqualified blessing " ; ( b ) " with his extra information about what White is doing , Black can better react to the new situation " ; and ( c ) because a draw is likely to be more acceptable to Black than to White , White is apt to avoid lines that allow drawish simplifications , while Black may not object to such lines .
|
A predicate is a measurable function from a measurable space to the space of truth values. |
{-
Descriptor language for easily defining relational structures
-}
{-# OPTIONS --cubical --no-import-sorts --no-exact-split --safe #-}
module Cubical.Structures.Relational.Macro where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Structure
open import Cubical.Foundations.RelationalStructure
open import Cubical.Data.Sigma
open import Cubical.Structures.Relational.Constant
open import Cubical.Structures.Relational.Function
open import Cubical.Structures.Relational.Maybe
open import Cubical.Structures.Relational.Parameterized
open import Cubical.Structures.Relational.Pointed
open import Cubical.Structures.Relational.Product
open import Cubical.Structures.Macro
open import Cubical.Structures.Maybe
data PosRelDesc (ℓ : Level) : Typeω where
-- constant structure: X ↦ A
constant : ∀ {ℓ'} → hSet ℓ' → PosRelDesc ℓ
-- pointed structure: X ↦ X
var : PosRelDesc ℓ
-- product of structures S,T : X ↦ (S X × T X)
_,_ : PosRelDesc ℓ → PosRelDesc ℓ → PosRelDesc ℓ
-- Maybe on a structure S: X ↦ Maybe (S X)
maybe : PosRelDesc ℓ → PosRelDesc ℓ
data RelDesc (ℓ : Level) : Typeω where
-- constant structure: X ↦ A
constant : ∀ {ℓ'} → hSet ℓ' → RelDesc ℓ
-- pointed structure: X ↦ X
var : RelDesc ℓ
-- product of structures S,T : X ↦ (S X × T X)
_,_ : RelDesc ℓ → RelDesc ℓ → RelDesc ℓ
-- structure S parameterized by constant A : X ↦ (A → S X)
param : ∀ {ℓ'} → (A : Type ℓ') → RelDesc ℓ → RelDesc ℓ
-- function from positive structure S to T: X ↦ (S X → T X)
function+ : PosRelDesc ℓ → RelDesc ℓ → RelDesc ℓ
-- Maybe on a structure S: X ↦ Maybe (S X)
maybe : RelDesc ℓ → RelDesc ℓ
infixr 4 _,_
posRelDesc→TranspDesc : ∀ {ℓ} → PosRelDesc ℓ → TranspDesc ℓ
posRelDesc→TranspDesc (constant A) = constant (A .fst)
posRelDesc→TranspDesc var = var
posRelDesc→TranspDesc (d₀ , d₁) = posRelDesc→TranspDesc d₀ , posRelDesc→TranspDesc d₁
posRelDesc→TranspDesc (maybe d) = maybe (posRelDesc→TranspDesc d)
posRelDesc→RelDesc : ∀ {ℓ} → PosRelDesc ℓ → RelDesc ℓ
posRelDesc→RelDesc (constant A) = constant A
posRelDesc→RelDesc var = var
posRelDesc→RelDesc (d₀ , d₁) = posRelDesc→RelDesc d₀ , posRelDesc→RelDesc d₁
posRelDesc→RelDesc (maybe d) = maybe (posRelDesc→RelDesc d)
relDesc→Desc : ∀ {ℓ} → RelDesc ℓ → Desc ℓ
relDesc→Desc (constant A) = constant (A .fst)
relDesc→Desc var = var
relDesc→Desc (d₀ , d₁) = relDesc→Desc d₀ , relDesc→Desc d₁
relDesc→Desc (param A d) = function+ (constant A) (relDesc→Desc d)
relDesc→Desc (function+ d₀ d₁) = function+ (posRelDesc→TranspDesc d₀) (relDesc→Desc d₁)
relDesc→Desc (maybe d) = maybe (relDesc→Desc d)
{- Universe level calculations -}
posRelMacroStrLevel : ∀ {ℓ} → PosRelDesc ℓ → Level
posRelMacroStrLevel d = transpMacroLevel (posRelDesc→TranspDesc d)
relMacroStrLevel : ∀ {ℓ} → RelDesc ℓ → Level
relMacroStrLevel d = macroStrLevel (relDesc→Desc d)
posRelMacroRelLevel : ∀ {ℓ} → PosRelDesc ℓ → Level
posRelMacroRelLevel (constant {ℓ'} A) = ℓ'
posRelMacroRelLevel {ℓ} var = ℓ
posRelMacroRelLevel (d₀ , d₁) = ℓ-max (posRelMacroRelLevel d₀) (posRelMacroRelLevel d₁)
posRelMacroRelLevel (maybe d) = posRelMacroRelLevel d
relMacroRelLevel : ∀ {ℓ} → RelDesc ℓ → Level
relMacroRelLevel (constant {ℓ'} A) = ℓ'
relMacroRelLevel {ℓ} var = ℓ
relMacroRelLevel (d₀ , d₁) = ℓ-max (relMacroRelLevel d₀) (relMacroRelLevel d₁)
relMacroRelLevel (param {ℓ'} A d) = ℓ-max ℓ' (relMacroRelLevel d)
relMacroRelLevel (function+ d₀ d₁) =
ℓ-max (posRelMacroStrLevel d₀) (ℓ-max (posRelMacroRelLevel d₀) (relMacroRelLevel d₁))
relMacroRelLevel (maybe d) = relMacroRelLevel d
{- Definition of structure -}
PosRelMacroStructure : ∀ {ℓ} (d : PosRelDesc ℓ) → Type ℓ → Type (posRelMacroStrLevel d)
PosRelMacroStructure d = TranspMacroStructure (posRelDesc→TranspDesc d)
RelMacroStructure : ∀ {ℓ} (d : RelDesc ℓ) → Type ℓ → Type (relMacroStrLevel d)
RelMacroStructure d = MacroStructure (relDesc→Desc d)
{- Notion of structured relation defined by a descriptor -}
PosRelMacroRelStr : ∀ {ℓ} (d : PosRelDesc ℓ) → StrRel {ℓ} (PosRelMacroStructure d) (posRelMacroRelLevel d)
PosRelMacroRelStr (constant A) = ConstantRelStr A
PosRelMacroRelStr var = PointedRelStr
PosRelMacroRelStr (d₀ , d₁) = ProductRelStr (PosRelMacroRelStr d₀) (PosRelMacroRelStr d₁)
PosRelMacroRelStr (maybe d) = MaybeRelStr (PosRelMacroRelStr d)
RelMacroRelStr : ∀ {ℓ} (d : RelDesc ℓ) → StrRel {ℓ} (RelMacroStructure d) (relMacroRelLevel d)
RelMacroRelStr (constant A) = ConstantRelStr A
RelMacroRelStr var = PointedRelStr
RelMacroRelStr (d₀ , d₁) = ProductRelStr (RelMacroRelStr d₀) (RelMacroRelStr d₁)
RelMacroRelStr (param A d) = ParamRelStr A (λ _ → RelMacroRelStr d)
RelMacroRelStr (function+ d₀ d₁) =
FunctionRelStr (PosRelMacroRelStr d₀) (RelMacroRelStr d₁)
RelMacroRelStr (maybe d) = MaybeRelStr (RelMacroRelStr d)
{- Proof that structure induced by descriptor is suitable or positive -}
posRelMacroSuitableRel : ∀ {ℓ} (d : PosRelDesc ℓ) → SuitableStrRel _ (PosRelMacroRelStr d)
posRelMacroSuitableRel (constant A) = constantSuitableRel A
posRelMacroSuitableRel var = pointedSuitableRel
posRelMacroSuitableRel (d₀ , d₁) =
productSuitableRel (posRelMacroSuitableRel d₀) (posRelMacroSuitableRel d₁)
posRelMacroSuitableRel (maybe d) = maybeSuitableRel (posRelMacroSuitableRel d)
posRelMacroPositiveRel : ∀ {ℓ} (d : PosRelDesc ℓ) → PositiveStrRel (posRelMacroSuitableRel d)
posRelMacroPositiveRel (constant A) = constantPositiveRel A
posRelMacroPositiveRel var = pointedPositiveRel
posRelMacroPositiveRel (d₀ , d₁) =
productPositiveRel (posRelMacroPositiveRel d₀) (posRelMacroPositiveRel d₁)
posRelMacroPositiveRel (maybe d) = maybePositiveRel (posRelMacroPositiveRel d)
relMacroSuitableRel : ∀ {ℓ} (d : RelDesc ℓ) → SuitableStrRel _ (RelMacroRelStr d)
relMacroSuitableRel (constant A) = constantSuitableRel A
relMacroSuitableRel var = pointedSuitableRel
relMacroSuitableRel (d₀ , d₁) = productSuitableRel (relMacroSuitableRel d₀) (relMacroSuitableRel d₁)
relMacroSuitableRel (param A d) = paramSuitableRel A (λ _ → relMacroSuitableRel d)
relMacroSuitableRel (function+ d₀ d₁) =
functionSuitableRel (posRelMacroSuitableRel d₀) (posRelMacroPositiveRel d₀) (relMacroSuitableRel d₁)
relMacroSuitableRel (maybe d) = maybeSuitableRel (relMacroSuitableRel d)
{- Proof that structured relations and equivalences agree -}
posRelMacroMatchesEquiv : ∀ {ℓ} (d : PosRelDesc ℓ)
→ StrRelMatchesEquiv (PosRelMacroRelStr d) (EquivAction→StrEquiv (transpMacroAction (posRelDesc→TranspDesc d)))
posRelMacroMatchesEquiv (constant A) _ _ _ = idEquiv _
posRelMacroMatchesEquiv var _ _ _ = idEquiv _
posRelMacroMatchesEquiv (d₀ , d₁) =
productRelMatchesTransp
(PosRelMacroRelStr d₀) (transpMacroAction (posRelDesc→TranspDesc d₀))
(PosRelMacroRelStr d₁) (transpMacroAction (posRelDesc→TranspDesc d₁))
(posRelMacroMatchesEquiv d₀) (posRelMacroMatchesEquiv d₁)
posRelMacroMatchesEquiv (maybe d) =
maybeRelMatchesTransp
(PosRelMacroRelStr d) (transpMacroAction (posRelDesc→TranspDesc d))
(posRelMacroMatchesEquiv d)
relMacroMatchesEquiv : ∀ {ℓ} (d : RelDesc ℓ)
→ StrRelMatchesEquiv (RelMacroRelStr d) (MacroEquivStr (relDesc→Desc d))
relMacroMatchesEquiv (constant A) = constantRelMatchesEquiv A
relMacroMatchesEquiv var = pointedRelMatchesEquiv
relMacroMatchesEquiv (d₁ , d₂) =
productRelMatchesEquiv
(RelMacroRelStr d₁) (RelMacroRelStr d₂)
(relMacroMatchesEquiv d₁) (relMacroMatchesEquiv d₂)
relMacroMatchesEquiv (param A d) =
paramRelMatchesEquiv A (λ _ → RelMacroRelStr d) (λ _ → relMacroMatchesEquiv d)
relMacroMatchesEquiv (function+ d₀ d₁) =
functionRelMatchesEquiv+
(PosRelMacroRelStr d₀) (transpMacroAction (posRelDesc→TranspDesc d₀))
(RelMacroRelStr d₁) (MacroEquivStr (relDesc→Desc d₁))
(posRelMacroMatchesEquiv d₀) (relMacroMatchesEquiv d₁)
relMacroMatchesEquiv (maybe d) =
maybeRelMatchesEquiv (RelMacroRelStr d) (relMacroMatchesEquiv d)
-- Module for easy importing
module RelMacro ℓ (d : RelDesc ℓ) where
relation = RelMacroRelStr d
suitable = relMacroSuitableRel d
matches = relMacroMatchesEquiv d
open Macro ℓ (relDesc→Desc d) public
|
library(Biostrings)
library(stringr)
options(scipen=999)
# read in genome
genome <- readDNAStringSet("camp.contigs.fasta")
# get contig names and lengths
genome_names <- genome@ranges@NAMES
genome_lengths <- as.numeric(sapply(strsplit(sapply(strsplit(genome_names, " "), "[[", 2), "="), "[[", 2))
# sort by genome lengths
genome <- genome[order(genome_lengths, decreasing=T)]
# get names and lengths again
genome_names <- genome@ranges@NAMES
genome_lengths <- as.numeric(sapply(strsplit(sapply(strsplit(genome_names, " "), "[[", 2), "="), "[[", 2))
head(genome_lengths)
# remake contig names to be simple
genome@ranges@NAMES <- paste("contig", str_pad(seq(from=1, to=length(genome_names), by=1), 4, pad="0"), sep="")
# remove contigs less than 10kb
genome2 <- genome[genome@ranges@width >= 10000]
# write output
writeXStringSet(genome2, file="camponotus_reordered.fasta")
# contig sizes for juicer:
sizes <- cbind(genome@ranges@NAMES, genome_lengths)
write.table(sizes, file="camponotus_reordered.contig.sizes", sep="\t", quote=F, row.names=F, col.names=F)
|
= = Distribution , habitat , and ecology = =
|
import algebra.pi_instances analysis.complex
import .algebra_tensor .monoid_ring .field_extensions
universes u v w
instance subtype.comm_group {α : Type u} [comm_group α] (s : set α) [is_subgroup s] : comm_group s :=
by subtype_instance
noncomputable theory
local attribute [instance] classical.prop_decidable
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_ring R] [comm_ring A] [comm_ring B]
variables (iA : algebra R A) (iB : algebra R B)
open algebra.tensor_product
class cogroup :=
(comul : iA →ₐ iA.tensor_product iA)
(comul_assoc : (aassoc iA iA iA).comp
((amap comul (alg_hom.id iA)).comp comul)
= (amap (alg_hom.id iA) comul).comp comul)
(coone : iA →ₐ algebra.id R)
(comul_coone : (tensor_id iA).comp
((amap (alg_hom.id iA) coone).comp comul)
= alg_hom.id iA)
(coinv : iA →ₐ iA)
(comul_coinv : (arec (alg_hom.id iA) coinv).comp comul
= iA.of_id.comp coone)
open monoid_ring
variables R
set_option class.instance_max_depth 50
instance group_ring.cogroup (M : Type v) [add_comm_group M] :
cogroup (monoid_ring.algebra R M) :=
{ comul := eval _ _ _ (λ n, of_monoid R M n ⊗ₜ of_monoid R M n) $
⟨λ _ _, by rw [of_monoid_add, tensor_product.mul_def],
by rw is_add_monoid_monoid_hom.zero (of_monoid R M); refl⟩,
coone := eval _ _ _ (λ n, 1) ⟨λ _ _, (mul_one 1).symm, rfl⟩,
comul_assoc := monoid_ring.ext _ _ _ _ _ (λ m,
by simp only [alg_hom.comp_apply, eval_of_monoid, amap_tmul, aassoc_tmul, alg_hom.id_apply]),
comul_coone := monoid_ring.ext _ _ _ _ _ (λ m,
by simp only [alg_hom.comp_apply, eval_of_monoid, amap_tmul, tensor_id_tmul, alg_hom.id_apply];
exact @one_smul R _ _ _ _ (of_monoid R M m)),
coinv := eval _ _ _ (λ n, of_monoid R M (-n))
⟨λ _ _, by rw [neg_add, of_monoid_add], by rw neg_zero; refl⟩,
comul_coinv := monoid_ring.ext _ _ _ _ _ (λ m,
by simp only [alg_hom.comp_apply, eval_of_monoid, arec_tmul, alg_hom.id_apply, algebra.of_id_apply];
rw [← of_monoid_add, add_neg_self]; refl) }
set_option class.instance_max_depth 32
instance int.add_comm_group : add_comm_group ℤ :=
ring.to_add_comm_group ℤ
def GL₁ⁿ (n : ℕ) : algebra R (monoid_ring R (fin n → ℤ)) :=
monoid_ring.algebra _ _
instance GL₁ⁿ.cogroup (n : ℕ) : cogroup (GL₁ⁿ R n) :=
group_ring.cogroup _ _
def GL₁ : algebra R (monoid_ring R ℤ) :=
monoid_ring.algebra _ _
instance GL₁.cogroup : cogroup (GL₁ R) :=
group_ring.cogroup _ _
variables {R}
class is_cogroup_hom [cogroup iA] [cogroup iB] (f : iA →ₐ iB) : Prop :=
(comul : (cogroup.comul iB).comp f = (amap f f).comp (cogroup.comul iA))
section is_cogroup_hom
-- f(1)
-- = f(1) * 1
-- = f(1) * (f(1) * f(1)⁻¹)
-- = (f(1) * f(1)) * f(1)⁻¹
-- = f(1 * 1) * f(1)⁻¹
-- = f(1) * f(1)⁻¹
-- = 1
/-theorem is_cogroup_hom.coone [cogroup iA] [cogroup iB]
(f : @alg_hom R A B _ _ _ _ _) [is_cogroup_hom R A B f] :
(cogroup.coone R B).comp f = cogroup.coone R A :=
have _ := cogroup.comul_coone R A,
calc (cogroup.coone R B).comp f
= ((cogroup.coone R B).comp f).comp ((alg_hom.tensor_ring _ _).comp
((tensor_a.map (alg_hom.id A) (cogroup.coone R A)).comp (cogroup.comul R A))) : by rw [cogroup.comul_coone R A]; simp
... = _ : _
... = _ : _-/
end is_cogroup_hom
def cogroup_hom [cogroup iA] [cogroup iB] :=
subtype (is_cogroup_hom iA iB)
def GL₁.alg_hom : units iA.mod ≃ alg_hom (GL₁ R) iA :=
equiv.trans (show units A ≃ add_monoid_monoid_hom ℤ A, from
{ to_fun := λ u, ⟨λ n, ((u^n:units A):A),
λ _ _, by simp [gpow_add], by simp⟩,
inv_fun := λ f, ⟨f.1 1, f.1 (-1),
by rw [← f.2.1, add_neg_self, f.2.2],
by rw [← f.2.1, neg_add_self, f.2.2]⟩,
left_inv := λ u, units.ext $ by simp; refl,
right_inv := λ f, subtype.eq $ funext $ λ n,
by apply int.induction_on n; intros;
simp at *; simp [f.2.2, f.2.1, gpow_add, *]; refl})
(monoid_ring.UMP _ _ _)
-- needs more lemmas about tensoring
instance cogroup.base_change_left [cogroup iB] :
cogroup (base_change_left iA iB) := sorry
structure cogroup_iso [cogroup iA] [cogroup iB] :=
(to_fun : iA →ₐ iB)
(inv_fun : iB →ₐ iA)
(left_inverse : ∀ x, inv_fun (to_fun x) = x)
(right_inverse : ∀ x, to_fun (inv_fun x) = x)
[hom : is_cogroup_hom iA iB to_fun]
def torus.is_split {F : Type u} [discrete_field F]
{TR : Type v} [comm_ring TR] (T : algebra F TR) [cogroup T]
(E : finite_Galois_extension F)
(rank : ℕ) :=
cogroup_iso (GL₁ⁿ E.S rank) (base_change_left E.S.algebra T)
structure torus {F : Type u} [discrete_field F]
{TR : Type v} [comm_ring TR] (T : algebra F TR) [cogroup T] :=
(top : finite_Galois_extension F)
(rank : ℕ)
(splits : torus.is_split T top rank)
variables {F : Type u} [discrete_field F]
variables {TR : Type v} [comm_ring TR] {T : algebra F TR} [cogroup T]
variables (ht : torus T)
include ht
def torus.base_change : algebra ht.top.S (ht.top.S.algebra.mod ⊗ T.mod) :=
base_change_left ht.top.S.algebra T
instance torus.base_change.cogroup : cogroup ht.base_change :=
cogroup.base_change_left _ _
def torus.char : Type (max u v) :=
cogroup_hom (GL₁ ht.top.S) ht.base_change
def torus.cochar : Type (max u v) :=
cogroup_hom ht.base_change (GL₁ ht.top.S)
instance torus.char.add_comm_group : add_comm_group ht.char := sorry
instance torus.cochar.add_comm_group : add_comm_group ht.cochar := sorry
def torus.rat_pt : Type (max u v) :=
T →ₐ algebra.id F
instance torus.rat_pt.topological_space : topological_space ht.rat_pt := sorry
instance torus.rat_pt.group : group ht.rat_pt := sorry
instance torus.rat_pt.topological_group : topological_group ht.rat_pt := sorry
def torus.hat : Type (max u v) :=
add_monoid_monoid_hom ht.cochar (units ℂ)
def torus.hat_to_fun : ht.hat → (ht.cochar → units ℂ) :=
subtype.val
instance torus.hat.comm_group : comm_group ht.hat :=
@subtype.comm_group (ht.cochar → units ℂ)
(@pi.comm_group _ _ $ λ _, units.comm_group)
is_add_monoid_monoid_hom
{ mul_mem := λ f g hf hg,
⟨λ x y, show f (x + y) * g (x + y) = (f x * g x) * (f y * g y),
by rw [hf.1, hg.1, mul_assoc, mul_assoc, mul_left_comm (f y)],
show f 0 * g 0 = 1, by rw [hf.2, hg.2, mul_one]⟩,
one_mem := ⟨λ _ _, (mul_one _).symm, rfl⟩,
inv_mem := λ f hf,
⟨λ x y, show (f (x + y))⁻¹ = (f x)⁻¹ * (f y)⁻¹,
by rw [hf.1, mul_inv],
show (f 0)⁻¹ = 1, by rw [hf.2, one_inv]⟩ }
instance torus.hat.topological_space : topological_space ht.hat :=
topological_space.induced subtype.val Pi.topological_space
instance torus.hat.is_group_hom_hat_to_fun : is_group_hom ht.hat_to_fun := ⟨λ _ _, rfl⟩
instance torus.hat.topological_group {F : Type u} [discrete_field F]
{TR : Type v} [comm_ring TR] {T : algebra F TR} [cogroup T]
(ht : torus T) : topological_group ht.hat :=
@@topological_group.induced _ _ _ _ _ _ ht.hat_to_fun _
instance torus.hat.topological_add_group_additive {F : Type u} [discrete_field F]
{TR : Type v} [comm_ring TR] {T : algebra F TR} [cogroup T]
(ht : torus T) : topological_add_group (additive ht.hat) :=
additive.topological_add_group
instance torus.hat.topological_space_additive {F : Type u} [discrete_field F]
{TR : Type v} [comm_ring TR] {T : algebra F TR} [cogroup T]
(ht : torus T) : topological_space (additive ht.hat) :=
additive.topological_space
|
(*
(C) Copyright 2010, COQTAIL team
Project Info: http://sourceforge.net/projects/coqtail/
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*)
Require Import Coq.omega.Omega.
Require Import Rsequence_def.
Require Import Morphisms Setoid.
Require Import Lra.
Open Scope R_scope.
Open Scope Rseq_scope.
(** printing ~ ~ *)
(** ** Extensionnal equality. *)
(** * Extensional equality is an equivalence relation. *)
(**********)
Lemma Rseq_eq_refl : forall Un, Un == Un.
Proof.
intros Un n; reflexivity.
Qed.
(**********)
Lemma Rseq_eq_sym : forall Un Vn, Un == Vn -> Vn == Un.
Proof.
intros Un Vn Heq n.
symmetry; apply Heq.
Qed.
(**********)
Lemma Rseq_eq_trans : forall Un Vn Wn, Un == Vn -> Vn == Wn -> Un == Wn.
Proof.
intros Un Vn Wn Heq1 Heq2 n.
transitivity (Vn n); [apply Heq1|apply Heq2].
Qed.
(**********)
Instance Rseq_eq_Equivalence : Equivalence Rseq_eq.
Proof.
split.
exact Rseq_eq_refl.
exact Rseq_eq_sym.
exact Rseq_eq_trans.
Qed.
(** * Rseq_opp is involutive. *)
Lemma Rseq_opp_invol : forall Un, - - Un == Un.
Proof.
intros Un n ; unfold Rseq_opp ; rewrite Ropp_involutive ;
reflexivity.
Qed.
(** * Compatibility of extensional equality with convergence. *)
(**********)
Lemma Rseq_cv_eq_compat :
forall Un Vn l, Un == Vn ->
(Rseq_cv Un l <-> Rseq_cv Vn l).
Proof.
intros Un Vn l Heq ; split ; intros Hcv eps Heps ;
destruct (Hcv eps Heps) as [N HN] ;
exists N; intros n Hn ;
[rewrite <- Heq | rewrite Heq] ;
apply HN; assumption.
Qed.
(**********)
Lemma Rseq_cv_pos_infty_eq_compat :
forall Un Vn, Un == Vn -> Rseq_cv_pos_infty Un -> Rseq_cv_pos_infty Vn.
Proof.
intros Un Vn Heq Hdiv.
intros m.
destruct (Hdiv m) as [N HN].
exists N; intros n Hn.
rewrite <- (Heq n).
apply HN; assumption.
Qed.
(**********)
Lemma Rseq_cv_neg_infty_eq_compat :
forall Un Vn, Un == Vn -> Rseq_cv_neg_infty Un -> Rseq_cv_neg_infty Vn.
Proof.
intros Un Vn Heq Hdiv.
intros m.
destruct (Hdiv m) as [N HN].
exists N; intros n Hn.
rewrite <- (Heq n).
apply HN; assumption.
Qed.
(** * Compatibility of extensional equality with Laudau relations. *)
(**********)
Lemma Rseq_big_O_eq_compat :
forall Un Vn Wn Xn, Un == Wn -> Vn == Xn ->
Un = O(Vn) -> Wn = O(Xn).
Proof.
intros Un Vn Wn Xn Huw Hvx Huv.
destruct Huv as [M [HM [N HN]]].
exists M; split.
assumption.
exists N; intros n Hn.
rewrite <- Huw; rewrite <- Hvx.
apply HN; assumption.
Qed.
(**********)
Lemma Rseq_little_O_eq_compat :
forall Un Vn Wn Xn, Un == Wn -> Vn == Xn ->
Un = o(Vn) -> Wn = o(Xn).
Proof.
intros Un Vn Wn Xn Huw Hvx Huv.
intros eps Heps.
destruct (Huv eps Heps) as [N HN].
exists N; intros n Hn.
rewrite <- Huw; rewrite <- Hvx.
apply HN; assumption.
Qed.
(**********)
Lemma Rseq_equiv_eq_compat :
forall Un Vn Wn Xn, Un == Wn -> Vn == Xn ->
Un ~ Vn -> Wn ~ Xn.
Proof.
intros Un Vn Wn Xn Huw Hvx Huv.
intros eps Heps.
destruct(Huv eps Heps) as [N HN].
exists N; intros n Hn.
unfold Rseq_minus.
rewrite <- Huw; rewrite <- Hvx.
apply HN; apply Hn.
Qed.
(** ** Boundedness and subsequences *)
Lemma even_odd_boundedness : forall (An : nat -> R) (M1 M2 : R),
Rseq_bound (fun n => An (2 * n)%nat) M1 ->
Rseq_bound (fun n => An (S (2 * n))) M2 ->
Rseq_bound An (Rmax M1 M2).
Proof.
intros An M1 M2 HM1 HM2 n ; destruct (n_modulo_2 n) as [n_even | n_odd].
destruct n_even as [p Hp] ; rewrite Hp ; apply Rle_trans with M1 ; [apply HM1 | apply RmaxLess1].
destruct n_odd as [p Hp] ; rewrite Hp ; apply Rle_trans with M2 ; [apply HM2 | apply RmaxLess2].
Qed.
(** ** Partial sequences. *)
Section Rseq_partial.
Variable Un : nat -> R.
(**********)
Lemma Rseq_partial_bound_max : forall N, exists M, forall n, (n <= N)%nat -> Un n <= M.
Proof.
induction N.
exists (Un 0).
intros n Hn; inversion Hn as [H|H]; apply Rle_refl.
destruct IHN as [M IHN].
exists (Rmax M (Un (S N))).
intros n Hn.
destruct (le_lt_eq_dec n (S N)) as [He|He]; try assumption.
eapply Rle_trans; [apply IHN|apply RmaxLess1].
apply lt_n_Sm_le; assumption.
rewrite He; apply RmaxLess2.
Qed.
(**********)
Lemma Rseq_partial_bound_min : forall N, exists m, forall n, (n <= N)%nat -> m <= Un n.
Proof.
induction N.
exists (Un 0).
intros n Hn; inversion Hn as [H|H]; apply Rle_refl.
destruct IHN as [m IHN].
exists (Rmin m (Un (S N))).
intros n Hn.
destruct (le_lt_eq_dec n (S N)) as [He|He]; try assumption.
eapply Rle_trans; [apply Rmin_l|apply IHN].
apply lt_n_Sm_le; assumption.
rewrite He; apply Rmin_r.
Qed.
(**********)
Lemma Rseq_partial_bound : forall N, exists M, forall n, (n <= N)%nat -> Rabs (Un n) <= M.
Proof.
intros N.
destruct (Rseq_partial_bound_max N) as [M HM].
destruct (Rseq_partial_bound_min N) as [m Hm].
exists (Rmax (Rabs m) (Rabs M)).
intros n Hn.
apply RmaxAbs; [apply Hm|apply HM]; assumption.
Qed.
End Rseq_partial.
(** ** Asymptotic properties. *)
(**********)
Definition Rseq_asymptotic P :=
forall (Q : Rseq -> Prop) Un,
(forall Vn, Q Vn -> P Vn) -> Rseq_eventually Q Un -> P Un.
(**********)
Definition Rseq_asymptotic2 P :=
forall (Q : Rseq -> Rseq -> Prop) Un Vn,
(forall Wn Xn, Q Wn Xn -> P Wn Xn) -> Rseq_eventually2 Q Un Vn -> P Un Vn.
(** * Convergence is asymptotic. *)
(**********)
Lemma Rseq_cv_asymptotic : forall l, Rseq_asymptotic (fun Un => Rseq_cv Un l).
Proof.
intros l Q Un HQ He eps Heps.
destruct He as [Ne HNe].
edestruct HQ as [N HN]; [eexact HNe|eexact Heps|].
exists (Ne + N)%nat; intros n Hn.
assert (Hn0 : exists n0, (n = Ne + n0)%nat).
induction Hn.
exists N; reflexivity.
destruct IHHn as [n0 H]; exists (S n0).
rewrite <- plus_Snm_nSm; simpl; rewrite H; reflexivity.
destruct Hn0 as [n0 Hn0].
rewrite Hn0; apply HN; omega.
Qed.
(**********)
Lemma Rseq_cv_asymptotic_eq_compat : forall Un Vn l,
(exists N, forall n : nat, (N <= n)%nat -> Un n = Vn n) -> Rseq_cv Un l -> Rseq_cv Vn l.
Proof.
intros Un Vn l [N HN] Hu eps Heps.
destruct (Hu eps Heps) as [N' HN'].
exists (N+N')%nat.
intros n Hn; unfold R_dist.
replace (Vn n -l)%R with ((Vn n - Un n) + (Un n -l))%R by ring.
apply Rle_lt_trans with (Rabs (Vn n - Un n)+ Rabs(Un n -l))%R.
apply Rabs_triang.
rewrite HN at 1.
unfold Rminus at 1.
rewrite Rplus_opp_r, Rabs_R0, Rplus_0_l.
apply HN'.
intuition.
intuition.
Qed.
(**********)
Lemma Rseq_cv_pos_infty_asymptotic : Rseq_asymptotic Rseq_cv_pos_infty.
Proof.
intros Q Un HQ He M.
destruct He as [Ne HNe].
edestruct HQ as [N HN]; [eexact HNe|].
exists (Ne + N)%nat; intros n Hn.
assert (Hn0 : exists n0, (n = Ne + n0)%nat).
induction Hn.
exists N; reflexivity.
destruct IHHn as [n0 H]; exists (S n0).
rewrite <- plus_Snm_nSm; simpl; rewrite H; reflexivity.
destruct Hn0 as [n0 Hn0].
rewrite Hn0; apply HN; omega.
Qed.
(**********)
Lemma Rseq_cv_neg_infty_asymptotic : Rseq_asymptotic Rseq_cv_neg_infty.
Proof.
intros Q Un HQ He M.
destruct He as [Ne HNe].
edestruct HQ as [N HN]; [eexact HNe|].
exists (Ne + N)%nat; intros n Hn.
assert (Hn0 : exists n0, (n = Ne + n0)%nat).
induction Hn.
exists N; reflexivity.
destruct IHHn as [n0 H]; exists (S n0).
rewrite <- plus_Snm_nSm; simpl; rewrite H; reflexivity.
destruct Hn0 as [n0 Hn0].
rewrite Hn0; apply HN; omega.
Qed.
(** * Landau relations are asymptotic. *)
(**********)
Lemma Rseq_big_O_asymptotic : Rseq_asymptotic2 Rseq_big_O.
Proof.
intros Q Un Vn HQ He.
destruct He as [Ne HNe].
edestruct HQ as [M [HM [N HN]]]; [eexact HNe|].
exists M; split.
assumption.
exists (Ne + N)%nat; intros n Hn.
assert (Hn0 : exists n0, (n = Ne + n0)%nat).
induction Hn.
exists N; reflexivity.
destruct IHHn as [n0 H]; exists (S n0).
rewrite <- plus_Snm_nSm; simpl; rewrite H; reflexivity.
destruct Hn0 as [n0 Hn0].
rewrite Hn0; apply HN; omega.
Qed.
(**********)
Lemma Rseq_little_O_asymptotic : Rseq_asymptotic2 Rseq_little_O.
Proof.
intros Q Un Vn HQ He.
destruct He as [Ne HNe].
intros eps Heps.
edestruct HQ as [N HN]; [eexact HNe|apply Heps|].
exists (Ne + N)%nat; intros n Hn.
assert (Hn0 : exists n0, (n = Ne + n0)%nat).
induction Hn.
exists N; reflexivity.
destruct IHHn as [n0 H]; exists (S n0).
rewrite <- plus_Snm_nSm; simpl; rewrite H; reflexivity.
destruct Hn0 as [n0 Hn0].
rewrite Hn0; apply HN; omega.
Qed.
(**********)
Lemma Rseq_equiv_asymptotic : Rseq_asymptotic2 Rseq_equiv.
Proof.
intros Q Un Vn HQ He.
destruct He as [Ne HNe].
intros eps Heps.
edestruct HQ as [N HN]; [eexact HNe|apply Heps|].
exists (Ne + N)%nat; intros n Hn.
assert (Hn0 : exists n0, (n = Ne + n0)%nat).
induction Hn.
exists N; reflexivity.
destruct IHHn as [n0 H]; exists (S n0).
rewrite <- plus_Snm_nSm; simpl; rewrite H; reflexivity.
destruct Hn0 as [n0 Hn0].
unfold Rseq_minus in HN.
rewrite Hn0; apply HN; omega.
Qed.
|
module BackpropNeuralNet
export
# types
NeuralNetwork,
# functions
init_network,
train,
net_eval
include("neural_net.jl")
end # module
|
module Prelude.Uninhabited
import Builtin
import Prelude.Basics
%default total
||| A canonical proof that some type is empty.
public export
interface Uninhabited t where
||| If I have a t, I've had a contradiction.
||| @ t the uninhabited type
uninhabited : t -> Void
||| The eliminator for the `Void` type.
%extern
public export
void : (0 x : Void) -> a
export
Uninhabited Void where
uninhabited = id
||| Use an absurd assumption to discharge a proof obligation.
||| @ t some empty type
||| @ a the goal type
||| @ h the contradictory hypothesis
public export
absurd : Uninhabited t => (h : t) -> a
absurd h = void (uninhabited h)
public export
Uninhabited (True = False) where
uninhabited Refl impossible
public export
Uninhabited (False = True) where
uninhabited Refl impossible
|
If $S$ is an open connected set in $\mathbb{R}^n$ with $n \geq 2$ and $T$ is a countable set, then $S - T$ is path-connected. |
[STATEMENT]
lemma get_root_node_si_parent_child_a_host_shadow_root_rel:
assumes "heap_is_wellformed h" and "known_ptrs h" and "type_wf h"
assumes "h \<turnstile> get_root_node_si ptr \<rightarrow>\<^sub>r root"
shows "(root, ptr) \<in> (parent_child_rel h \<union> a_host_shadow_root_rel h)\<^sup>*"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (root, ptr) \<in> (parent_child_rel h \<union> local.a_host_shadow_root_rel h)\<^sup>*
[PROOF STEP]
using assms
[PROOF STATE]
proof (prove)
using this:
heap_is_wellformed h
known_ptrs h
type_wf h
h \<turnstile> get_root_node_si ptr \<rightarrow>\<^sub>r root
goal (1 subgoal):
1. (root, ptr) \<in> (parent_child_rel h \<union> local.a_host_shadow_root_rel h)\<^sup>*
[PROOF STEP]
using get_ancestors_si_parent_child_a_host_shadow_root_rel get_ancestors_si_never_empty
[PROOF STATE]
proof (prove)
using this:
heap_is_wellformed h
known_ptrs h
type_wf h
h \<turnstile> get_root_node_si ptr \<rightarrow>\<^sub>r root
\<lbrakk>heap_is_wellformed ?h; known_ptrs ?h; type_wf ?h; ?h \<turnstile> get_ancestors_si ?child \<rightarrow>\<^sub>r ?ancestors\<rbrakk> \<Longrightarrow> ((?ptr, ?child) \<in> (parent_child_rel ?h \<union> local.a_host_shadow_root_rel ?h)\<^sup>*) = (?ptr \<in> set ?ancestors)
?h \<turnstile> get_ancestors_si ?child \<rightarrow>\<^sub>r ?ancestors \<Longrightarrow> ?ancestors \<noteq> []
goal (1 subgoal):
1. (root, ptr) \<in> (parent_child_rel h \<union> local.a_host_shadow_root_rel h)\<^sup>*
[PROOF STEP]
by(auto simp add: get_root_node_si_def elim!: bind_returns_result_E2 intro!: bind_pure_returns_result_I) |
Mac McCorkle runs a bar and helps out his partner, who is a agent with the CIA.
When McCorkle took his life savings and began to open a small pub in Bonn, Germany, after being discharged from the army, he wasn't looking for a partner. That didn't stop Mike Padillo from dropping in, handing him a check for half the value of the place, and telling Mac he could either accept the offer or see the opening delayed forever in red tape.
Knowing he really had no choice, McCorkle accepted gracefully, albeit unhappily. To his credit, Padillo, forced by his own superiors to make the extortion, had the decency to be embarrassed.
So began the partnership between the two men, one that would quickly turn into a life-long friendship. Mike Padillo worked for the government (probably the CIA). When not on assignment, he helped run the bar, which grew over the years in success and made both a considerable amount of money. But every couple of months, he would show up, tell McCorkle he'd be gone for a while, and a week or a month would go by with him gone.
Such was the basis for the series which probably was never meant to be one. The ending of the first book made it pretty clear that was it. Then the book won for Mr. Thomas an Edgar for the best first novel of 1966. I'm sure that's when the publishers began to demand a sequel.
The sequel came the next year but this time Mr. Thomas apparently withstood the pressure for more and used his incredible talent on other ideas. Six books, including three in a different non-spy series followed before the pair of McCorkle and Padillo were heard from again. And then it would be 19 years more before the last in the series was written.
Through the years, the two unwavering qualities of this series remained the close friendship between McCorkle and Padillo and the terrific writing skills of Ross Thomas.
McCorkle discovers that his friend and partner has been sacrificed by his superiors in an exchange with the Soviets to get back two defectors. He realizes he is the only one willing to risk it all for Padillo.
Happily married and living in Washington, McCorkle would have been happy to meet his old friend Padillo if McCorkle's wife had been kidnapped to force Padillo to kill someone.
Long out of the game, both men are less than anxious to help protect the future king of a country rich with oil but Padillo owes a huge favor to the ones doing the asking.
The death of a CIA agent didn't raise too much of a fuss until it is learned he wrote a tell-all book which someone wants buried, possibly along with the agent's son who might have it. The son asks Padillo and McCorkle for help.
A fellow spy-fiction fan and friend of mine was almost jumping for joy when he got his hands on "The Backup Men" in 1972-3, shouting, "They're back! McCorkle and Padillo!" You would have thought I'd slapped him by his expression when I asked, "Who?"
After having the first book literally thrust into my hands later and reading the first few pages, I knew I'd never have to ask that question again. I was as hooked as my friend (thank you, Bob Walker, wherever you are!).
It isn't hard to understand why anyone who likes spy-fi would love this series. Mr. Thomas's skill as an author are without a doubt. The man won TWO Edgars. Most writers don't win any. He had two. And deserved them both handily.
Furthermore, the characters are awesomely interesting and developed, the style is both exciting and wry, the locales are perfectly presented, and the plots just make sense. What more can you ask for, except more adventures.
Unfortunately, Mr. Thomas' passing makes that impossible but I like to believe that McCorkle and Padillo are still out there, serving drinks and saving the day. |
{-
This module defines the basic opens of the Zariski lattice and proves that they're a basis of the lattice.
It also contains the construction of the structure presheaf and a proof of the sheaf property on basic opens,
using the theory developed in the module PreSheafFromUniversalProp and its toSheaf.lemma.
Note that the structure sheaf is a functor into R-algebras and not just commutative rings.
-}
{-# OPTIONS --safe --experimental-lossy-unification #-}
module Cubical.Algebra.ZariskiLattice.StructureSheaf where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Function
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.Univalence
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Transport
open import Cubical.Foundations.Powerset using (ℙ ; ⊆-refl-consequence)
renaming (_∈_ to _∈ₚ_ ; subst-∈ to subst-∈ₚ)
import Cubical.Data.Empty as ⊥
open import Cubical.Data.Bool
open import Cubical.Data.Nat renaming ( _+_ to _+ℕ_ ; _·_ to _·ℕ_ ; _^_ to _^ℕ_
; +-comm to +ℕ-comm ; +-assoc to +ℕ-assoc
; ·-assoc to ·ℕ-assoc ; ·-comm to ·ℕ-comm
; ·-identityʳ to ·ℕ-rid)
open import Cubical.Data.Sigma.Base
open import Cubical.Data.Sigma.Properties
open import Cubical.Data.FinData
open import Cubical.Data.Unit
open import Cubical.Relation.Nullary
open import Cubical.Relation.Binary
open import Cubical.Relation.Binary.Poset
open import Cubical.Algebra.Ring
open import Cubical.Algebra.Ring.Properties
open import Cubical.Algebra.Ring.BigOps
open import Cubical.Algebra.Algebra
open import Cubical.Algebra.CommRing
open import Cubical.Algebra.CommRing.BinomialThm
open import Cubical.Algebra.CommRing.Ideal
open import Cubical.Algebra.CommRing.FGIdeal
open import Cubical.Algebra.CommRing.RadicalIdeal
open import Cubical.Algebra.CommRing.Localisation.Base
open import Cubical.Algebra.CommRing.Localisation.UniversalProperty
open import Cubical.Algebra.CommRing.Localisation.InvertingElements
open import Cubical.Algebra.CommRing.Localisation.PullbackSquare
open import Cubical.Algebra.CommAlgebra.Base
open import Cubical.Algebra.CommAlgebra.Properties
open import Cubical.Algebra.CommAlgebra.Localisation
open import Cubical.Algebra.CommAlgebra.Instances.Unit
open import Cubical.Algebra.RingSolver.Reflection
open import Cubical.Algebra.Semilattice
open import Cubical.Algebra.Lattice
open import Cubical.Algebra.DistLattice
open import Cubical.Algebra.DistLattice.Basis
open import Cubical.Algebra.DistLattice.BigOps
open import Cubical.Algebra.ZariskiLattice.Base
open import Cubical.Algebra.ZariskiLattice.UniversalProperty
open import Cubical.Categories.Category.Base hiding (_[_,_])
open import Cubical.Categories.Functor
open import Cubical.Categories.Limits.Pullback
open import Cubical.Categories.Instances.CommAlgebras
open import Cubical.Categories.Instances.DistLattice
open import Cubical.Categories.Instances.Semilattice
open import Cubical.Categories.DistLatticeSheaf
open import Cubical.HITs.SetQuotients as SQ
open import Cubical.HITs.PropositionalTruncation as PT
open Iso
open BinaryRelation
open isEquivRel
private
variable
ℓ ℓ' : Level
module _ (R' : CommRing ℓ) where
open CommRingStr ⦃...⦄
open RingTheory (CommRing→Ring R')
open CommIdeal R'
open isCommIdeal
open ZarLat R'
open ZarLatUniversalProp R'
open IsZarMap
open Join ZariskiLattice
open JoinSemilattice (Lattice→JoinSemilattice (DistLattice→Lattice ZariskiLattice))
open IsBasis
private
R = fst R'
instance
_ = snd R'
⟨_⟩ : R → CommIdeal
⟨ f ⟩ = ⟨ replicateFinVec 1 f ⟩[ R' ]
⟨_⟩ₚ : R × R → CommIdeal -- p is for pair
⟨ f , g ⟩ₚ = ⟨ replicateFinVec 1 f ++Fin replicateFinVec 1 g ⟩[ R' ]
BasicOpens : ℙ ZL
BasicOpens 𝔞 = (∃[ f ∈ R ] (D f ≡ 𝔞)) , isPropPropTrunc
BO : Type (ℓ-suc ℓ)
BO = Σ[ 𝔞 ∈ ZL ] (𝔞 ∈ₚ BasicOpens)
basicOpensAreBasis : IsBasis ZariskiLattice BasicOpens
contains1 basicOpensAreBasis = ∣ 1r , isZarMapD .pres1 ∣
∧lClosed basicOpensAreBasis 𝔞 𝔟 = map2
λ (f , Df≡𝔞) (g , Dg≡𝔟) → (f · g) , isZarMapD .·≡∧ f g ∙ cong₂ (_∧z_) Df≡𝔞 Dg≡𝔟
⋁Basis basicOpensAreBasis = elimProp (λ _ → isPropPropTrunc) Σhelper
where
Σhelper : (a : Σ[ n ∈ ℕ ] FinVec R n)
→ ∃[ n ∈ ℕ ] Σ[ α ∈ FinVec ZL n ] (∀ i → α i ∈ₚ BasicOpens) × (⋁ α ≡ [ a ])
Σhelper (n , α) = ∣ n , (D ∘ α) , (λ i → ∣ α i , refl ∣) , path ∣
where
path : ⋁ (D ∘ α) ≡ [ n , α ]
path = funExt⁻ (cong fst ZLUniversalPropCorollary) _
-- The structure presheaf on BO
ZariskiCat = DistLatticeCategory ZariskiLattice
BOCat : Category (ℓ-suc ℓ) (ℓ-suc ℓ)
BOCat = ΣPropCat ZariskiCat BasicOpens
private
P : ZL → Type _
P 𝔞 = Σ[ f ∈ R ] (D f ≡ 𝔞) -- the untruncated defining property
𝓕 : Σ ZL P → CommAlgebra R' _
𝓕 (_ , f , _) = R[1/ f ]AsCommAlgebra -- D(f) ↦ R[1/f]
uniqueHom : ∀ (x y : Σ ZL P) → (fst x) ≤ (fst y) → isContr (CommAlgebraHom (𝓕 y) (𝓕 x))
uniqueHom (𝔞 , f , p) (𝔟 , g , q) = contrHoms 𝔞 𝔟 f g p q
where
open InvertingElementsBase R'
contrHoms : (𝔞 𝔟 : ZL) (f g : R) (p : D f ≡ 𝔞) (q : D g ≡ 𝔟)
→ 𝔞 ≤ 𝔟 → isContr (CommAlgebraHom R[1/ g ]AsCommAlgebra R[1/ f ]AsCommAlgebra)
contrHoms 𝔞 𝔟 f g p q 𝔞≤𝔟 = R[1/g]HasAlgUniversalProp R[1/ f ]AsCommAlgebra
λ s s∈[gⁿ|n≥0] → subst-∈ₚ (R[1/ f ]AsCommRing ˣ)
(sym (·Rid (s /1))) --can't apply the lemma directly as we get mult with 1 somewhere
(RadicalLemma.toUnit R' f g f∈√⟨g⟩ s s∈[gⁿ|n≥0])
where
open AlgLoc R' [ g ⁿ|n≥0] (powersFormMultClosedSubset g)
renaming (S⁻¹RHasAlgUniversalProp to R[1/g]HasAlgUniversalProp)
open S⁻¹RUniversalProp R' [ f ⁿ|n≥0] (powersFormMultClosedSubset f) using (_/1)
open RadicalIdeal R'
private
instance
_ = snd R[1/ f ]AsCommRing
Df≤Dg : D f ≤ D g
Df≤Dg = subst2 _≤_ (sym p) (sym q) 𝔞≤𝔟
radicalHelper : √ ⟨ f , g ⟩ₚ ≡ √ ⟨ g ⟩
radicalHelper =
isEquivRel→effectiveIso (λ _ _ → isSetCommIdeal _ _) ∼EquivRel _ _ .fun Df≤Dg
f∈√⟨g⟩ : f ∈ √ ⟨ g ⟩
f∈√⟨g⟩ = subst (f ∈_) radicalHelper (∈→∈√ _ _ (indInIdeal _ _ zero))
open PreSheafFromUniversalProp ZariskiCat P 𝓕 uniqueHom
BasisStructurePShf : Functor (BOCat ^op) (CommAlgebrasCategory R')
BasisStructurePShf = universalPShf
-- now prove the sheaf properties
open SheafOnBasis ZariskiLattice (CommAlgebrasCategory R' {ℓ' = ℓ})
(TerminalCommAlgebra R') BasicOpens basicOpensAreBasis
isSheafBasisStructurePShf : isDLBasisSheaf BasisStructurePShf
fst isSheafBasisStructurePShf 0∈BO =
transport (λ i → F-ob (0z , canonical0∈BO≡0∈BO i) ≡ UnitCommAlgebra R') R[1/0]≡0
where
open Functor ⦃...⦄
instance
_ = BasisStructurePShf
canonical0∈BO : 0z ∈ₚ BasicOpens
canonical0∈BO = ∣ 0r , isZarMapD .pres0 ∣
canonical0∈BO≡0∈BO : canonical0∈BO ≡ 0∈BO
canonical0∈BO≡0∈BO = BasicOpens 0z .snd _ _
R[1/0]≡0 : R[1/ 0r ]AsCommAlgebra ≡ UnitCommAlgebra R'
R[1/0]≡0 = uaCommAlgebra (e , eIsRHom)
where
open InvertingElementsBase R' using (isContrR[1/0])
open IsAlgebraHom
e : R[1/ 0r ]AsCommAlgebra .fst ≃ UnitCommAlgebra R' .fst
e = isContr→Equiv isContrR[1/0] isContrUnit*
eIsRHom : IsCommAlgebraEquiv (R[1/ 0r ]AsCommAlgebra .snd) e (UnitCommAlgebra R' .snd)
pres0 eIsRHom = refl
pres1 eIsRHom = refl
pres+ eIsRHom _ _ = refl
pres· eIsRHom _ _ = refl
pres- eIsRHom _ = refl
pres⋆ eIsRHom _ _ = refl
snd isSheafBasisStructurePShf (𝔞 , 𝔞∈BO) (𝔟 , 𝔟∈BO) 𝔞∨𝔟∈BO = curriedHelper 𝔞 𝔟 𝔞∈BO 𝔟∈BO 𝔞∨𝔟∈BO
where
open condSquare
{-
here:
BFsq (𝔞 , 𝔞∈BO) (𝔟 , 𝔟∈BO) 𝔞∨𝔟∈BO BasisStructurePShf =
𝓞 (𝔞∨𝔟) → 𝓞 (𝔞)
↓ ↓
𝓞 (𝔟) → 𝓞 (𝔞∧𝔟)
-}
curriedHelper : (𝔞 𝔟 : ZL) (𝔞∈BO : 𝔞 ∈ₚ BasicOpens) (𝔟∈BO : 𝔟 ∈ₚ BasicOpens)
(𝔞∨𝔟∈BO : 𝔞 ∨z 𝔟 ∈ₚ BasicOpens)
→ isPullback (CommAlgebrasCategory R') _ _ _
(BFsq (𝔞 , 𝔞∈BO) (𝔟 , 𝔟∈BO) 𝔞∨𝔟∈BO BasisStructurePShf)
curriedHelper 𝔞 𝔟 = elim3 (λ 𝔞∈BO 𝔟∈BO 𝔞∨𝔟∈BO → isPropIsPullback _ _ _ _
(BFsq (𝔞 , 𝔞∈BO) (𝔟 , 𝔟∈BO) 𝔞∨𝔟∈BO BasisStructurePShf))
Σhelper
where
-- write everything explicitly so things can type-check
thePShfCospan : (a : Σ[ f ∈ R ] D f ≡ 𝔞) (b : Σ[ g ∈ R ] D g ≡ 𝔟)
→ Cospan (CommAlgebrasCategory R')
Cospan.l (thePShfCospan (f , Df≡𝔞) (g , Dg≡𝔟)) = BasisStructurePShf .Functor.F-ob (𝔟 , ∣ g , Dg≡𝔟 ∣)
Cospan.m (thePShfCospan (f , Df≡𝔞) (g , Dg≡𝔟)) = BasisStructurePShf .Functor.F-ob
(𝔞 ∧z 𝔟 , basicOpensAreBasis .∧lClosed 𝔞 𝔟 ∣ f , Df≡𝔞 ∣ ∣ g , Dg≡𝔟 ∣)
Cospan.r (thePShfCospan (f , Df≡𝔞) (g , Dg≡𝔟)) = BasisStructurePShf .Functor.F-ob (𝔞 , ∣ f , Df≡𝔞 ∣)
Cospan.s₁ (thePShfCospan (f , Df≡𝔞) (g , Dg≡𝔟)) = BasisStructurePShf .Functor.F-hom
{x = (𝔟 , ∣ g , Dg≡𝔟 ∣)}
{y = (𝔞 ∧z 𝔟 , basicOpensAreBasis .∧lClosed 𝔞 𝔟 ∣ f , Df≡𝔞 ∣ ∣ g , Dg≡𝔟 ∣)}
(hom-∧₂ ZariskiLattice (CommAlgebrasCategory R' {ℓ' = ℓ}) (TerminalCommAlgebra R') 𝔞 𝔟)
Cospan.s₂ (thePShfCospan (f , Df≡𝔞) (g , Dg≡𝔟)) = BasisStructurePShf .Functor.F-hom
{x = (𝔞 , ∣ f , Df≡𝔞 ∣)}
{y = (𝔞 ∧z 𝔟 , basicOpensAreBasis .∧lClosed 𝔞 𝔟 ∣ f , Df≡𝔞 ∣ ∣ g , Dg≡𝔟 ∣)}
(hom-∧₁ ZariskiLattice (CommAlgebrasCategory R' {ℓ' = ℓ}) (TerminalCommAlgebra R') 𝔞 𝔟)
Σhelper : (a : Σ[ f ∈ R ] D f ≡ 𝔞) (b : Σ[ g ∈ R ] D g ≡ 𝔟) (c : Σ[ h ∈ R ] D h ≡ 𝔞 ∨z 𝔟)
→ isPullback (CommAlgebrasCategory R') (thePShfCospan a b) _ _
(BFsq (𝔞 , ∣ a ∣) (𝔟 , ∣ b ∣) ∣ c ∣ BasisStructurePShf)
Σhelper (f , Df≡𝔞) (g , Dg≡𝔟) (h , Dh≡𝔞∨𝔟) = toSheaf.lemma
(𝔞 ∨z 𝔟 , ∣ h , Dh≡𝔞∨𝔟 ∣)
(𝔞 , ∣ f , Df≡𝔞 ∣)
(𝔟 , ∣ g , Dg≡𝔟 ∣)
(𝔞 ∧z 𝔟 , basicOpensAreBasis .∧lClosed 𝔞 𝔟 ∣ f , Df≡𝔞 ∣ ∣ g , Dg≡𝔟 ∣)
(Bsq (𝔞 , ∣ f , Df≡𝔞 ∣) (𝔟 , ∣ g , Dg≡𝔟 ∣) ∣ h , Dh≡𝔞∨𝔟 ∣)
theAlgebraCospan theAlgebraPullback refl gPath fPath fgPath
where
open Exponentiation R'
open RadicalIdeal R'
open InvertingElementsBase R'
open DoubleLoc R' h
open S⁻¹RUniversalProp R' [ h ⁿ|n≥0] (powersFormMultClosedSubset h)
open CommIdeal R[1/ h ]AsCommRing using () renaming (CommIdeal to CommIdealₕ ; _∈_ to _∈ₕ_)
instance
_ = snd R[1/ h ]AsCommRing
⟨_⟩ₕ : R[1/ h ] × R[1/ h ] → CommIdealₕ
⟨ x , y ⟩ₕ = ⟨ replicateFinVec 1 x ++Fin replicateFinVec 1 y ⟩[ R[1/ h ]AsCommRing ]
-- the crucial algebraic fact:
radicalPath : √ ⟨ h ⟩ ≡ √ ⟨ f , g ⟩ₚ
radicalPath = isEquivRel→effectiveIso (λ _ _ → isSetCommIdeal _ _) ∼EquivRel _ _ .fun DHelper
where
DHelper : D h ≡ D f ∨z D g
DHelper = Dh≡𝔞∨𝔟 ∙ cong₂ (_∨z_) (sym Df≡𝔞) (sym Dg≡𝔟)
f∈√⟨h⟩ : f ∈ √ ⟨ h ⟩
f∈√⟨h⟩ = subst (f ∈_) (sym radicalPath) (∈→∈√ _ _ (indInIdeal _ _ zero))
g∈√⟨h⟩ : g ∈ √ ⟨ h ⟩
g∈√⟨h⟩ = subst (g ∈_) (sym radicalPath) (∈→∈√ _ _ (indInIdeal _ _ (suc zero)))
fg∈√⟨h⟩ : (f · g) ∈ √ ⟨ h ⟩
fg∈√⟨h⟩ = √ ⟨ h ⟩ .snd .·Closed f g∈√⟨h⟩
1∈fgIdeal : 1r ∈ₕ ⟨ (f /1) , (g /1) ⟩ₕ
1∈fgIdeal = helper1 (subst (h ∈_) radicalPath (∈→∈√ _ _ (indInIdeal _ _ zero)))
where
helper1 : h ∈ √ ⟨ f , g ⟩ₚ
→ 1r ∈ₕ ⟨ (f /1) , (g /1) ⟩ₕ
helper1 = PT.rec isPropPropTrunc (uncurry helper2)
where
helper2 : (n : ℕ)
→ h ^ n ∈ ⟨ f , g ⟩ₚ
→ 1r ∈ₕ ⟨ (f /1) , (g /1) ⟩ₕ
helper2 n = map helper3
where
helper3 : Σ[ α ∈ FinVec R 2 ]
h ^ n ≡ linearCombination R' α (λ { zero → f ; (suc zero) → g })
→ Σ[ β ∈ FinVec R[1/ h ] 2 ]
1r ≡ linearCombination R[1/ h ]AsCommRing β
λ { zero → f /1 ; (suc zero) → g /1 }
helper3 (α , p) = β , path
where
β : FinVec R[1/ h ] 2
β zero = [ α zero , h ^ n , ∣ n , refl ∣ ]
β (suc zero) = [ α (suc zero) , h ^ n , ∣ n , refl ∣ ]
path : 1r ≡ linearCombination R[1/ h ]AsCommRing β
λ { zero → f /1 ; (suc zero) → g /1 }
path = eq/ _ _ ((1r , ∣ 0 , refl ∣) , bigPath)
∙ cong (β zero · (f /1) +_) (sym (+Rid (β (suc zero) · (g /1))))
where
useSolver1 : ∀ hn → 1r · 1r · ((hn · 1r) · (hn · 1r)) ≡ hn · hn
useSolver1 = solve R'
useSolver2 : ∀ az f hn as g → hn · (az · f + (as · g + 0r))
≡ 1r · (az · f · (hn · 1r) + as · g · (hn · 1r)) · 1r
useSolver2 = solve R'
bigPath : 1r · 1r · ((h ^ n · 1r) · (h ^ n · 1r))
≡ 1r · (α zero · f · (h ^ n · 1r) + α (suc zero) · g · (h ^ n · 1r)) · 1r
bigPath = useSolver1 (h ^ n) ∙ cong (h ^ n ·_) p ∙ useSolver2 _ _ _ _ _
{-
We get the following pullback square in CommRings
R[1/h] → R[1/h][1/f]
⌟
↓ ↓
R[1/h][1/g] → R[1/h][1/fg]
this lifts to a pullback in R-Algebras using PullbackFromCommRing
as all for rings have canonical morphisms coming from R
and all the triangles commute.
Then using toSheaf.lemma we get the desired square
R[1/h] → R[1/f]
⌟
↓ ↓
R[1/g] → R[1/fg]
by only providing paths between the corresponding vertices of the square.
These paths are constructed using S⁻¹RAlgCharEquiv, which gives
an equivalent characterization of the universal property of localization
that can be found in e.g. Cor 3.2 of Atiyah-MacDonald
-}
theRingCospan = fgCospan R[1/ h ]AsCommRing (f /1) (g /1)
theRingPullback = fgPullback R[1/ h ]AsCommRing (f /1) (g /1) 1∈fgIdeal
R[1/h][1/f] = InvertingElementsBase.R[1/_] R[1/ h ]AsCommRing (f /1)
R[1/h][1/f]AsCommRing = InvertingElementsBase.R[1/_]AsCommRing R[1/ h ]AsCommRing (f /1)
R[1/h][1/g] = InvertingElementsBase.R[1/_] R[1/ h ]AsCommRing (g /1)
R[1/h][1/g]AsCommRing = InvertingElementsBase.R[1/_]AsCommRing R[1/ h ]AsCommRing (g /1)
R[1/h][1/fg] = InvertingElementsBase.R[1/_] R[1/ h ]AsCommRing ((f /1) · (g /1))
R[1/h][1/fg]AsCommRing = InvertingElementsBase.R[1/_]AsCommRing
R[1/ h ]AsCommRing ((f /1) · (g /1))
open IsRingHom
/1/1AsCommRingHomFG : CommRingHom R' R[1/h][1/fg]AsCommRing
fst /1/1AsCommRingHomFG r = [ [ r , 1r , ∣ 0 , refl ∣ ] , 1r , ∣ 0 , refl ∣ ]
pres0 (snd /1/1AsCommRingHomFG) = refl
pres1 (snd /1/1AsCommRingHomFG) = refl
pres+ (snd /1/1AsCommRingHomFG) x y = cong [_] (≡-× (cong [_] (≡-×
(cong₂ _+_ (useSolver x) (useSolver y))
(Σ≡Prop (λ _ → isPropPropTrunc) (useSolver 1r))))
(Σ≡Prop (λ _ → isPropPropTrunc) (sym (·Rid 1r))))
where
useSolver : ∀ a → a ≡ a · 1r · (1r · 1r)
useSolver = solve R'
pres· (snd /1/1AsCommRingHomFG) x y = cong [_] (≡-× (cong [_] (≡-× refl
(Σ≡Prop (λ _ → isPropPropTrunc) (sym (·Rid 1r)))))
(Σ≡Prop (λ _ → isPropPropTrunc) (sym (·Rid 1r))))
pres- (snd /1/1AsCommRingHomFG) x = refl
open Cospan
open Pullback
open RingHoms
isRHomR[1/h]→R[1/h][1/f] : theRingPullback .pbPr₂ ∘r /1AsCommRingHom ≡ /1/1AsCommRingHom f
isRHomR[1/h]→R[1/h][1/f] = RingHom≡ (funExt (λ x → refl))
isRHomR[1/h]→R[1/h][1/g] : theRingPullback .pbPr₁ ∘r /1AsCommRingHom ≡ /1/1AsCommRingHom g
isRHomR[1/h]→R[1/h][1/g] = RingHom≡ (funExt (λ x → refl))
isRHomR[1/h][1/f]→R[1/h][1/fg] : theRingCospan .s₂ ∘r /1/1AsCommRingHom f ≡ /1/1AsCommRingHomFG
isRHomR[1/h][1/f]→R[1/h][1/fg] = RingHom≡ (funExt
(λ x → cong [_] (≡-× (cong [_] (≡-× (cong (x ·_) (transportRefl 1r) ∙ ·Rid x)
(Σ≡Prop (λ _ → isPropPropTrunc) (cong (1r ·_) (transportRefl 1r) ∙ ·Rid 1r))))
(Σ≡Prop (λ _ → isPropPropTrunc) (cong (1r ·_) (transportRefl 1r) ∙ ·Rid 1r)))))
isRHomR[1/h][1/g]→R[1/h][1/fg] : theRingCospan .s₁ ∘r /1/1AsCommRingHom g ≡ /1/1AsCommRingHomFG
isRHomR[1/h][1/g]→R[1/h][1/fg] = RingHom≡ (funExt
(λ x → cong [_] (≡-× (cong [_] (≡-× (cong (x ·_) (transportRefl 1r) ∙ ·Rid x)
(Σ≡Prop (λ _ → isPropPropTrunc) (cong (1r ·_) (transportRefl 1r) ∙ ·Rid 1r))))
(Σ≡Prop (λ _ → isPropPropTrunc) (cong (1r ·_) (transportRefl 1r) ∙ ·Rid 1r)))))
open PullbackFromCommRing R' theRingCospan theRingPullback
/1AsCommRingHom (/1/1AsCommRingHom f) (/1/1AsCommRingHom g) /1/1AsCommRingHomFG
theAlgebraCospan = algCospan isRHomR[1/h]→R[1/h][1/f]
isRHomR[1/h]→R[1/h][1/g]
isRHomR[1/h][1/f]→R[1/h][1/fg]
isRHomR[1/h][1/g]→R[1/h][1/fg]
theAlgebraPullback = algPullback isRHomR[1/h]→R[1/h][1/f]
isRHomR[1/h]→R[1/h][1/g]
isRHomR[1/h][1/f]→R[1/h][1/fg]
isRHomR[1/h][1/g]→R[1/h][1/fg]
--and the three remaining paths
fPath : theAlgebraCospan .r ≡ R[1/ f ]AsCommAlgebra
fPath = doubleLocCancel f∈√⟨h⟩
where
open DoubleAlgLoc R' h f
gPath : theAlgebraCospan .l ≡ R[1/ g ]AsCommAlgebra
gPath = doubleLocCancel g∈√⟨h⟩
where
open DoubleAlgLoc R' h g
fgPath : theAlgebraCospan .m ≡ R[1/ (f · g) ]AsCommAlgebra
fgPath = path ∙ doubleLocCancel fg∈√⟨h⟩
where
open DoubleAlgLoc R' h (f · g)
open CommAlgChar R'
R[1/h][1/fg]AsCommRing' = InvertingElementsBase.R[1/_]AsCommRing R[1/ h ]AsCommRing ((f · g) /1)
path : toCommAlg (R[1/h][1/fg]AsCommRing , /1/1AsCommRingHomFG)
≡ toCommAlg (R[1/h][1/fg]AsCommRing' , /1/1AsCommRingHom (f · g))
path = cong toCommAlg (ΣPathP (p , q))
where
eqInR[1/h] : (f /1) · (g /1) ≡ (f · g) /1
eqInR[1/h] = sym (/1AsCommRingHom .snd .pres· f g)
p : R[1/h][1/fg]AsCommRing ≡ R[1/h][1/fg]AsCommRing'
p i = InvertingElementsBase.R[1/_]AsCommRing R[1/ h ]AsCommRing (eqInR[1/h] i)
q : PathP (λ i → CommRingHom R' (p i)) /1/1AsCommRingHomFG (/1/1AsCommRingHom (f · g))
q = toPathP (RingHom≡ (funExt (
λ x → cong [_] (≡-× (cong [_] (≡-× (transportRefl _ ∙ transportRefl x)
(Σ≡Prop (λ _ → isPropPropTrunc) (transportRefl 1r))))
(Σ≡Prop (λ _ → isPropPropTrunc) (transportRefl 1r))))))
|
(* Title: HOL/Auth/n_german_lemma_inv__27_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_german Protocol Case Study*}
theory n_german_lemma_inv__27_on_rules imports n_german_lemma_on_inv__27
begin
section{*All lemmas on causal relation between inv__27*}
lemma lemma_inv__27_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__27 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqEVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__27) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__27) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
/-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
! This file was ported from Lean 3 source module linear_algebra.tensor_algebra.to_tensor_power
! leanprover-community/mathlib commit d97a0c9f7a7efe6d76d652c5a6b7c9c634b70e0a
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.LinearAlgebra.TensorAlgebra.Basic
import Mathbin.LinearAlgebra.TensorPower
/-!
# Tensor algebras as direct sums of tensor powers
In this file we show that `tensor_algebra R M` is isomorphic to a direct sum of tensor powers, as
`tensor_algebra.equiv_direct_sum`.
-/
open DirectSum TensorProduct
variable {R M : Type _} [CommSemiring R] [AddCommMonoid M] [Module R M]
namespace TensorPower
/-- The canonical embedding from a tensor power to the tensor algebra -/
def toTensorAlgebra {n} : (⨂[R]^n) M →ₗ[R] TensorAlgebra R M :=
PiTensorProduct.lift (TensorAlgebra.tprod R M n)
#align tensor_power.to_tensor_algebra TensorPower.toTensorAlgebra
@[simp]
theorem toTensorAlgebra_tprod {n} (x : Fin n → M) :
TensorPower.toTensorAlgebra (PiTensorProduct.tprod R x) = TensorAlgebra.tprod R M n x :=
PiTensorProduct.lift.tprod _
#align tensor_power.to_tensor_algebra_tprod TensorPower.toTensorAlgebra_tprod
@[simp]
theorem toTensorAlgebra_ghasOne :
(@GradedMonoid.GOne.one _ (fun n => (⨂[R]^n) M) _ _).toTensorAlgebra = 1 :=
TensorPower.toTensorAlgebra_tprod _
#align tensor_power.to_tensor_algebra_ghas_one TensorPower.toTensorAlgebra_ghasOne
@[simp]
theorem toTensorAlgebra_ghasMul {i j} (a : (⨂[R]^i) M) (b : (⨂[R]^j) M) :
(@GradedMonoid.GMul.mul _ (fun n => (⨂[R]^n) M) _ _ _ _ a b).toTensorAlgebra =
a.toTensorAlgebra * b.toTensorAlgebra :=
by
-- change `a` and `b` to `tprod R a` and `tprod R b`
rw [TensorPower.ghasMul_eq_coe_linearMap, ← LinearMap.compr₂_apply, ← @LinearMap.mul_apply' R, ←
LinearMap.compl₂_apply, ← LinearMap.comp_apply]
refine' LinearMap.congr_fun (LinearMap.congr_fun _ a) b
clear a b
ext (a b)
simp only [LinearMap.compr₂_apply, LinearMap.mul_apply', LinearMap.compl₂_apply,
LinearMap.comp_apply, LinearMap.compMultilinearMap_apply, PiTensorProduct.lift.tprod,
TensorPower.tprod_mul_tprod, TensorPower.toTensorAlgebra_tprod, TensorAlgebra.tprod_apply, ←
ghas_mul_eq_coe_linear_map]
refine' Eq.trans _ List.prod_append
congr
rw [← List.map_ofFn _ (TensorAlgebra.ι R), ← List.map_ofFn _ (TensorAlgebra.ι R), ←
List.map_ofFn _ (TensorAlgebra.ι R), ← List.map_append, List.ofFn_fin_append]
#align tensor_power.to_tensor_algebra_ghas_mul TensorPower.toTensorAlgebra_ghasMul
@[simp]
theorem toTensorAlgebra_galgebra_toFun (r : R) :
(@DirectSum.Galgebra.toFun _ R (fun n => (⨂[R]^n) M) _ _ _ _ _ _ _ r).toTensorAlgebra =
algebraMap _ _ r :=
by
rw [TensorPower.galgebra_toFun_def, TensorPower.algebraMap₀_eq_smul_one, LinearMap.map_smul,
TensorPower.toTensorAlgebra_ghasOne, Algebra.algebraMap_eq_smul_one]
#align tensor_power.to_tensor_algebra_galgebra_to_fun TensorPower.toTensorAlgebra_galgebra_toFun
end TensorPower
namespace TensorAlgebra
/-- The canonical map from a direct sum of tensor powers to the tensor algebra. -/
def ofDirectSum : (⨁ n, (⨂[R]^n) M) →ₐ[R] TensorAlgebra R M :=
DirectSum.toAlgebra _ _ (fun n => TensorPower.toTensorAlgebra) TensorPower.toTensorAlgebra_ghasOne
(fun i j => TensorPower.toTensorAlgebra_ghasMul) TensorPower.toTensorAlgebra_galgebra_toFun
#align tensor_algebra.of_direct_sum TensorAlgebra.ofDirectSum
@[simp]
theorem ofDirectSum_of_tprod {n} (x : Fin n → M) :
ofDirectSum (DirectSum.of _ n (PiTensorProduct.tprod R x)) = tprod R M n x :=
(DirectSum.toAddMonoid_of _ _ _).trans (TensorPower.toTensorAlgebra_tprod _)
#align tensor_algebra.of_direct_sum_of_tprod TensorAlgebra.ofDirectSum_of_tprod
/-- The canonical map from the tensor algebra to a direct sum of tensor powers. -/
def toDirectSum : TensorAlgebra R M →ₐ[R] ⨁ n, (⨂[R]^n) M :=
TensorAlgebra.lift R <|
DirectSum.lof R ℕ (fun n => (⨂[R]^n) M) _ ∘ₗ
(LinearEquiv.symm <| PiTensorProduct.subsingletonEquiv (0 : Fin 1) : M ≃ₗ[R] _).toLinearMap
#align tensor_algebra.to_direct_sum TensorAlgebra.toDirectSum
@[simp]
theorem toDirectSum_ι (x : M) :
toDirectSum (ι R x) =
DirectSum.of (fun n => (⨂[R]^n) M) _ (PiTensorProduct.tprod R fun _ : Fin 1 => x) :=
TensorAlgebra.lift_ι_apply _ _
#align tensor_algebra.to_direct_sum_ι TensorAlgebra.toDirectSum_ι
theorem ofDirectSum_comp_toDirectSum :
ofDirectSum.comp toDirectSum = AlgHom.id R (TensorAlgebra R M) :=
by
ext
simp [DirectSum.lof_eq_of, tprod_apply]
#align tensor_algebra.of_direct_sum_comp_to_direct_sum TensorAlgebra.ofDirectSum_comp_toDirectSum
@[simp]
theorem ofDirectSum_toDirectSum (x : TensorAlgebra R M) : ofDirectSum x.toDirectSum = x :=
AlgHom.congr_fun ofDirectSum_comp_toDirectSum x
#align tensor_algebra.of_direct_sum_to_direct_sum TensorAlgebra.ofDirectSum_toDirectSum
@[simp]
theorem mk_reindex_cast {n m : ℕ} (h : n = m) (x : (⨂[R]^n) M) :
GradedMonoid.mk m (PiTensorProduct.reindex R M (Equiv.cast <| congr_arg Fin h) x) =
GradedMonoid.mk n x :=
Eq.symm (PiTensorProduct.gradedMonoid_eq_of_reindex_cast h rfl)
#align tensor_algebra.mk_reindex_cast TensorAlgebra.mk_reindex_cast
@[simp]
theorem mk_reindex_fin_cast {n m : ℕ} (h : n = m) (x : (⨂[R]^n) M) :
GradedMonoid.mk m (PiTensorProduct.reindex R M (Fin.cast h).toEquiv x) = GradedMonoid.mk n x :=
by rw [Fin.cast_to_equiv, mk_reindex_cast h]
#align tensor_algebra.mk_reindex_fin_cast TensorAlgebra.mk_reindex_fin_cast
/-- The product of tensor products made of a single vector is the same as a single product of
all the vectors. -/
theorem TensorPower.list_prod_gradedMonoid_mk_single (n : ℕ) (x : Fin n → M) :
((List.finRange n).map fun a =>
(GradedMonoid.mk _ (PiTensorProduct.tprod R fun i : Fin 1 => x a) :
GradedMonoid fun n => (⨂[R]^n) M)).Prod =
GradedMonoid.mk n (PiTensorProduct.tprod R x) :=
by
refine' Fin.consInduction _ _ x <;> clear x
· rw [List.finRange_zero, List.map_nil, List.prod_nil]
rfl
· intro n x₀ x ih
rw [List.finRange_succ_eq_map, List.map_cons, List.prod_cons, List.map_map, Function.comp]
simp_rw [Fin.cons_zero, Fin.cons_succ]
rw [ih, GradedMonoid.mk_mul_mk, TensorPower.tprod_mul_tprod]
refine' TensorPower.gradedMonoid_eq_of_cast (add_comm _ _) _
dsimp only [GradedMonoid.mk]
rw [TensorPower.cast_tprod]
simp_rw [Fin.append_left_eq_cons, Function.comp]
congr 1 with i
congr 1
rw [Fin.cast_trans, Fin.cast_refl, OrderIso.refl_apply]
#align tensor_power.list_prod_graded_monoid_mk_single TensorPower.list_prod_gradedMonoid_mk_single
theorem toDirectSum_tensorPower_tprod {n} (x : Fin n → M) :
toDirectSum (tprod R M n x) = DirectSum.of _ n (PiTensorProduct.tprod R x) :=
by
rw [tprod_apply, AlgHom.map_list_prod, List.map_ofFn, Function.comp]
simp_rw [to_direct_sum_ι]
dsimp only
rw [DirectSum.list_prod_ofFn_of_eq_dProd]
apply DirectSum.of_eq_of_gradedMonoid_eq
rw [GradedMonoid.mk_list_dProd]
rw [TensorPower.list_prod_gradedMonoid_mk_single]
#align tensor_algebra.to_direct_sum_tensor_power_tprod TensorAlgebra.toDirectSum_tensorPower_tprod
theorem toDirectSum_comp_ofDirectSum :
toDirectSum.comp ofDirectSum = AlgHom.id R (⨁ n, (⨂[R]^n) M) :=
by
ext
simp [DirectSum.lof_eq_of, -tprod_apply, to_direct_sum_tensor_power_tprod]
#align tensor_algebra.to_direct_sum_comp_of_direct_sum TensorAlgebra.toDirectSum_comp_ofDirectSum
@[simp]
theorem toDirectSum_ofDirectSum (x : ⨁ n, (⨂[R]^n) M) : (ofDirectSum x).toDirectSum = x :=
AlgHom.congr_fun toDirectSum_comp_ofDirectSum x
#align tensor_algebra.to_direct_sum_of_direct_sum TensorAlgebra.toDirectSum_ofDirectSum
/-- The tensor algebra is isomorphic to a direct sum of tensor powers. -/
@[simps]
def equivDirectSum : TensorAlgebra R M ≃ₐ[R] ⨁ n, (⨂[R]^n) M :=
AlgEquiv.ofAlgHom toDirectSum ofDirectSum toDirectSum_comp_ofDirectSum
ofDirectSum_comp_toDirectSum
#align tensor_algebra.equiv_direct_sum TensorAlgebra.equivDirectSum
end TensorAlgebra
|
/* ode-initval/gsl_odeiv.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#ifndef __GSL_ODEIV_H__
#define __GSL_ODEIV_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Description of a system of ODEs.
*
* y' = f(t,y) = dydt(t, y)
*
* The system is specified by giving the right-hand-side
* of the equation and possibly a jacobian function.
*
* Some methods require the jacobian function, which calculates
* the matrix dfdy and the vector dfdt. The matrix dfdy conforms
* to the GSL standard, being a continuous range of floating point
* values, in row-order.
*
* As with GSL function objects, user-supplied parameter
* data is also present.
*/
typedef struct
{
int (* function) (double t, const double y[], double dydt[], void * params);
int (* jacobian) (double t, const double y[], double * dfdy, double dfdt[], void * params);
size_t dimension;
void * params;
}
gsl_odeiv_system;
#define GSL_ODEIV_FN_EVAL(S,t,y,f) (*((S)->function))(t,y,f,(S)->params)
#define GSL_ODEIV_JA_EVAL(S,t,y,dfdy,dfdt) (*((S)->jacobian))(t,y,dfdy,dfdt,(S)->params)
/* General stepper object.
*
* Opaque object for stepping an ODE system from t to t+h.
* In general the object has some state which facilitates
* iterating the stepping operation.
*/
typedef struct
{
const char * name;
int can_use_dydt_in;
int gives_exact_dydt_out;
void * (*alloc) (size_t dim);
int (*apply) (void * state, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * dydt);
int (*reset) (void * state, size_t dim);
unsigned int (*order) (void * state);
void (*free) (void * state);
}
gsl_odeiv_step_type;
typedef struct {
const gsl_odeiv_step_type * type;
size_t dimension;
void * state;
}
gsl_odeiv_step;
/* Available stepper types.
*
* rk2 : embedded 2nd(3rd) Runge-Kutta
* rk4 : 4th order (classical) Runge-Kutta
* rkck : embedded 4th(5th) Runge-Kutta, Cash-Karp
* rk8pd : embedded 8th(9th) Runge-Kutta, Prince-Dormand
* rk2imp : implicit 2nd order Runge-Kutta at Gaussian points
* rk4imp : implicit 4th order Runge-Kutta at Gaussian points
* gear1 : M=1 implicit Gear method
* gear2 : M=2 implicit Gear method
*/
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk4;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rkf45;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rkck;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk8pd;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2imp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2simp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk4imp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_bsimp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_gear1;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_gear2;
/* Constructor for specialized stepper objects.
*/
GSL_FUN gsl_odeiv_step * gsl_odeiv_step_alloc(const gsl_odeiv_step_type * T, size_t dim);
GSL_FUN int gsl_odeiv_step_reset(gsl_odeiv_step * s);
GSL_FUN void gsl_odeiv_step_free(gsl_odeiv_step * s);
/* General stepper object methods.
*/
GSL_FUN const char * gsl_odeiv_step_name(const gsl_odeiv_step * s);
GSL_FUN unsigned int gsl_odeiv_step_order(const gsl_odeiv_step * s);
GSL_FUN int gsl_odeiv_step_apply(gsl_odeiv_step * s, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * dydt);
/* General step size control object.
*
* The hadjust() method controls the adjustment of
* step size given the result of a step and the error.
* Valid hadjust() methods must return one of the codes below.
*
* The general data can be used by specializations
* to store state and control their heuristics.
*/
typedef struct
{
const char * name;
void * (*alloc) (void);
int (*init) (void * state, double eps_abs, double eps_rel, double a_y, double a_dydt);
int (*hadjust) (void * state, size_t dim, unsigned int ord, const double y[], const double yerr[], const double yp[], double * h);
void (*free) (void * state);
}
gsl_odeiv_control_type;
typedef struct
{
const gsl_odeiv_control_type * type;
void * state;
}
gsl_odeiv_control;
/* Possible return values for an hadjust() evolution method.
*/
#define GSL_ODEIV_HADJ_INC 1 /* step was increased */
#define GSL_ODEIV_HADJ_NIL 0 /* step unchanged */
#define GSL_ODEIV_HADJ_DEC (-1) /* step decreased */
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_alloc(const gsl_odeiv_control_type * T);
GSL_FUN int gsl_odeiv_control_init(gsl_odeiv_control * c, double eps_abs, double eps_rel, double a_y, double a_dydt);
GSL_FUN void gsl_odeiv_control_free(gsl_odeiv_control * c);
GSL_FUN int gsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s, const double y[], const double yerr[], const double dydt[], double * h);
GSL_FUN const char * gsl_odeiv_control_name(const gsl_odeiv_control * c);
/* Available control object constructors.
*
* The standard control object is a four parameter heuristic
* defined as follows:
* D0 = eps_abs + eps_rel * (a_y |y| + a_dydt h |y'|)
* D1 = |yerr|
* q = consistency order of method (q=4 for 4(5) embedded RK)
* S = safety factor (0.9 say)
*
* / (D0/D1)^(1/(q+1)) D0 >= D1
* h_NEW = S h_OLD * |
* \ (D0/D1)^(1/q) D0 < D1
*
* This encompasses all the standard error scaling methods.
*
* The y method is the standard method with a_y=1, a_dydt=0.
* The yp method is the standard method with a_y=0, a_dydt=1.
*/
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_standard_new(double eps_abs, double eps_rel, double a_y, double a_dydt);
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_y_new(double eps_abs, double eps_rel);
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_yp_new(double eps_abs, double eps_rel);
/* This controller computes errors using different absolute errors for
* each component
*
* D0 = eps_abs * scale_abs[i] + eps_rel * (a_y |y| + a_dydt h |y'|)
*/
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_scaled_new(double eps_abs, double eps_rel, double a_y, double a_dydt, const double scale_abs[], size_t dim);
/* General evolution object.
*/
typedef struct {
size_t dimension;
double * y0;
double * yerr;
double * dydt_in;
double * dydt_out;
double last_step;
unsigned long int count;
unsigned long int failed_steps;
}
gsl_odeiv_evolve;
/* Evolution object methods.
*/
GSL_FUN gsl_odeiv_evolve * gsl_odeiv_evolve_alloc(size_t dim);
GSL_FUN int gsl_odeiv_evolve_apply(gsl_odeiv_evolve * e, gsl_odeiv_control * con, gsl_odeiv_step * step, const gsl_odeiv_system * dydt, double * t, double t1, double * h, double y[]);
GSL_FUN int gsl_odeiv_evolve_reset(gsl_odeiv_evolve * e);
GSL_FUN void gsl_odeiv_evolve_free(gsl_odeiv_evolve * e);
__END_DECLS
#endif /* __GSL_ODEIV_H__ */
|
[STATEMENT]
lemma res_mult_eq: "x \<otimes> y = (x * y) mod m"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x \<otimes> y = x * y mod m
[PROOF STEP]
by (auto simp: R_m_def residue_ring_def) |
[STATEMENT]
lemma sync_commute: "(P \<lbrakk> A \<rbrakk> Q) = (Q \<lbrakk> A \<rbrakk> P)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (P \<lbrakk>A\<rbrakk> Q) = (Q \<lbrakk>A\<rbrakk> P)
[PROOF STEP]
by (simp add: Process_eq_spec mono_D_syn mono_F_syn) |
theory T91
imports Main
begin
lemma "(
(\<forall> x::nat. \<forall> y::nat. meet(x, y) = meet(y, x)) &
(\<forall> x::nat. \<forall> y::nat. join(x, y) = join(y, x)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, meet(y, z)) = meet(meet(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(x, join(y, z)) = join(join(x, y), z)) &
(\<forall> x::nat. \<forall> y::nat. meet(x, join(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. join(x, meet(x, y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(x, join(y, z)) = join(mult(x, y), mult(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(join(x, y), z) = join(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(x, over(join(mult(x, y), z), y)) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. meet(y, undr(x, join(mult(x, y), z))) = y) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(over(x, y), y), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. join(mult(y, undr(y, x)), x) = x) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. mult(meet(x, y), z) = meet(mult(x, z), mult(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(join(x, y), z) = join(over(x, z), over(y, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. over(x, meet(y, z)) = join(over(x, y), over(x, z))) &
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(meet(x, y), z) = join(undr(x, z), undr(y, z))) &
(\<forall> x::nat. \<forall> y::nat. invo(join(x, y)) = meet(invo(x), invo(y))) &
(\<forall> x::nat. \<forall> y::nat. invo(meet(x, y)) = join(invo(x), invo(y))) &
(\<forall> x::nat. invo(invo(x)) = x)
) \<longrightarrow>
(\<forall> x::nat. \<forall> y::nat. \<forall> z::nat. undr(x, join(y, z)) = join(undr(x, y), undr(x, z)))
"
nitpick[card nat=4,timeout=86400]
oops
end |
lemma arg_unique: assumes "sgn z = cis x" and "-pi < x" and "x \<le> pi" shows "arg z = x" |
{-
This file contains:
- Definition of functions of the equivalence between FreeGroup and the FundamentalGroup
- Definition of encode decode functions
- Proof that for all x : Bouquet A → p : base ≡ x → decode x (encode x p) ≡ p (no truncations)
- Proof of the truncated versions of encodeDecode and of right-homotopy
- Definition of truncated encode decode functions
- Proof of the truncated versions of decodeEncode and encodeDecode
- Proof that π₁Bouquet ≡ FreeGroup A
-}
{-# OPTIONS --safe #-}
module Cubical.HITs.Bouquet.FundamentalGroupProof where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Function
open import Cubical.Foundations.Pointed
open import Cubical.Foundations.Univalence
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.GroupoidLaws renaming (assoc to pathAssoc)
open import Cubical.HITs.SetTruncation hiding (rec2)
open import Cubical.HITs.PropositionalTruncation hiding (map ; elim) renaming (rec to propRec)
open import Cubical.Algebra.Group
open import Cubical.Homotopy.Group.Base
open import Cubical.Homotopy.Loopspace
open import Cubical.HITs.Bouquet.Base
open import Cubical.HITs.FreeGroup.Base
open import Cubical.HITs.FreeGroupoid
private
variable
ℓ : Level
A : Type ℓ
-- Pointed versions of the non truncated types
ΩBouquet : {A : Type ℓ} → Pointed ℓ
ΩBouquet {A = A} = Ω (Bouquet∙ A)
FreeGroupoid∙ : {A : Type ℓ} → Pointed ℓ
FreeGroupoid∙ {A = A} = FreeGroupoid A , ε
-- Functions without using the truncated forms of types
looping : FreeGroupoid A → typ ΩBouquet
looping (η a) = loop a
looping (g1 · g2) = looping g1 ∙ looping g2
looping ε = refl
looping (inv g) = sym (looping g)
looping (assoc g1 g2 g3 i) = pathAssoc (looping g1) (looping g2) (looping g3) i
looping (idr g i) = rUnit (looping g) i
looping (idl g i) = lUnit (looping g) i
looping (invr g i) = rCancel (looping g) i
looping (invl g i) = lCancel (looping g) i
looping∙ : FreeGroupoid∙ →∙ ΩBouquet {A = A}
looping∙ = looping , refl
code : {A : Type ℓ} → (Bouquet A) → Type ℓ
code {A = A} base = (FreeGroupoid A)
code (loop a i) = pathsInU (η a) i
winding : typ ΩBouquet → FreeGroupoid A
winding l = subst code l ε
winding∙ : ΩBouquet →∙ FreeGroupoid∙ {A = A}
winding∙ = winding , refl
-- Functions using the truncated forms of types
π₁Bouquet : {A : Type ℓ} → Type ℓ
π₁Bouquet {A = A} = π 1 (Bouquet∙ A)
loopingT : ∥ FreeGroupoid A ∥₂ → π₁Bouquet
loopingT = map looping
windingT : π₁Bouquet → ∥ FreeGroupoid A ∥₂
windingT = map winding
-- Utility proofs
substPathsR : {C : Type ℓ}{y z : C} → (x : C) → (p : y ≡ z) → subst (λ y → x ≡ y) p ≡ λ q → q ∙ p
substPathsR {y = y} x p = funExt homotopy where
homotopy : ∀ q → subst (λ y → x ≡ y) p q ≡ q ∙ p
homotopy q = J P d p where
P : ∀ z' → y ≡ z' → Type _
P z' p' = subst (λ y → x ≡ y) p' q ≡ q ∙ p'
d : P y refl
d =
subst (λ y → x ≡ y) refl q
≡⟨ substRefl {B = λ y → x ≡ y} q ⟩
q
≡⟨ rUnit q ⟩
q ∙ refl ∎
substFunctions : {B C : A → Type ℓ}{x y : A}
→ (p : x ≡ y)
→ (f : B x → C x)
→ subst (λ z → (B z → C z)) p f ≡ subst C p ∘ f ∘ subst B (sym p)
substFunctions {B = B} {C = C} {x = x} p f = J P d p where
auxC : idfun (C x) ≡ subst C refl
auxC = funExt (λ c → sym (substRefl {B = C} c))
auxB : idfun (B x) ≡ subst B refl
auxB = funExt (λ b → sym (substRefl {B = B} b))
P : ∀ y' → x ≡ y' → Type _
P y' p' = subst (λ z → (B z → C z)) p' f ≡ subst C p' ∘ f ∘ subst B (sym p')
d : P x refl
d =
subst (λ z → (B z → C z)) refl f
≡⟨ substRefl {B = λ z → (B z → C z)} f ⟩
f
≡⟨ cong (λ h → h ∘ f ∘ idfun (B x)) auxC ⟩
subst C refl ∘ f ∘ idfun (B x)
≡⟨ cong (λ h → subst C refl ∘ f ∘ h) auxB ⟩
subst C refl ∘ f ∘ subst B (sym refl) ∎
-- Definition of the encode - decode functions over the family of types Π(x : W A) → code x
encode : (x : Bouquet A) → base ≡ x → code x
encode x l = subst code l ε
decode : {A : Type ℓ}(x : Bouquet A) → code x → base ≡ x
decode {A = A} base = looping
decode {A = A} (loop a i) = path i where
pathover : PathP (λ i → (code (loop a i) → base ≡ (loop a i))) looping (subst (λ z → (code z → base ≡ z)) (loop a) looping)
pathover = subst-filler (λ z → (code z → base ≡ z)) (loop a) looping
aux : (a : A) → subst code (sym (loop a)) ≡ action (inv (η a))
aux a = funExt homotopy where
homotopy : ∀ (g : FreeGroupoid A) → subst code (sym (loop a)) g ≡ action (inv (η a)) g
homotopy g =
subst code (sym (loop a)) g
≡⟨ cong (λ x → transport x g) (sym (invPathsInUNaturality (η a))) ⟩
transport (pathsInU (inv (η a))) g
≡⟨ uaβ (equivs (inv (η a))) g ⟩
action (inv (η a)) g ∎
calculations : ∀ (a : A) → ∀ g → looping (g · (inv (η a))) ∙ loop a ≡ looping g
calculations a g =
looping (g · (inv (η a))) ∙ loop a
≡⟨ sym (pathAssoc (looping g) (sym (loop a)) (loop a)) ⟩
looping g ∙ (sym (loop a) ∙ loop a)
≡⟨ cong (λ x → looping g ∙ x) (lCancel (loop a)) ⟩
looping g ∙ refl
≡⟨ sym (rUnit (looping g)) ⟩
looping g ∎
path' : subst (λ z → (code z → base ≡ z)) (loop a) looping ≡ looping
path' =
subst (λ z → (code z → base ≡ z)) (loop a) looping
≡⟨ substFunctions {B = code} {C = λ z → base ≡ z} (loop a) looping ⟩
subst (λ z → base ≡ z) (loop a) ∘ looping ∘ subst code (sym (loop a))
≡⟨ cong (λ x → x ∘ looping ∘ subst code (sym (loop a))) (substPathsR base (loop a)) ⟩
(λ p → p ∙ loop a) ∘ looping ∘ subst code (sym (loop a))
≡⟨ cong (λ x → (λ p → p ∙ loop a) ∘ looping ∘ x) (aux a) ⟩
(λ p → p ∙ loop a) ∘ looping ∘ action (inv (η a))
≡⟨ funExt (calculations a) ⟩
looping ∎
path'' : PathP (λ i → code ((loop a ∙ refl) i) → base ≡ ((loop a ∙ refl) i)) looping looping
path'' = compPathP' {A = Bouquet A} {B = λ z → code z → base ≡ z} pathover path'
p''≡p : PathP (λ i → code ((loop a ∙ refl) i) → base ≡ ((loop a ∙ refl) i)) looping looping ≡
PathP (λ i → code (loop a i) → base ≡ (loop a i)) looping looping
p''≡p = cong (λ x → PathP (λ i → code (x i) → base ≡ (x i)) looping looping) (sym (rUnit (loop a)))
path : PathP (λ i → code (loop a i) → base ≡ (loop a i)) looping looping
path = transport p''≡p path''
-- Non truncated Left Homotopy
decodeEncode : (x : Bouquet A) → (p : base ≡ x) → decode x (encode x p) ≡ p
decodeEncode x p = J P d p where
P : (x' : Bouquet A) → base ≡ x' → Type _
P x' p' = decode x' (encode x' p') ≡ p'
d : P base refl
d =
decode base (encode base refl)
≡⟨ cong (λ e' → looping e') (transportRefl ε) ⟩
refl ∎
left-homotopy : ∀ (l : typ (ΩBouquet {A = A})) → looping (winding l) ≡ l
left-homotopy l = decodeEncode base l
-- Truncated proofs of right homotopy of winding/looping functions
truncatedPathEquality : (g : FreeGroupoid A) → ∥ cong code (looping g) ≡ ua (equivs g) ∥₁
truncatedPathEquality = elimProp
Bprop
(λ a → ∣ η-ind a ∣₁)
(λ g1 g2 → λ ∣ind1∣₁ ∣ind2∣₁ → rec2 squash₁ (λ ind1 ind2 → ∣ ·-ind g1 g2 ind1 ind2 ∣₁) ∣ind1∣₁ ∣ind2∣₁)
∣ ε-ind ∣₁
(λ g → λ ∣ind∣₁ → propRec squash₁ (λ ind → ∣ inv-ind g ind ∣₁) ∣ind∣₁) where
B : ∀ g → Type _
B g = cong code (looping g) ≡ ua (equivs g)
Bprop : ∀ g → isProp ∥ B g ∥₁
Bprop g = squash₁
η-ind : ∀ a → B (η a)
η-ind a = refl
·-ind : ∀ g1 g2 → B g1 → B g2 → B (g1 · g2)
·-ind g1 g2 ind1 ind2 =
cong code (looping (g1 · g2))
≡⟨ cong (λ x → x ∙ cong code (looping g2)) ind1 ⟩
pathsInU g1 ∙ cong code (looping g2)
≡⟨ cong (λ x → pathsInU g1 ∙ x) ind2 ⟩
pathsInU g1 ∙ pathsInU g2
≡⟨ sym (multPathsInUNaturality g1 g2) ⟩
pathsInU (g1 · g2) ∎
ε-ind : B ε
ε-ind =
cong code (looping ε)
≡⟨ sym idPathsInUNaturality ⟩
pathsInU ε ∎
inv-ind : ∀ g → B g → B (inv g)
inv-ind g ind =
cong code (looping (inv g))
≡⟨ cong sym ind ⟩
sym (pathsInU g)
≡⟨ sym (invPathsInUNaturality g) ⟩
ua (equivs (inv g)) ∎
truncatedRight-homotopy : (g : FreeGroupoid A) → ∥ winding (looping g) ≡ g ∥₁
truncatedRight-homotopy g = propRec squash₁ recursion (truncatedPathEquality g) where
recursion : cong code (looping g) ≡ ua (equivs g) → ∥ winding (looping g) ≡ g ∥₁
recursion hyp = ∣ aux ∣₁ where
aux : winding (looping g) ≡ g
aux =
winding (looping g)
≡⟨ cong (λ x → transport x ε) hyp ⟩
transport (ua (equivs g)) ε
≡⟨ uaβ (equivs g) ε ⟩
ε · g
≡⟨ sym (idl g) ⟩
g ∎
right-homotopyInTruncatedGroupoid : (g : FreeGroupoid A) → ∣ winding (looping g) ∣₂ ≡ ∣ g ∣₂
right-homotopyInTruncatedGroupoid g = Iso.inv PathIdTrunc₀Iso (truncatedRight-homotopy g)
-- Truncated encodeDecode over all fibrations
truncatedEncodeDecode : (x : Bouquet A) → (g : code x) → ∥ encode x (decode x g) ≡ g ∥₁
truncatedEncodeDecode base = truncatedRight-homotopy
truncatedEncodeDecode (loop a i) = isProp→PathP prop truncatedRight-homotopy truncatedRight-homotopy i where
prop : ∀ i → isProp (∀ (g : code (loop a i)) → ∥ encode (loop a i) (decode (loop a i) g) ≡ g ∥₁)
prop i f g = funExt pointwise where
pointwise : (x : code (loop a i)) → PathP (λ _ → ∥ encode (loop a i) (decode (loop a i) x) ≡ x ∥₁) (f x) (g x)
pointwise x = isProp→PathP (λ i → squash₁) (f x) (g x)
encodeDecodeInTruncatedGroupoid : (x : Bouquet A) → (g : code x) → ∣ encode x (decode x g) ∣₂ ≡ ∣ g ∣₂
encodeDecodeInTruncatedGroupoid x g = Iso.inv PathIdTrunc₀Iso (truncatedEncodeDecode x g)
-- Encode Decode over the truncated versions of the types
encodeT : (x : Bouquet A) → ∥ base ≡ x ∥₂ → ∥ code x ∥₂
encodeT x = map (encode x)
decodeT : (x : Bouquet A) → ∥ code x ∥₂ → ∥ base ≡ x ∥₂
decodeT x = map (decode x)
decodeEncodeT : (x : Bouquet A) → (p : ∥ base ≡ x ∥₂) → decodeT x (encodeT x p) ≡ p
decodeEncodeT x g = elim sethood induction g where
sethood : (q : ∥ base ≡ x ∥₂) → isSet (decodeT x (encodeT x q) ≡ q)
sethood q = isProp→isSet (squash₂ (decodeT x (encodeT x q)) q)
induction : (l : base ≡ x) → ∣ decode x (encode x l) ∣₂ ≡ ∣ l ∣₂
induction l = cong (λ l' → ∣ l' ∣₂) (decodeEncode x l)
encodeDecodeT : (x : Bouquet A) → (g : ∥ code x ∥₂) → encodeT x (decodeT x g) ≡ g
encodeDecodeT x g = elim sethood induction g where
sethood : (z : ∥ code x ∥₂) → isSet (encodeT x (decodeT x z) ≡ z)
sethood z = isProp→isSet (squash₂ (encodeT x (decodeT x z)) z)
induction : (a : code x) → ∣ encode x (decode x a) ∣₂ ≡ ∣ a ∣₂
induction a = encodeDecodeInTruncatedGroupoid x a
-- Final equivalences
TruncatedFamiliesIso : (x : Bouquet A) → Iso ∥ base ≡ x ∥₂ ∥ code x ∥₂
Iso.fun (TruncatedFamiliesIso x) = encodeT x
Iso.inv (TruncatedFamiliesIso x) = decodeT x
Iso.rightInv (TruncatedFamiliesIso x) = encodeDecodeT x
Iso.leftInv (TruncatedFamiliesIso x) = decodeEncodeT x
TruncatedFamiliesEquiv : (x : Bouquet A) → ∥ base ≡ x ∥₂ ≃ ∥ code x ∥₂
TruncatedFamiliesEquiv x = isoToEquiv (TruncatedFamiliesIso x)
TruncatedFamilies≡ : (x : Bouquet A) → ∥ base ≡ x ∥₂ ≡ ∥ code x ∥₂
TruncatedFamilies≡ x = ua (TruncatedFamiliesEquiv x)
π₁Bouquet≡∥FreeGroupoid∥₂ : π₁Bouquet ≡ ∥ FreeGroupoid A ∥₂
π₁Bouquet≡∥FreeGroupoid∥₂ = TruncatedFamilies≡ base
π₁Bouquet≡FreeGroup : {A : Type ℓ} → π₁Bouquet ≡ FreeGroup A
π₁Bouquet≡FreeGroup {A = A} =
π₁Bouquet
≡⟨ π₁Bouquet≡∥FreeGroupoid∥₂ ⟩
∥ FreeGroupoid A ∥₂
≡⟨ sym freeGroupTruncIdempotent ⟩
FreeGroup A ∎
|
State Before: F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
⊢ sup (s ×ˢ t) f = sup s fun i => sup t fun i' => f (i, i') State After: F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
⊢ (∀ (a : β) (b : γ), a ∈ s → b ∈ t → f (a, b) ≤ sup s fun i => sup t fun i' => f (i, i')) ∧
∀ (b : β), b ∈ s → ∀ (b_1 : γ), b_1 ∈ t → f (b, b_1) ≤ sup (s ×ˢ t) f Tactic: simp only [le_antisymm_iff, Finset.sup_le_iff, mem_product, and_imp, Prod.forall] State Before: F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
⊢ (∀ (a : β) (b : γ), a ∈ s → b ∈ t → f (a, b) ≤ sup s fun i => sup t fun i' => f (i, i')) ∧
∀ (b : β), b ∈ s → ∀ (b_1 : γ), b_1 ∈ t → f (b, b_1) ≤ sup (s ×ˢ t) f State After: case refine_1
F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
b : β
c : γ
hb : b ∈ s
hc : c ∈ t
⊢ f (b, c) ≤ sup s fun i => sup t fun i' => f (i, i')
case refine_2
F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
b : β
hb : b ∈ s
c : γ
hc : c ∈ t
⊢ f (b, c) ≤ sup (s ×ˢ t) f Tactic: refine ⟨fun b c hb hc => ?_, fun b hb c hc => ?_⟩ State Before: case refine_1
F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
b : β
c : γ
hb : b ∈ s
hc : c ∈ t
⊢ f (b, c) ≤ sup s fun i => sup t fun i' => f (i, i') State After: case refine_1
F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
b : β
c : γ
hb : b ∈ s
hc : c ∈ t
⊢ f (b, c) ≤ sup t fun i' => f (b, i') Tactic: refine (le_sup hb).trans' ?_ State Before: case refine_1
F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
b : β
c : γ
hb : b ∈ s
hc : c ∈ t
⊢ f (b, c) ≤ sup t fun i' => f (b, i') State After: no goals Tactic: exact @le_sup _ _ _ _ _ (fun c => f (b, c)) c hc State Before: case refine_2
F : Type ?u.55319
α : Type u_3
β : Type u_1
γ : Type u_2
ι : Type ?u.55331
κ : Type ?u.55334
inst✝¹ : SemilatticeSup α
inst✝ : OrderBot α
s✝ s₁ s₂ : Finset β
f✝ g : β → α
a : α
s : Finset β
t : Finset γ
f : β × γ → α
b : β
hb : b ∈ s
c : γ
hc : c ∈ t
⊢ f (b, c) ≤ sup (s ×ˢ t) f State After: no goals Tactic: exact le_sup <| mem_product.2 ⟨hb, hc⟩ |
-- {-# OPTIONS -v tc.conv:10 #-}
-- 2013-11-03 Reported by sanzhiyan
module Issue933 where
record RGraph : Set₁ where
field
O : Set
R : Set
refl : O -> R
module Families (Γ : RGraph) where
module Γ = RGraph Γ
record RG-Fam : Set₁ where
field
O : Γ.O -> Set
refl : ∀ {γo} -> (o : O γo) → O (Γ.refl γo)
-- "O (Γ.refl γo)" should be a type error.
-- Andreas: Fixed. SyntacticEquality wrongly just skipped projections.
|
{-# OPTIONS --without-K --safe #-}
open import Categories.Category.Core
open import Categories.Object.Zero
-- Normal Mono and Epimorphisms
-- https://ncatlab.org/nlab/show/normal+monomorphism
module Categories.Morphism.Normal {o ℓ e} (𝒞 : Category o ℓ e) (𝒞-Zero : Zero 𝒞) where
open import Level
open import Categories.Object.Kernel 𝒞-Zero
open import Categories.Object.Kernel.Properties 𝒞-Zero
open import Categories.Morphism 𝒞
open Category 𝒞
record IsNormalMonomorphism {A K : Obj} (k : K ⇒ A) : Set (o ⊔ ℓ ⊔ e) where
field
{B} : Obj
arr : A ⇒ B
isKernel : IsKernel k arr
open IsKernel isKernel public
mono : Mono k
mono = Kernel-Mono (IsKernel⇒Kernel isKernel)
record NormalMonomorphism (K A : Obj) : Set (o ⊔ ℓ ⊔ e) where
field
mor : K ⇒ A
isNormalMonomorphism : IsNormalMonomorphism mor
open IsNormalMonomorphism isNormalMonomorphism public
|
lemma hol_pal_lem1: assumes "convex S" "open S" and abc: "a \<in> S" "b \<in> S" "c \<in> S" "d \<noteq> 0" and lek: "d \<bullet> a \<le> k" "d \<bullet> b \<le> k" "d \<bullet> c \<le> k" and holf1: "f holomorphic_on {z. z \<in> S \<and> d \<bullet> z < k}" and contf: "continuous_on S f" shows "contour_integral (linepath a b) f + contour_integral (linepath b c) f + contour_integral (linepath c a) f = 0" |
# <span style='font-family:Marker Felt;font-weight:bold'>LINEAR MODELS FOR REGRESSION</span>
---
In this chapter we start to learn some fundamental algorithms behind the most common and simple machine learning tools. To do it, we will use some simple mathematic equations that require basic knowledge of statistics and probability.
<p align="center">
</p>
## <span style='font-family:Marker Felt;font-weight:bold'>Linear models</span>
---
The goal of a regression problem is to learn a mapping from a given $D$-dimensional vector **x** of input variables to one or more continuous target variables **t**. Some examples of regression problems are the prediction of a stock market price, the prediction of future emissions of $CO_2$, the effect of an actuation in robotics and so on.
The simplest form of regression is given by **linear models** which are models linear in their weights, not necessarily in the inputs. The advantages of these models are many:
* Can be solved analytically. This means, as you will see later, that the associated optimization problem can be solved in _closed form_. We will always obtain the minimum of the approximation loss on the data we have. If the model fails to properly approximate the phenomenon then the problem is for sure related to the hypothesis space, so on the model we are using.
* They are the core concepts of more complex machine learning algorithms.
* Their approximation capability is not limited to linear function: they can approximate any complex function provided the correct input space is considered.
The simplest linear model, is obviously, the one that involves a linear combination of the input variables:
\begin{align}
y(\textbf{x}, \textbf{w}) = w_0 + \sum_{j=1}^{D-1}w_j x_j = \textbf{w}^T\textbf{x}
\end{align}
where $w_0$ is nothing but the offset of the model at zero.
### <span style='font-family:Marker Felt;font-weight:bold'>Loss function</span>
How can we state if this model is sufficiently accurate for our system? We need to define a loss function, also called the _error function_. Generally speaking a loss function can be defined as:
$$
\begin{align}\mathbb{E}[\mathcal{L}] = \int\int L(t, y(\textbf{x}))p(\textbf{x},t)d\textbf{x} dt
\end{align}
$$
where $p(\textbf{x}, t)$ represents the probability to see that particular combination of input and output; this probability acts as a weight on the loss. Since the distribution of this probability is unknown we have to estimate it with the data points we have.
In regression, a common choice of loss function is the **squared loss function**:
$$
\begin{align}
\mathbb{E}[\mathcal{L}] = \int\int (t - y(\textbf{x}))^2 p(\textbf{x},t)d\textbf{x}dt
\end{align}
$$
Deriving this loss function w.r.t. $y$ and setting the derivative to zero we obtain that the optimal solution is the conditional mean of $t$ conditioned on $\textbf{x}$, also called *regression function*:
$$
\begin{align}
y(\textbf{x}) = \int t p(t|\textbf{x})dt = \mathbb{E}[t|\textbf{x}]
\end{align}
$$
<p align="center">
</p>
There are situations in which the squared loss function doesn't produce any good result, as in the case where $p(t|\textbf{x})$ is multi-modal. The generalization of the squared loss is the *Minkowski loss* defined as:
$$
\begin{align}
\mathbb{E}[\mathcal{L}] = \int\int (t - y(\textbf{x}))^q p(\textbf{x},t)d\textbf{x}dt
\end{align}
$$
Up to now we have only looked at linear functions of weights and inputs. In order to approximate more complex non-linear functions we can use *non-linear basis functions*. In this way the model still remains linear in the weights but it will be non linear in the input features.
$$
\begin{align}
y(\textbf{x}, \textbf{w}) = w_0 + \sum_{j=1}^{M-1}w_j\phi_j(\textbf{x}) = \textbf{w}^T \bf{\phi}(x)
\end{align}
$$
Thanks to $\bf{\phi}$ we transform the original input space into another one. By using nonlinear basis functions, we allow the function $y(\textbf{x}, \textbf{w})$ to be a nonlinear function of the input vector. In this way we can exploit also our domain knowledge by providing a specific transformation of the inputs.
Some examples of basis functions are:
* Polynomial
* Gaussian
* Sigmoidal
* Fourier basis
The pictures below show the Gaussian basis functions and the Sigmoid ones.
<p align="center">
</p>
<div class="alert alert-block alert-info">
<span style='color:DodgerBlue;font-weight:bold'>REGRESSION APPROACHES</span>
<span style='font-style:italic;font-weight:bold'>Generative</span>: these are the models that explicitly model the distribution of the inputs as well as the outputs. Probabilistically speaking they model also $p(\textbf{x},t)$
<span style='font-style:italic;font-weight:bold'>Discriminative</span>: they directly model the posterior probability $p(t|\textbf{x})$.
<span style='font-style:italic;font-weight:bold'>Direct</span>: they directly find a mapping function from each input to the output
</span>
</div>
## <span style='font-family:Marker Felt;font-weight:bold'>Minimizing Least Squares</span>
---
Let's consider a data set of inputs $\textbf{X}=\{\textbf{x}_1,...,\textbf{x}_N\}$ with the associated target values $t_1,...,t_N$. The error function is defined as the *sum of squared estimate of errors (SSE)*:
$$
\begin{align}
SSE(\textbf{w}) = \mathcal{L}(\textbf{w}) = \frac{1}{2} \sum_{n=1}^N(y(\textbf{x}_n, \textbf{w}) - t_n)^2
\end{align}
$$
The loss can also be written in terms of the $l_2$ norm of the residual errors, known as *residual sum of squares (RSS)*:
$$
\begin{align}
RSS(\textbf{w}) = \left\lVert \epsilon \right\rVert ^2_2 = \sum^N_{n=1} \epsilon_n^2
\end{align}
$$
Note that if we have an high number $N$ of samples the approximation will be very good otherwise, if $N$ is small, the loss will be very noisy. This is because, without the knowledge of $p(\textbf x, t)$ we have to approximate it with a finite number of points and, higher is the number of points and better is the approximation.
In matrix form the RSS becomes:
$$
\begin{align}
\mathcal{L}(\textbf{w}) = \frac{1}{2}(\textbf{t} - \bf{\Phi}\textbf{w})^T(\textbf{t} - \bf{\Phi}\textbf{w}
\end{align}
$$
where:
$$
\begin{align}
\bf{\Phi} = (\phi(\textbf{x}_1), ...,\phi(\textbf{x}_N))^T
\end{align}
$$
To obtain the minimum of the loss we calculate its the first and the second derivatives w.r.t. the weights:
$$
\begin{align}
\frac{\partial \mathcal{L}(\textbf{w})}{\partial \textbf{w}} = -\bf{\Phi}^T(\textbf{t} - \bf{\Phi}\textbf{w})
\end{align}
$$
$$
\begin{align}
\frac{\partial^2 \mathcal{L}(\textbf{w})}{\partial \textbf{w}\partial \textbf{w}} = \bf{\Phi}^T\bf{\Phi}
\end{align}
$$
Providing that the Gram matrix (or Gramian matrix, or *Gramian*) $\bf{\Phi}^T\bf{\Phi}$ is nonsingular, the solution of the *ordinary least squares (OLS)* is:
$$
\begin{align}
\hat{\textbf{w}}_{OLS} = (\bf{\Phi}^T\bf{\Phi})^{-1}\bf{\Phi}^T\textbf{t}
\end{align}
$$
This set of equations are known as *normal equations* for the least squares problem. The inversion of the Gram matrix can be performed with Singular Values Decomposition (SVD) at the complexity cost of $\mathcal{O}(NM^2 + M^3)$, where $M$ is the number of features.
### <span style='font-family:Marker Felt;font-weight:bold'>Sequential learning</span>
Batch techniques can be computationally expensive when dealing with big data. In order to solve this problem we can rely on sequential algorithms, also known as *online algorithms*. This type of updates are also helpful for real-time applications where the data arrives in a continuous stream. Since the total loss can be expressed as the sum of the loss in each data point we can update the parameters with **stochastic gradient descent (SGD)** as follow:
$$
\begin{align}
\textbf{w}^{k+1} = \textbf{w}^{k} - \alpha^{k+1}\nabla\mathcal{L}(x_n)
\end{align}
$$
where k represents the iteration number and $\alpha$ is called the learning rate. The value of $\alpha$ needs to satisfy certain conditions for convergence:
$$
\begin{align}
\sum^{\infty}_{k=0}\alpha^k = + \infty
\end{align}
$$
$$
\begin{align}
\sum^{\infty}_{k=0}(\alpha^k)^2 < + \infty
\end{align}
$$
### <span style='font-family:Marker Felt;font-weight:bold'>Geometric interpretation</span>
Let's consider an $N$-dimensional space which axes are given by the $t_n$. Each basis function can also be represented as a vector in the same space. Define $\varphi_j$ the $j^{th}$ column of $\Phi$. If the number $M$ of basis functions is smaller than the number $N$ of data points, then the $\varphi_j$ will span just a linear subspace of dimensionality $M$. Since $\textbf{y}$ is defined as a linear combination of the vectors $\varphi_j$ it lives in the same space of dimension $M$. The least squares solution for $\textbf{w}$ corresponds to the solution $\hat{\textbf t}$ ($\textbf{y}$ in the picture below) that is closest to $\textbf{t}$ in the subspace.
$$
\begin{align}
\hat{\textbf{t}} = \bf{\Phi}\hat{\textbf{w}} = \bf{\Phi}(\bf{\Phi}^T\bf{\Phi})^{-1}\bf{\Phi}^T \textbf{t}
\end{align}
$$
The solution corresponds to the projection of $\textbf{t}$ in the subspace of dimensionality $M$ through a projection matrix called the *hat matrix*:
$$
\begin{align}
H = \bf{\Phi}(\bf{\Phi}^T\bf{\Phi})^{-1}\bf{\Phi}^T
\end{align}
$$
<p align="center">
</p>
### <span style='font-family:Marker Felt;font-weight:bold'>Maximum likelihood</span>
Let's consider the relationship between the least squares approach and the maximum likelihood approach. We assume that the target $t$ is in a deterministic relationship with $\textbf{x}$ and $\textbf{w}$ contaminated with additive noise:
$$
\begin{align}
t = y(\textbf{x},\textbf{w}) + \epsilon
\end{align}
$$
We assume a Gaussian model for the noise function $\epsilon \sim \mathcal{N}(0, \sigma^2) = \mathcal{N}(0, \beta^{-1}) $
where $\sigma^2$ is the variance and $\beta$ is the precision. Given N samples independent and identically distributed (iid) we can write the *likelihood function* <a name="likelihood"></a>:
$$
\begin{align}
p(\textbf{t}|\textbf{X},\textbf{w},\sigma^2) = \prod^N_{n=1}\mathcal{N}(t_n|\textbf{w}^T\phi(\textbf{x}_n), \sigma^2)
\end{align}
$$
<div class="alert alert-block alert-warning">
<b>NOTE:</b> $$ \begin{align} \mathcal{N}(x| \mu, \sigma^2) = \frac{1}{(2 \pi \sigma)^{1/2}} \exp\Big\{-\frac{1}{2\sigma^2}(x- \mu)^2\Big\} \end{align} $$
</div>
Taking the logarithm of the likelihood function:
$$
\begin{align}
\ell(\textbf{w}) = \ln p(\textbf{t}|\textbf{X},\textbf{w},\sigma^2) = \sum^N_{n=1}\ln p(t_n|\textbf{w},\textbf{x}_n, \sigma^2) \\ =-
\frac{N}{2}\log (2 \pi \sigma^2) -\frac{1}{2 \sigma^2} RSS(\textbf{w})
\end{align}
$$
To find the maximum likelihood we just have to set to zero the derivative of the likelihood w.r.t. the weights:
$$
\begin{align}
\nabla \ell(\textbf{w}) = \sum^N_{n=1}t_n \phi(\textbf{x}_n)^T - \textbf{w}^T \sum^N_{n=1} \phi(\textbf{x}_n) \phi(\textbf{x}_n)^T = 0
\end{align}
$$
from which we obtain the *maximum likelihood* of the weights:
$$
\begin{align}
\textbf{w}_{ML} = (\bf{\Phi}^T \bf{\Phi})^{-1} \bf{\Phi}^T \textbf{t}
\end{align}
$$
Notice that the maximum likelihood values of the parameters don't depend on the variance of the additive noise.
Assuming that the observation $t_i$ are uncorrelated and with constant variance $\sigma^2$ and that the $x_i$ are non random, the variance of the least squares estimate is:
$$
\begin{align}
Var(\hat{ \textbf{w} }_{OLS}) = (\bf{\Phi}^T \bf{\Phi})^{-1} \sigma^2
\end{align}
$$
We can notice that the value of the variance decreases as the eigenvalues of $(\bf{\Phi}^T \bf{\Phi})$ increase. The inverse produces low values when the eigenvalues of $\bf{\Phi}^T \bf{\Phi} $ are high so when the features are linearly independent and the number of samples is high.
<div class="alert alert-block alert-warning">
<b>NOTE:</b> $$ \begin{align} A = diag(\lambda_i) \rightarrow A^{-1} = diag(\lambda_i^{-1}) \end{align} $$
</div>
Usually the variance is estimated as:
$$
\begin{align}
\hat{\sigma}^2 = \frac{1}{N-M-1} \sum^N_{n=1}(t_n - \hat{\textbf{w}}^T \phi(\textbf{x}_n))^2
\end{align}
$$
So, we obtain that:
$$
\begin{align}
\hat{\textbf{w}} \sim \mathcal{N}(\textbf{w}, (\bf{\Phi}^T \bf{\Phi})^{-1} \sigma^2)
\end{align}
$$
<div class="alert alert-block alert-info">
<span style='color:DodgerBlue;font-weight:bold'>GAUSS-MARKOV THEOREM</span>
*The least squares estimate of $\textbf{w}$ has the smallest variance among all linear unbiased estimates.*
</div>
This theorem tells us that the least squares estimator has the lowest Mean Squared Error (MSE) among all the linear estimators with no bias. However, there may exists a biased estimator with smaller MSE. *An unbiased estimator is not always the best choice.*
### <span style='font-family:Marker Felt;font-weight:bold'>Multiple outputs</span>
Let's now consider the case of multiple outputs. In this case we have the possibility to use different sets of basis functions for each output, obtaining different and independent regression problems. However, the most common approach is to use the same set of basis functions to model all the components of the target vector.
$$
\begin{align}
\textbf{y(x,w)} = \textbf{W}^T\phi(\textbf{x})
\end{align}
$$
where $\textbf{y}$ is a $K$-dimensional column vector, $\textbf{W}$ is an $M \times K$ matrix and $\phi(\textbf{x})$ is an $M$-dimensional column vector.
With the same procedure seen before, the maximum likelihood approach, we obtain the values of the parameters:
$$
\begin{align}
\hat{\textbf{W}}_{ML} = (\bf{\Phi}^T \bf{\Phi})^{-1} \bf{\Phi}^T \textbf{T}
\end{align}
$$
For each output $t_k$ we have:
$$
\begin{align}
\hat{\textbf{w}}_{k} = (\bf{\Phi}^T \bf{\Phi})^{-1} \bf{\Phi}^T \textbf{t}_k = \bf{\Phi}^{\dagger} \textbf{t}_k
\end{align}
$$
where $\bf{\Phi}^{\dagger}$ is called the *Moore-Penrose pseudo-inverse* and needs to be computed only once.
## <span style='font-family:Marker Felt;font-weight:bold'>Regularization</span>
---
In order to have a clear idea of what is and why we need regularization the best way is considering an example: the polynomial curve fitting. Let's consider the function $sin(2 \pi x)$ and draw 10 samples of this function with random noise included. Now we want to fit these points with a polynomial function of the form:
$$y(x, \textbf{w}) = w_0 + w_1 x + ... + w_M x^M = \sum_{j=0}^M w_j x^j $$
$M$ represents the order of the polynomial. For various values of $M$ we obtain different fitting of the data points:
<p align="center">
</p>
The problem is choosing the value of M: this is a very important concept called **model selection**. With a low order polynomial what we obtain is an **underfitting** of the data while, with an high order polynomial, we obtain an **overfitting**. In this last case the model starts to learn the *idiosyncratic* noise of the data set at hand.
* <span style='color:SlateBlue;font-style:italic;font-weight:bold'> Overfitting: </span>the model is too strong and learn the position of the data points inside the training set without discovering the underlying function.
* <span style='color:SlateBlue;font-style:italic;font-weight:bold'> Underfitting: </span>the model is too weak and is not able to approximate well the points inside the training set.
Since the objective of regression, and in general of ML, is the generalization to unseen samples we need a model in the middle of the two extremes. In order to evaluate the overfitting we generate another set composed by $100$ samples, taken from the same distribution of the $10$ samples generate before. To have some quantitative insight into the generalization performance we evaluate the loss both on the initial data set, called *training set*, and also on the new one, called *test set*. In this case we evaluate the Root Mean Square (RMS) error since it allows to account for the difference in size of the two bunch of points.
$$
\begin{align}
E_{RMS} = \sqrt{\frac{2 \cdot RSS}{N}}
\end{align}
$$
<p align="center">
</p>
The *test set error* is a measure of how well the model will behave on unseen samples. We can see from the above pictures that for $M=9$ the train error goes to zero but the error on the test set increases considerably.
<p align="center">
</p>
This is because as $M$ increases the magnitude of the coefficients gets larger, producing wiggling curves. Wiggling curves can be perfectly tuned to pass through all the points of the training set, as in the case of $M=9$, but that's not we want. We know that the points used to optimize the coefficient derive from a function soiled with noise so, we prefer a function that does not interpolate precisely the training points encouraging a smoother interpolation. Below are reported the values of the parameters for various order of the polynomial model.
<p align="center">
</p>
One possibility to overcome overfitting problems is to introduce a regularization term inside the loss function which prevents the coefficients to reach too high values.
### <span style='font-family:Marker Felt;font-weight:bold'>Ridge regression</span>
In ridge regression the loss is modified as follows:
$$
\begin{align}
\mathcal{L}(\textbf{w}) &= \frac{1}{2} \sum_{n=1}^N(y(\textbf{x}_n, \textbf{w}) - t_n)^2 + \frac{\lambda}{2} \left\lVert \textbf{w} \right\rVert_2^2 = \\ &= \mathcal{L}_D(\textbf{w}) + \lambda \mathcal{L}_W(\textbf{w})
\end{align}
$$
where the first term is nothing but the standard RSS while the second term affects the complexity of the model. In ML this choice of regularizer is known as *weights decay*. In statistics this is an example of *parameters shrinkage* since it shrinks the parameter values toward zero. We see that the magnitude of the weights enter directly in the loss function, since we want to minimize the loss we need to converge to a solution with small values of $\textbf w$.
The advantage of this technique is that the loss function remains quadratic on the weights and a closed form solution is possible:
$$
\begin{align}
\textbf w = (\lambda \textbf I + \bf \Phi ^T \bf \Phi)^{-1} \bf \Phi^T \textbf t
\end{align}
$$
The effect of $\lambda$ is to virtually reduce the hypothesis space. In this case the matrix is always invertible if the regularization term is not null and it gives a lowerbound on the eigenvalues. We can have two cases:
* $\lambda=0$: we have the OLS which is unbiased but has high variance
* $\lambda \ne 0$: we introduce a bias but the variance is reduced
It is important to remark that the bias is necessary when we don't have enough data in order to prevent from overfitting. We can see from the pictures below that as $\lambda$ increases the shape of the approximating function becomes smoother.
<p align="center">
</p>
We can quantify the effect of the regularization by looking at the loss on the train and on the test set.
<p align="center">
</p>
### <span style='font-family:Marker Felt;font-weight:bold'>Lasso regression</span>
Lasso is another popular technique in which the loss is modified as:
$$
\begin{align}
\mathcal{L}(\textbf{w}) = \frac{1}{2} \sum_{n=1}^N(y(\textbf{x}_n, \textbf{w}) - t_n)^2 + \frac{\lambda}{2} \left\lVert \textbf{w} \right\rVert_1
\end{align}
$$
The important effect of Lasso is that if $\lambda$ is sufficiently large some parameters goes to zero producing a sparse model (easier to interpret) and can be used also for features selection. We can see this by thinking that the Lasso method can be seen as an unregularized minimization problem subjected to the constraint:
$$
\begin{align}
\sum^M_{j=1} \left\lVert w_j \right\rVert < \eta
\end{align}
$$
The origin of the sparsity of Lasso can be better understand by looking at the following pictures
<p align="center">
</p>
The red circles are the isolines of the unregularized loss function while the light blue parts are the regions of the weights-space that satisfy the constraints.
In the Ridge regression technique the $l_2$ norm squared distance produces an hyper-sphere region (that is a circle in the 2D space) centered in the origin. Reducing $\lambda$ the circle radius reduces as well.
In the Lasso technique the constraint is a polytope (that is a rhomboid in the 2D space). Reducing $\lambda$ the constraint space will reduce as well, but differently from Ridge Regression, $w^*$ can be located exactly on one axis (so that we will have a weight equal to 0).
Regularization allows to train complex models also with few data without obtaining severe overfitting. The problem of determining the maximum number of the polynomial degree is translated into determining the best value of the regularization parameter.
## <span style='font-family:Marker Felt;font-weight:bold'>Bayesian linear regression</span>
---
What we have seen so far was the frequentist approach to linear regression. We have data and we want to find the parameters that better explain the data. In the Bayesian approach the perspective changes. Here the parameters are **uncertain** and they become random variables. We can specify our knowledge on the parameters by specifying a prior distribution based on what we know about the problem. We start from a **prior** distribution, we observe data and this data will change our prior distribution. Combining prior and data we obtain a new probability over parameters called **posterior**. We change our knowledge by observing the real world. The posterior can be used to make predictions and, differently from the frequentist approach where the output is a single value for each weights, here we obtain a probability distribution over all the parameters. In this case we can account for uncertainties and the presence of the uncertainties helps to make decisions about the results.
The posterior can be found by combining the prior with the [likelihood](#likelihood) of the parameters (given data) through the **Bayes' Rule**:
$$
\begin{align}
p(parameters|data) = \frac{p(data|parameters)p(parameters)}{p(data)}
\end{align}
$$
$$
\begin{align}
p(parameters|data) = \frac{p(data|parameters)p(parameters)}{p(data)}
\end{align}
$$
$$
\begin{align}
posterior = \frac{likelihood\times prior}{marginal}
\end{align}
$$
$$
\begin{align}
p(\textbf w | D) = \frac{p( \mathcal D | \textbf w)p(\textbf w)}{p(\mathcal D)}
\end{align}
$$
where $\textbf w$ are the weights of the model and $ \mathcal D$ represents the observed data.
If we don't have a priori knowledge about parameters distribution we can provide an uninformative prior. This prior is nothing but a uniform probability over all the parameters space.
Since the denominator is just a normalizing term we can write that the posterior is proportional to product between the likelihood and the prior:
$$
\begin{align}
posterior \propto likelihood \times prior
\end{align}
$$
If we want to have a single output from our Bayesian model we can take the most probable value of $\textbf w$ given the data, i.e. the mode of the posterior. This approach is called **maximum a posteriori (MAP)** estimate.
The Bayesian approach is another method that allows to avoid overfitting since the prior on the parameters acts as a regularizer. The stronger the prior, the less chance the parameters have of moving in the design space. We can imagine the prior like a spring centered in the mean of the distribution with a stiffness constant $k$ proportional to the variance. The drawback is that if our prior is wrong we add an high bias to the model.
Assuming a multivariate Gaussian prior distribution $ p(\textbf w) = \mathcal{N}( \textbf w | \textbf w_0, \textbf S_0)$ we are specifying that from what we know the mean of the parameters is given by $\textbf w_0$ with a covariance matrix given by $ \textbf S_0$.
If also the likelihood is Gaussian then the posterior will be Gaussian too (this is true only for Gaussian probability distributions).
$$
\begin{align}
p(\textbf w | \textbf t , \bf \Phi, \sigma^2) \propto \mathcal N (\textbf w | \textbf w_0, \textbf S_0) \mathcal N (\textbf t| \bf \Phi \textbf w, \sigma^2 \textbf I_N) = \mathcal N (\textbf w | \textbf w_N, \textbf S_N)
\end{align}
$$
$$
\begin{align}
\textbf w_N = \textbf S_N \Big( \textbf S_0^{-1} \textbf w_0 +
\frac{\bf \Phi^T \textbf t}{\sigma^2} \Big)
\end{align}
$$
$$
\begin{align}
\textbf S_N^{-1} = \textbf S_0^{-1} + \frac{\bf \Phi^T \bf \Phi}{\sigma^2}
\end{align}
$$
Let's analyze the results. If we consider the uninformative prior, so $ \textbf S_0 \rightarrow \infty $, and substitute it into the equations before we obtain that the MAP is equal to the maximum likelihood solution of the previous sections. Since the MAP of a Gaussian is equal to the mean:
$$
\begin{align}
\lim_{\textbf S_0 \to \infty} \textbf w_{MAP} = (\bf \Phi^T \bf \Phi)^{-1} \bf \Phi^T \textbf t = \textbf w_{ML}
\end{align}
$$
If then someone will provide us other data, as in an online sequential case, the just computed posterior will act as a prior for the new model.
What if the mean is $0$? Consider a case in which the prior is defined by a single parameter $\tau^2$:
$$
\begin{align}
p(\textbf w| \tau^2) = \mathcal N (\textbf w | \textbf 0, \tau^2 \textbf I)
\end{align}
$$
we have that the corresponding posterior will have mean and covariance:
$$
\begin{align}
\textbf m_N = \frac{\textbf S_N \bf \Phi^T \textbf t}{\sigma^2}
\end{align}
$$
$$
\begin{align}
\textbf S_N^{-1} = \tau^{-2} \textbf I + \sigma^{-2} \bf \Phi^T \bf \Phi
\end{align}
$$
from which we can compute the log of the posterior:
$$
\begin{align}
\ln p(\textbf w |\textbf t) = -\frac{1}{2 \sigma^2} \sum_{n=1}^N(t_n - \textbf w^T \phi(\textbf x_n))^2 - \frac{1}{2 \tau^2} \left\lVert \textbf w \right\rVert_2^2
\end{align}
$$
We obtain a result very similar to the case of linear regression with regularization. Also here we are searching for parameters that are around zero and the role of $\lambda$ is played by the covariance matrix of the prior. The maximization of the log of the posterior distribution w.r.t $\textbf w$ is therefore equivalent to the minimization of the sum-of-squares-error with the addition of a quadratic regularization term with $\lambda = \frac{\sigma^2}{\tau^2}$.
Let's consider the example of a single input variable $x$ and a single target variable $t$ given by a linear model of the form $ y(x, \textbf w) = w_0 + w_1 x$. We can generate synthetic data from the function $ y(x, \textbf a) = a_0 + a_1 x$ with for the example $a_0 = -0.3$ and $a_1 = 0.5$ following three steps:
1. Draw $x_n$ from the uniform distribution $U(x|-1,1)$
2. Evaluate $f(x_n, \textbf a)$
3. Add Gaussian noise to obtain $y(x_n, \textbf a)$
At this point our goal is to recover $a_0$ and $a_1$ from the data and we will do that following a Bayesian approach. The first line of the figure below represents the situation before data are obtained. In the central column is plotted the prior over the parameters while in the right column some functions drawn from the prior. In the second line we see the situation after having observed a single point, the blue dot in the right column. Since now we have data we can plot on the left column the likelihood. By multiplying this likelihood with the prior of the previous line, and normalizing, we obtain the posterior distribution in the central column of the second raw. We go on in the same way for all the data. This is also an example of sequential learning.
<p align="center">
</p>
We can see in the fourth row that as the number of samples increases, the posterior becomes more narrow and in the limit of an infinite number of points it would be a delta function centered on the true value of the parameters.
By taking only the MAP, we are throwing away all the informations about the uncertainty on the weights which are the the very advantage offered by a Bayesian approach. It is better to consider the **posterior predictive distribution**
$$
\begin{align}
p(t| \textbf x, \mathcal D, \sigma^2) = \int \mathcal N(t| \textbf w^T \phi(\textbf x), \sigma^2) \mathcal N (\textbf w| \textbf w_N, \textbf S_N) d\textbf w \\
= \mathcal N(t| \textbf w_N^T \phi(\textbf x), \sigma^2_N(\textbf x))
\end{align}
$$
$$
\begin{align}
\sigma^2_N(\textbf x) = \sigma^2 + \phi(\textbf x)^T \textbf S_N \phi(\textbf x)
\end{align}
$$
The variance term is composed by the irreducible noise inside the data and a term related to the uncertainty about the parameters. The first term is fixed and we cannot act on it but, as $N \rightarrow \infty$ the second term goes to zero.
By considering again the example with the sinusoidal function we can illustrate the predictive distribution for Bayesian linear regression. For each plot on the left column below, the solid red curve represents the mean of the Gaussian predictive distribution and the shaded region spans one standard deviation either side of the mean. On the right column we have functions drawn from the posterior distribution. As we can see increasing the number of samples, the shaded region decreases and the functions drawn from the posterior become more compact. The shaded region is also narrow near the blue dots since they are observed point and, the only uncertainty we have is the noise on the data.
<p align="center">
</p>
<p align="center">
</p>
<p align="center">
</p>
<p align="center">
</p>
When we face a Bayesian linear model we have two challenges:
1. Specify a suitable model, able to describe well the likelihood
2. Provide a suitable prior
In the frequentist approach we just have to face the first problem. The prior is what makes the Bayesian approach strong and at the same time risky. Another aspect related to the Bayesian treatment is associated to the computational issue of the posterior distribution. We have a closed form solution just with Gaussian distributions and so with unimodal problems. When we need to apply other distributions we lose the closed form solution and we need to rely on:
* Analytical integration
* Gaussian (Laplace) approximation
* Monte Carlo integration
* Variational approximation
So, what we have to remember from this last section?
<p align="center">
</p>
<span style='font-family:Marker Felt;font-size:20pt;color:DarkCyan;font-weight:bold'>References:</span>
1. *Restelli M., Machine Learning - course slides*
2. *Bishop C.M., "Pattern Recognition and Machine Learning", chapters: 1.1, 1.2, 1.3, 3.1, 3.3*
|
/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.list.lemmas
import Mathlib.Lean3Lib.init.wf
universes u_1
namespace Mathlib
namespace list
-- Note: we can't use the equation compiler here because
-- init.meta.well_founded_tactics uses this file
def qsort.F {α : Type u_1} (lt : α → α → Bool) (x : List α) : ((y : List α) → length y < length x → List α) → List α :=
sorry
/- This is based on the minimalist Haskell "quicksort".
Remark: this is *not* really quicksort since it doesn't partition the elements in-place -/
def qsort {α : Type u_1} (lt : α → α → Bool) : List α → List α :=
well_founded.fix sorry sorry
@[simp] theorem qsort_nil {α : Type u_1} (lt : α → α → Bool) : qsort lt [] = [] := sorry
@[simp] theorem qsort_cons {α : Type u_1} (lt : α → α → Bool) (h : α) (t : List α) : qsort lt (h :: t) =
(fun (_a : List α × List α) =>
prod.cases_on _a fun (fst snd : List α) => idRhs (List α) (qsort lt snd ++ h :: qsort lt fst))
(partition (fun (x : α) => lt h x = tt) t) := sorry
|
State Before: α : Type u_2
β : Type u_1
inst✝³ : UniformSpace α
inst✝² : Group α
inst✝¹ : UniformGroup α
inst✝ : UniformSpace β
f g : β → α
hf : UniformContinuous f
hg : UniformContinuous g
⊢ UniformContinuous fun x => f x * g x State After: α : Type u_2
β : Type u_1
inst✝³ : UniformSpace α
inst✝² : Group α
inst✝¹ : UniformGroup α
inst✝ : UniformSpace β
f g : β → α
hf : UniformContinuous f
hg : UniformContinuous g
this : UniformContinuous fun x => f x / (g x)⁻¹
⊢ UniformContinuous fun x => f x * g x Tactic: have : UniformContinuous fun x => f x / (g x)⁻¹ := hf.div hg.inv State Before: α : Type u_2
β : Type u_1
inst✝³ : UniformSpace α
inst✝² : Group α
inst✝¹ : UniformGroup α
inst✝ : UniformSpace β
f g : β → α
hf : UniformContinuous f
hg : UniformContinuous g
this : UniformContinuous fun x => f x / (g x)⁻¹
⊢ UniformContinuous fun x => f x * g x State After: no goals Tactic: simp_all |
(* Title: HOL/Auth/n_german_lemma_inv__23_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_german Protocol Case Study*}
theory n_german_lemma_inv__23_on_rules imports n_german_lemma_on_inv__23
begin
section{*All lemmas on causal relation between inv__23*}
lemma lemma_inv__23_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqEVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__23) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__23) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
If $p$ is a prime number and $m$ is a positive integer, then there exist a positive integer $k$ and a positive integer $n$ that is not divisible by $p$ such that $m = n \cdot p^k$. |
[STATEMENT]
lemma strictly_precise: "strictly_exact P \<Longrightarrow> precise P"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. strictly_exact P \<Longrightarrow> precise P
[PROOF STEP]
by (metis precise_def strictly_exactD) |
module SlurpTypes
import ...PatternStructure.Trees: SlurpHead
export SlurpHead, LazySlurp, GreedySlurp, GenericGreedySlurp, GenericLazySlurp,
SimpleLastSlurp, SimpleGreedySlurpUntil, SimpleLazySlurpUntil, SimpleSlurp
abstract type LazySlurp <: SlurpHead end
abstract type GreedySlurp <: SlurpHead end
struct GenericLazySlurp <: LazySlurp end
struct GenericGreedySlurp <: GreedySlurp end
#-----------------------------------------------------------------------------------
# Simple: slurp is composed of one single binding name, e.g. *{a}
#-----------------------------------------------------------------------------------
abstract type SimpleGreedySlurp <: GreedySlurp end
abstract type SimpleLazySlurp <: LazySlurp end
struct SimpleLastSlurp <: SimpleGreedySlurp
post::Int
end
struct SimpleGreedySlurpUntil <: SimpleGreedySlurp
until::Vector
index::Int
end
struct SimpleLazySlurpUntil <: SimpleLazySlurp
until::Vector
index::Int
end
const SimpleSlurp = Union{SimpleGreedySlurp, SimpleLazySlurp}
end
|
(* Title: HOL/Auth/n_german_lemma_inv__7_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_german Protocol Case Study*}
theory n_german_lemma_inv__7_on_rules imports n_german_lemma_on_inv__7
begin
section{*All lemmas on causal relation between inv__7*}
lemma lemma_inv__7_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__7 p__Inv2)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqSVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__0Vsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendReqE__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendReqE__part__1Vsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqEVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__7) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__7) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
(* Title: HOL/Auth/n_germanSimp_lemma_inv__42_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanSimp Protocol Case Study*}
theory n_germanSimp_lemma_inv__42_on_rules imports n_germanSimp_lemma_on_inv__42
begin
section{*All lemmas on causal relation between inv__42*}
lemma lemma_inv__42_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv3 p__Inv4. p__Inv3\<le>N\<and>p__Inv4\<le>N\<and>p__Inv3~=p__Inv4\<and>f=inv__42 p__Inv3 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqE__part__0Vsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqE__part__1Vsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__42) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__42) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Relational specification of expression simplification. *)
Require Import Coqlib.
Require Import Errors.
Require Import Maps.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import AST.
Require Import Csyntax.
Require Cstrategy.
Require Import Clight.
Require Import SimplExpr.
Section SPEC.
Local Open Scope gensym_monad_scope.
(** * Relational specification of the translation. *)
(** ** Translation of expressions *)
(** This specification covers:
- all cases of [transl_lvalue] and [transl_rvalue];
- two additional cases for [C.Eparen], so that reductions of [C.Econdition]
expressions are properly tracked;
- three additional cases allowing [C.Eval v] C expressions to match
any Clight expression [a] that evaluates to [v] in any environment
matching the given temporary environment [le].
*)
Definition final (dst: destination) (a: expr) : list statement :=
match dst with
| For_val => nil
| For_effects => nil
| For_test tyl s1 s2 => makeif (fold_left Ecast tyl a) s1 s2 :: nil
end.
Inductive tr_rvalof: type -> expr -> list statement -> expr -> list ident -> Prop :=
| tr_rvalof_nonvol: forall ty a tmp,
type_is_volatile ty = false ->
tr_rvalof ty a nil a tmp
| tr_rvalof_vol: forall ty a t tmp,
type_is_volatile ty = true -> In t tmp ->
tr_rvalof ty a (Svolread t a :: nil) (Etempvar t ty) tmp.
Inductive tr_expr: temp_env -> destination -> C.expr -> list statement -> expr -> list ident -> Prop :=
| tr_var: forall le dst id ty tmp,
tr_expr le dst (C.Evar id ty)
(final dst (Evar id ty)) (Evar id ty) tmp
| tr_deref: forall le dst e1 ty sl1 a1 tmp,
tr_expr le For_val e1 sl1 a1 tmp ->
tr_expr le dst (C.Ederef e1 ty)
(sl1 ++ final dst (Ederef a1 ty)) (Ederef a1 ty) tmp
| tr_field: forall le dst e1 f ty sl1 a1 tmp,
tr_expr le For_val e1 sl1 a1 tmp ->
tr_expr le dst (C.Efield e1 f ty)
(sl1 ++ final dst (Efield a1 f ty)) (Efield a1 f ty) tmp
| tr_val_effect: forall le v ty any tmp,
tr_expr le For_effects (C.Eval v ty) nil any tmp
| tr_val_value: forall le v ty a tmp,
typeof a = ty ->
(forall tge e le' m,
(forall id, In id tmp -> le'!id = le!id) ->
eval_expr tge e le' m a v) ->
tr_expr le For_val (C.Eval v ty)
nil a tmp
| tr_val_test: forall le tyl s1 s2 v ty a any tmp,
typeof a = ty ->
(forall tge e le' m,
(forall id, In id tmp -> le'!id = le!id) ->
eval_expr tge e le' m a v) ->
tr_expr le (For_test tyl s1 s2) (C.Eval v ty)
(makeif (fold_left Ecast tyl a) s1 s2 :: nil) any tmp
| tr_sizeof: forall le dst ty' ty tmp,
tr_expr le dst (C.Esizeof ty' ty)
(final dst (Esizeof ty' ty))
(Esizeof ty' ty) tmp
| tr_alignof: forall le dst ty' ty tmp,
tr_expr le dst (C.Ealignof ty' ty)
(final dst (Ealignof ty' ty))
(Ealignof ty' ty) tmp
| tr_valof: forall le dst e1 ty tmp sl1 a1 tmp1 sl2 a2 tmp2,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_rvalof (C.typeof e1) a1 sl2 a2 tmp2 ->
list_disjoint tmp1 tmp2 -> incl tmp1 tmp -> incl tmp2 tmp ->
tr_expr le dst (C.Evalof e1 ty)
(sl1 ++ sl2 ++ final dst a2)
a2 tmp
| tr_addrof: forall le dst e1 ty tmp sl1 a1,
tr_expr le For_val e1 sl1 a1 tmp ->
tr_expr le dst (C.Eaddrof e1 ty)
(sl1 ++ final dst (Eaddrof a1 ty))
(Eaddrof a1 ty) tmp
| tr_unop: forall le dst op e1 ty tmp sl1 a1,
tr_expr le For_val e1 sl1 a1 tmp ->
tr_expr le dst (C.Eunop op e1 ty)
(sl1 ++ final dst (Eunop op a1 ty))
(Eunop op a1 ty) tmp
| tr_binop: forall le dst op e1 e2 ty sl1 a1 tmp1 sl2 a2 tmp2 tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le For_val e2 sl2 a2 tmp2 ->
list_disjoint tmp1 tmp2 -> incl tmp1 tmp -> incl tmp2 tmp ->
tr_expr le dst (C.Ebinop op e1 e2 ty)
(sl1 ++ sl2 ++ final dst (Ebinop op a1 a2 ty))
(Ebinop op a1 a2 ty) tmp
| tr_cast: forall le dst e1 ty sl1 a1 tmp,
tr_expr le For_val e1 sl1 a1 tmp ->
tr_expr le dst (C.Ecast e1 ty)
(sl1 ++ final dst (Ecast a1 ty))
(Ecast a1 ty) tmp
| tr_condition_simple: forall le dst e1 e2 e3 ty sl1 a1 tmp1 sl2 a2 tmp2 sl3 a3 tmp3 tmp,
Cstrategy.simple e2 = true -> Cstrategy.simple e3 = true ->
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le For_val e2 sl2 a2 tmp2 ->
tr_expr le For_val e3 sl3 a3 tmp3 ->
list_disjoint tmp1 tmp2 ->
list_disjoint tmp1 tmp3 ->
incl tmp1 tmp -> incl tmp2 tmp -> incl tmp3 tmp ->
tr_expr le dst (C.Econdition e1 e2 e3 ty)
(sl1 ++ final dst (Econdition a1 a2 a3 ty))
(Econdition a1 a2 a3 ty) tmp
| tr_condition_val: forall le e1 e2 e3 ty sl1 a1 tmp1 sl2 a2 tmp2 sl3 a3 tmp3 t tmp,
Cstrategy.simple e2 = false \/ Cstrategy.simple e3 = false ->
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le For_val e2 sl2 a2 tmp2 ->
tr_expr le For_val e3 sl3 a3 tmp3 ->
list_disjoint tmp1 tmp2 ->
list_disjoint tmp1 tmp3 ->
incl tmp1 tmp -> incl tmp2 tmp -> incl tmp3 tmp ->
In t tmp -> ~In t tmp1 ->
tr_expr le For_val (C.Econdition e1 e2 e3 ty)
(sl1 ++ makeif a1
(Ssequence (makeseq sl2) (Sset t (Ecast a2 ty)))
(Ssequence (makeseq sl3) (Sset t (Ecast a3 ty))) :: nil)
(Etempvar t ty) tmp
| tr_condition_effects: forall le dst e1 e2 e3 ty sl1 a1 tmp1 sl2 a2 tmp2 sl3 a3 tmp3 any tmp,
Cstrategy.simple e2 = false \/ Cstrategy.simple e3 = false ->
dst <> For_val ->
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le (cast_destination ty dst) e2 sl2 a2 tmp2 ->
tr_expr le (cast_destination ty dst) e3 sl3 a3 tmp3 ->
list_disjoint tmp1 tmp2 ->
list_disjoint tmp1 tmp3 ->
incl tmp1 tmp -> incl tmp2 tmp -> incl tmp3 tmp ->
tr_expr le dst (C.Econdition e1 e2 e3 ty)
(sl1 ++ makeif a1 (makeseq sl2) (makeseq sl3) :: nil)
any tmp
| tr_assign_effects: forall le e1 e2 ty sl1 a1 tmp1 sl2 a2 tmp2 any tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le For_val e2 sl2 a2 tmp2 ->
list_disjoint tmp1 tmp2 ->
incl tmp1 tmp -> incl tmp2 tmp ->
tr_expr le For_effects (C.Eassign e1 e2 ty)
(sl1 ++ sl2 ++ Sassign a1 a2 :: nil)
any tmp
| tr_assign_val: forall le dst e1 e2 ty sl1 a1 tmp1 sl2 a2 tmp2 t tmp ty1 ty2,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le For_val e2 sl2 a2 tmp2 ->
incl tmp1 tmp -> incl tmp2 tmp ->
list_disjoint tmp1 tmp2 ->
In t tmp -> ~In t tmp1 -> ~In t tmp2 ->
ty1 = C.typeof e1 ->
ty2 = C.typeof e2 ->
tr_expr le dst (C.Eassign e1 e2 ty)
(sl1 ++ sl2 ++
Sset t a2 ::
Sassign a1 (Etempvar t ty2) ::
final dst (Ecast (Etempvar t ty2) ty1))
(Ecast (Etempvar t ty2) ty1) tmp
| tr_assignop_effects: forall le op e1 e2 tyres ty ty1 sl1 a1 tmp1 sl2 a2 tmp2 sl3 a3 tmp3 any tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le For_val e2 sl2 a2 tmp2 ->
ty1 = C.typeof e1 ->
tr_rvalof ty1 a1 sl3 a3 tmp3 ->
list_disjoint tmp1 tmp2 -> list_disjoint tmp1 tmp3 -> list_disjoint tmp2 tmp3 ->
incl tmp1 tmp -> incl tmp2 tmp -> incl tmp3 tmp ->
tr_expr le For_effects (C.Eassignop op e1 e2 tyres ty)
(sl1 ++ sl2 ++ sl3 ++ Sassign a1 (Ebinop op a3 a2 tyres) :: nil)
any tmp
| tr_assignop_val: forall le dst op e1 e2 tyres ty sl1 a1 tmp1 sl2 a2 tmp2 sl3 a3 tmp3 t tmp ty1,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_expr le For_val e2 sl2 a2 tmp2 ->
tr_rvalof ty1 a1 sl3 a3 tmp3 ->
list_disjoint tmp1 tmp2 -> list_disjoint tmp1 tmp3 -> list_disjoint tmp2 tmp3 ->
incl tmp1 tmp -> incl tmp2 tmp -> incl tmp3 tmp ->
In t tmp -> ~In t tmp1 -> ~In t tmp2 -> ~In t tmp3 ->
ty1 = C.typeof e1 ->
tr_expr le dst (C.Eassignop op e1 e2 tyres ty)
(sl1 ++ sl2 ++ sl3 ++
Sset t (Ebinop op a3 a2 tyres) ::
Sassign a1 (Etempvar t tyres) ::
final dst (Ecast (Etempvar t tyres) ty1))
(Ecast (Etempvar t tyres) ty1) tmp
| tr_postincr_effects: forall le id e1 ty ty1 sl1 a1 tmp1 sl2 a2 tmp2 any tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_rvalof ty1 a1 sl2 a2 tmp2 ->
ty1 = C.typeof e1 ->
incl tmp1 tmp -> incl tmp2 tmp ->
list_disjoint tmp1 tmp2 ->
tr_expr le For_effects (C.Epostincr id e1 ty)
(sl1 ++ sl2 ++ Sassign a1 (transl_incrdecr id a2 ty1) :: nil)
any tmp
| tr_postincr_val: forall le dst id e1 ty sl1 a1 tmp1 t ty1 tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
incl tmp1 tmp -> In t tmp -> ~In t tmp1 ->
ty1 = C.typeof e1 ->
tr_expr le dst (C.Epostincr id e1 ty)
(sl1 ++ make_set t a1 ::
Sassign a1 (transl_incrdecr id (Etempvar t ty1) ty1) ::
final dst (Etempvar t ty1))
(Etempvar t ty1) tmp
| tr_comma: forall le dst e1 e2 ty sl1 a1 tmp1 sl2 a2 tmp2 tmp,
tr_expr le For_effects e1 sl1 a1 tmp1 ->
tr_expr le dst e2 sl2 a2 tmp2 ->
list_disjoint tmp1 tmp2 ->
incl tmp1 tmp -> incl tmp2 tmp ->
tr_expr le dst (C.Ecomma e1 e2 ty) (sl1 ++ sl2) a2 tmp
| tr_call_effects: forall le e1 el2 ty sl1 a1 tmp1 sl2 al2 tmp2 any tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_exprlist le el2 sl2 al2 tmp2 ->
list_disjoint tmp1 tmp2 ->
incl tmp1 tmp -> incl tmp2 tmp ->
tr_expr le For_effects (C.Ecall e1 el2 ty)
(sl1 ++ sl2 ++ Scall None a1 al2 :: nil)
any tmp
| tr_call_val: forall le dst e1 el2 ty sl1 a1 tmp1 sl2 al2 tmp2 t tmp,
dst <> For_effects ->
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_exprlist le el2 sl2 al2 tmp2 ->
list_disjoint tmp1 tmp2 -> In t tmp ->
incl tmp1 tmp -> incl tmp2 tmp ->
tr_expr le dst (C.Ecall e1 el2 ty)
(sl1 ++ sl2 ++ Scall (Some t) a1 al2 :: final dst (Etempvar t ty))
(Etempvar t ty) tmp
| tr_paren_val: forall le e1 ty sl1 a1 tmp1 t tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
incl tmp1 tmp -> In t tmp ->
tr_expr le For_val (C.Eparen e1 ty)
(sl1 ++ Sset t (Ecast a1 ty) :: nil)
(Etempvar t ty) tmp
| tr_paren_effects: forall le dst e1 ty sl1 a1 tmp any,
dst <> For_val ->
tr_expr le (cast_destination ty dst) e1 sl1 a1 tmp ->
tr_expr le dst (C.Eparen e1 ty) sl1 any tmp
with tr_exprlist: temp_env -> C.exprlist -> list statement -> list expr -> list ident -> Prop :=
| tr_nil: forall le tmp,
tr_exprlist le C.Enil nil nil tmp
| tr_cons: forall le e1 el2 sl1 a1 tmp1 sl2 al2 tmp2 tmp,
tr_expr le For_val e1 sl1 a1 tmp1 ->
tr_exprlist le el2 sl2 al2 tmp2 ->
list_disjoint tmp1 tmp2 ->
incl tmp1 tmp -> incl tmp2 tmp ->
tr_exprlist le (C.Econs e1 el2) (sl1 ++ sl2) (a1 :: al2) tmp.
Scheme tr_expr_ind2 := Minimality for tr_expr Sort Prop
with tr_exprlist_ind2 := Minimality for tr_exprlist Sort Prop.
Combined Scheme tr_expr_exprlist from tr_expr_ind2, tr_exprlist_ind2.
(** Useful invariance properties. *)
Lemma tr_expr_invariant:
forall le dst r sl a tmps, tr_expr le dst r sl a tmps ->
forall le', (forall x, In x tmps -> le'!x = le!x) ->
tr_expr le' dst r sl a tmps
with tr_exprlist_invariant:
forall le rl sl al tmps, tr_exprlist le rl sl al tmps ->
forall le', (forall x, In x tmps -> le'!x = le!x) ->
tr_exprlist le' rl sl al tmps.
Proof.
induction 1; intros; econstructor; eauto.
intros. apply H0. intros. transitivity (le'!id); auto.
intros. apply H0. auto. intros. transitivity (le'!id); auto.
induction 1; intros; econstructor; eauto.
Qed.
Lemma tr_rvalof_monotone:
forall ty a sl b tmps, tr_rvalof ty a sl b tmps ->
forall tmps', incl tmps tmps' -> tr_rvalof ty a sl b tmps'.
Proof.
induction 1; intros; econstructor; unfold incl in *; eauto.
Qed.
Lemma tr_expr_monotone:
forall le dst r sl a tmps, tr_expr le dst r sl a tmps ->
forall tmps', incl tmps tmps' -> tr_expr le dst r sl a tmps'
with tr_exprlist_monotone:
forall le rl sl al tmps, tr_exprlist le rl sl al tmps ->
forall tmps', incl tmps tmps' -> tr_exprlist le rl sl al tmps'.
Proof.
specialize tr_rvalof_monotone. intros RVALOF.
induction 1; intros; econstructor; unfold incl in *; eauto.
induction 1; intros; econstructor; unfold incl in *; eauto.
Qed.
(** ** Top-level translation *)
(** The "top-level" translation is equivalent to [tr_expr] above
for source terms. It brings additional flexibility in the matching
between C values and Cminor expressions: in the case of
[tr_expr], the Cminor expression must not depend on memory,
while in the case of [tr_top] it can depend on the current memory
state. This special case is extended to values occurring under
one or several [C.Eparen]. *)
Section TR_TOP.
Variable ge: genv.
Variable e: env.
Variable le: temp_env.
Variable m: mem.
Inductive tr_top: destination -> C.expr -> list statement -> expr -> list ident -> Prop :=
| tr_top_val_val: forall v ty a tmp,
typeof a = ty -> eval_expr ge e le m a v ->
tr_top For_val (C.Eval v ty) nil a tmp
| tr_top_val_test: forall tyl s1 s2 v ty a any tmp,
typeof a = ty -> eval_expr ge e le m a v ->
tr_top (For_test tyl s1 s2) (C.Eval v ty) (makeif (fold_left Ecast tyl a) s1 s2 :: nil) any tmp
| tr_top_base: forall dst r sl a tmp,
tr_expr le dst r sl a tmp ->
tr_top dst r sl a tmp
| tr_top_paren_test: forall tyl s1 s2 r ty sl a tmp,
tr_top (For_test (ty :: tyl) s1 s2) r sl a tmp ->
tr_top (For_test tyl s1 s2) (C.Eparen r ty) sl a tmp.
End TR_TOP.
(** ** Translation of statements *)
Inductive tr_expression: C.expr -> statement -> expr -> Prop :=
| tr_expression_intro: forall r sl a tmps,
(forall ge e le m, tr_top ge e le m For_val r sl a tmps) ->
tr_expression r (makeseq sl) a.
Inductive tr_expr_stmt: C.expr -> statement -> Prop :=
| tr_expr_stmt_intro: forall r sl a tmps,
(forall ge e le m, tr_top ge e le m For_effects r sl a tmps) ->
tr_expr_stmt r (makeseq sl).
Inductive tr_if: C.expr -> statement -> statement -> statement -> Prop :=
| tr_if_intro: forall r s1 s2 sl a tmps,
(forall ge e le m, tr_top ge e le m (For_test nil s1 s2) r sl a tmps) ->
tr_if r s1 s2 (makeseq sl).
Inductive tr_stmt: C.statement -> statement -> Prop :=
| tr_skip:
tr_stmt C.Sskip Sskip
| tr_do: forall r s,
tr_expr_stmt r s ->
tr_stmt (C.Sdo r) s
| tr_seq: forall s1 s2 ts1 ts2,
tr_stmt s1 ts1 -> tr_stmt s2 ts2 ->
tr_stmt (C.Ssequence s1 s2) (Ssequence ts1 ts2)
| tr_ifthenelse_big: forall r s1 s2 s' a ts1 ts2,
tr_expression r s' a ->
tr_stmt s1 ts1 -> tr_stmt s2 ts2 ->
tr_stmt (C.Sifthenelse r s1 s2) (Ssequence s' (Sifthenelse a ts1 ts2))
| tr_ifthenelse_small: forall r s1 s2 ts1 ts2 ts,
tr_stmt s1 ts1 -> tr_stmt s2 ts2 ->
small_stmt ts1 = true -> small_stmt ts2 = true ->
tr_if r ts1 ts2 ts ->
tr_stmt (C.Sifthenelse r s1 s2) ts
| tr_while: forall r s1 s' ts1,
tr_if r Sskip Sbreak s' ->
tr_stmt s1 ts1 ->
tr_stmt (C.Swhile r s1)
(Swhile expr_true (Ssequence s' ts1))
| tr_dowhile: forall r s1 s' ts1,
tr_if r Sskip Sbreak s' ->
tr_stmt s1 ts1 ->
tr_stmt (C.Sdowhile r s1)
(Sfor' expr_true s' ts1)
| tr_for_1: forall r s3 s4 s' ts3 ts4,
tr_if r Sskip Sbreak s' ->
tr_stmt s3 ts3 ->
tr_stmt s4 ts4 ->
tr_stmt (C.Sfor C.Sskip r s3 s4)
(Sfor' expr_true ts3 (Ssequence s' ts4))
| tr_for_2: forall s1 r s3 s4 s' ts1 ts3 ts4,
tr_if r Sskip Sbreak s' ->
s1 <> C.Sskip ->
tr_stmt s1 ts1 ->
tr_stmt s3 ts3 ->
tr_stmt s4 ts4 ->
tr_stmt (C.Sfor s1 r s3 s4)
(Ssequence ts1 (Sfor' expr_true ts3 (Ssequence s' ts4)))
| tr_break:
tr_stmt C.Sbreak Sbreak
| tr_continue:
tr_stmt C.Scontinue Scontinue
| tr_return_none:
tr_stmt (C.Sreturn None) (Sreturn None)
| tr_return_some: forall r s' a,
tr_expression r s' a ->
tr_stmt (C.Sreturn (Some r)) (Ssequence s' (Sreturn (Some a)))
| tr_switch: forall r ls s' a tls,
tr_expression r s' a ->
tr_lblstmts ls tls ->
tr_stmt (C.Sswitch r ls) (Ssequence s' (Sswitch a tls))
| tr_label: forall lbl s ts,
tr_stmt s ts ->
tr_stmt (C.Slabel lbl s) (Slabel lbl ts)
| tr_goto: forall lbl,
tr_stmt (C.Sgoto lbl) (Sgoto lbl)
with tr_lblstmts: C.labeled_statements -> labeled_statements -> Prop :=
| tr_default: forall s ts,
tr_stmt s ts ->
tr_lblstmts (C.LSdefault s) (LSdefault ts)
| tr_case: forall n s ls ts tls,
tr_stmt s ts ->
tr_lblstmts ls tls ->
tr_lblstmts (C.LScase n s ls) (LScase n ts tls).
(** * Correctness proof with respect to the specification. *)
(** ** Properties of the monad *)
Remark bind_inversion:
forall (A B: Type) (f: mon A) (g: A -> mon B) (y: B) (z1 z3: generator) I,
bind f g z1 = Res y z3 I ->
exists x, exists z2, exists I1, exists I2,
f z1 = Res x z2 I1 /\ g x z2 = Res y z3 I2.
Proof.
intros until I. unfold bind. destruct (f z1).
congruence.
caseEq (g a g'); intros; inv H0.
econstructor; econstructor; econstructor; econstructor; eauto.
Qed.
Remark bind2_inversion:
forall (A B C: Type) (f: mon (A*B)) (g: A -> B -> mon C) (y: C) (z1 z3: generator) I,
bind2 f g z1 = Res y z3 I ->
exists x1, exists x2, exists z2, exists I1, exists I2,
f z1 = Res (x1,x2) z2 I1 /\ g x1 x2 z2 = Res y z3 I2.
Proof.
unfold bind2. intros.
exploit bind_inversion; eauto.
intros [[x1 x2] [z2 [I1 [I2 [P Q]]]]]. simpl in Q.
exists x1; exists x2; exists z2; exists I1; exists I2; auto.
Qed.
Ltac monadInv1 H :=
match type of H with
| (Res _ _ _ = Res _ _ _) =>
inversion H; clear H; try subst
| (@ret _ _ _ = Res _ _ _) =>
inversion H; clear H; try subst
| (@error _ _ _ = Res _ _ _) =>
inversion H
| (bind ?F ?G ?Z = Res ?X ?Z' ?I) =>
let x := fresh "x" in (
let z := fresh "z" in (
let I1 := fresh "I" in (
let I2 := fresh "I" in (
let EQ1 := fresh "EQ" in (
let EQ2 := fresh "EQ" in (
destruct (bind_inversion _ _ F G X Z Z' I H) as [x [z [I1 [I2 [EQ1 EQ2]]]]];
clear H;
try (monadInv1 EQ2)))))))
| (bind2 ?F ?G ?Z = Res ?X ?Z' ?I) =>
let x := fresh "x" in (
let y := fresh "y" in (
let z := fresh "z" in (
let I1 := fresh "I" in (
let I2 := fresh "I" in (
let EQ1 := fresh "EQ" in (
let EQ2 := fresh "EQ" in (
destruct (bind2_inversion _ _ _ F G X Z Z' I H) as [x [y [z [I1 [I2 [EQ1 EQ2]]]]]];
clear H;
try (monadInv1 EQ2))))))))
end.
Ltac monadInv H :=
match type of H with
| (@ret _ _ _ = Res _ _ _) => monadInv1 H
| (@error _ _ _ = Res _ _ _) => monadInv1 H
| (bind ?F ?G ?Z = Res ?X ?Z' ?I) => monadInv1 H
| (bind2 ?F ?G ?Z = Res ?X ?Z' ?I) => monadInv1 H
| (?F _ _ _ _ _ _ _ _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
| (?F _ _ _ _ _ _ _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
| (?F _ _ _ _ _ _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
| (?F _ _ _ _ _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
| (?F _ _ _ _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
| (?F _ _ _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
| (?F _ _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
| (?F _ = Res _ _ _) =>
((progress simpl in H) || unfold F in H); monadInv1 H
end.
(** ** Freshness and separation properties. *)
Definition within (id: ident) (g1 g2: generator) : Prop :=
Ple (gen_next g1) id /\ Plt id (gen_next g2).
Lemma gensym_within:
forall ty g1 id g2 I,
gensym ty g1 = Res id g2 I -> within id g1 g2.
Proof.
intros. monadInv H. split. apply Ple_refl. apply Plt_succ.
Qed.
Lemma within_widen:
forall id g1 g2 g1' g2',
within id g1 g2 ->
Ple (gen_next g1') (gen_next g1) ->
Ple (gen_next g2) (gen_next g2') ->
within id g1' g2'.
Proof.
intros. destruct H. split.
eapply Ple_trans; eauto.
unfold Plt, Ple in *. omega.
Qed.
Definition contained (l: list ident) (g1 g2: generator) : Prop :=
forall id, In id l -> within id g1 g2.
Lemma contained_nil:
forall g1 g2, contained nil g1 g2.
Proof.
intros; red; intros; contradiction.
Qed.
Lemma contained_widen:
forall l g1 g2 g1' g2',
contained l g1 g2 ->
Ple (gen_next g1') (gen_next g1) ->
Ple (gen_next g2) (gen_next g2') ->
contained l g1' g2'.
Proof.
intros; red; intros. eapply within_widen; eauto.
Qed.
Lemma contained_cons:
forall id l g1 g2,
within id g1 g2 -> contained l g1 g2 -> contained (id :: l) g1 g2.
Proof.
intros; red; intros. simpl in H1; destruct H1. subst id0. auto. auto.
Qed.
Lemma contained_app:
forall l1 l2 g1 g2,
contained l1 g1 g2 -> contained l2 g1 g2 -> contained (l1 ++ l2) g1 g2.
Proof.
intros; red; intros. destruct (in_app_or _ _ _ H1); auto.
Qed.
Lemma contained_disjoint:
forall g1 l1 g2 l2 g3,
contained l1 g1 g2 -> contained l2 g2 g3 -> list_disjoint l1 l2.
Proof.
intros; red; intros. red; intro; subst y.
exploit H; eauto. intros [A B]. exploit H0; eauto. intros [C D].
elim (Plt_strict x). apply Plt_Ple_trans with (gen_next g2); auto.
Qed.
Lemma contained_notin:
forall g1 l g2 id g3,
contained l g1 g2 -> within id g2 g3 -> ~In id l.
Proof.
intros; red; intros. exploit H; eauto. intros [C D]. destruct H0 as [A B].
elim (Plt_strict id). apply Plt_Ple_trans with (gen_next g2); auto.
Qed.
Hint Resolve gensym_within within_widen contained_widen
contained_cons contained_app contained_disjoint
contained_notin contained_nil
incl_refl incl_tl incl_app incl_appl incl_appr
in_eq in_cons
Ple_trans Ple_refl: gensym.
(** ** Correctness of the translation functions *)
Lemma finish_meets_spec_1:
forall dst sl a sl' a',
finish dst sl a = (sl', a') -> sl' = sl ++ final dst a.
Proof.
intros. destruct dst; simpl in *; inv H. apply app_nil_end. apply app_nil_end. auto.
Qed.
Lemma finish_meets_spec_2:
forall dst sl a sl' a',
finish dst sl a = (sl', a') -> a' = a.
Proof.
intros. destruct dst; simpl in *; inv H; auto.
Qed.
Ltac UseFinish :=
match goal with
| [ H: finish _ _ _ = (_, _) |- _ ] =>
try (rewrite (finish_meets_spec_2 _ _ _ _ _ H));
try (rewrite (finish_meets_spec_1 _ _ _ _ _ H));
repeat rewrite app_ass
end.
Lemma transl_valof_meets_spec:
forall ty a g sl b g' I,
transl_valof ty a g = Res (sl, b) g' I ->
exists tmps, tr_rvalof ty a sl b tmps /\ contained tmps g g'.
Proof.
unfold transl_valof; intros.
destruct (type_is_volatile ty) as []_eqn; monadInv H.
exists (x :: nil); split; eauto with gensym. econstructor; eauto with coqlib.
exists (@nil ident); split; eauto with gensym. constructor; auto.
(*
destruct (access_mode ty) as []_eqn.
destruct (Csem.type_is_volatile ty) as []_eqn; monadInv H.
exists (x :: nil); split; eauto with gensym. econstructor; eauto with coqlib.
exists (@nil ident); split; eauto with gensym. constructor; auto.
monadInv H. exists (@nil ident); split; eauto with gensym. constructor; auto.
monadInv H. exists (@nil ident); split; eauto with gensym. constructor; auto.
*)
Qed.
Scheme expr_ind2 := Induction for C.expr Sort Prop
with exprlist_ind2 := Induction for C.exprlist Sort Prop.
Combined Scheme expr_exprlist_ind from expr_ind2, exprlist_ind2.
Lemma transl_meets_spec:
(forall r dst g sl a g' I,
transl_expr dst r g = Res (sl, a) g' I ->
exists tmps, (forall le, tr_expr le dst r sl a tmps) /\ contained tmps g g')
/\
(forall rl g sl al g' I,
transl_exprlist rl g = Res (sl, al) g' I ->
exists tmps, (forall le, tr_exprlist le rl sl al tmps) /\ contained tmps g g').
Proof.
apply expr_exprlist_ind; intros.
(* val *)
simpl in H. destruct v; monadInv H; exists (@nil ident); split; auto with gensym.
Opaque makeif.
intros. destruct dst; simpl in H1; inv H1.
constructor. auto. intros; constructor.
constructor.
constructor. auto. intros; constructor.
intros. destruct dst; simpl in H1; inv H1.
constructor. auto. intros; constructor.
constructor.
constructor. auto. intros; constructor.
(* var *)
monadInv H; econstructor; split; auto with gensym. UseFinish. constructor.
(* field *)
monadInv H0. exploit H; eauto. intros [tmp [A B]]. UseFinish.
econstructor; split; eauto. constructor; auto.
(* valof *)
monadInv H0. exploit H; eauto. intros [tmp1 [A B]].
exploit transl_valof_meets_spec; eauto. intros [tmp2 [C D]]. UseFinish.
exists (tmp1 ++ tmp2); split.
econstructor; eauto with gensym.
eauto with gensym.
(* deref *)
monadInv H0. exploit H; eauto. intros [tmp [A B]]. UseFinish.
econstructor; split; eauto. constructor; auto.
(* addrof *)
monadInv H0. exploit H; eauto. intros [tmp [A B]]. UseFinish.
econstructor; split; eauto. econstructor; eauto.
(* unop *)
monadInv H0. exploit H; eauto. intros [tmp [A B]]. UseFinish.
econstructor; split; eauto. constructor; auto.
(* binop *)
monadInv H1. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]]. UseFinish.
exists (tmp1 ++ tmp2); split.
econstructor; eauto with gensym.
eauto with gensym.
(* cast *)
monadInv H0. exploit H; eauto. intros [tmp [A B]]. UseFinish.
econstructor; split; eauto. constructor; auto.
(* condition *)
simpl in H2.
destruct (Cstrategy.simple r2 && Cstrategy.simple r3) as []_eqn.
(* simple *)
monadInv H2. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]].
exploit H1; eauto. intros [tmp3 [E F]].
UseFinish. destruct (andb_prop _ _ Heqb).
exists (tmp1 ++ tmp2 ++ tmp3); split.
intros; eapply tr_condition_simple; eauto with gensym.
apply contained_app. eauto with gensym.
apply contained_app; eauto with gensym.
(* not simple *)
monadInv H2. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]].
exploit H1; eauto. intros [tmp3 [E F]].
rewrite andb_false_iff in Heqb.
destruct dst; monadInv EQ3.
(* for value *)
exists (x2 :: tmp1 ++ tmp2 ++ tmp3); split.
intros; eapply tr_condition_val; eauto with gensym.
apply contained_cons. eauto with gensym.
apply contained_app. eauto with gensym.
apply contained_app; eauto with gensym.
(* for effects *)
exists (tmp1 ++ tmp2 ++ tmp3); split.
intros; eapply tr_condition_effects; eauto with gensym. congruence.
apply contained_app; eauto with gensym.
(* for test *)
exists (tmp1 ++ tmp2 ++ tmp3); split.
intros; eapply tr_condition_effects; eauto with gensym. congruence.
apply contained_app; eauto with gensym.
(* sizeof *)
monadInv H. UseFinish.
exists (@nil ident); split; auto with gensym. constructor.
(* alignof *)
monadInv H. UseFinish.
exists (@nil ident); split; auto with gensym. constructor.
(* assign *)
monadInv H1. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]].
destruct dst; monadInv EQ2.
(* for value *)
exists (x1 :: tmp1 ++ tmp2); split.
intros. eapply tr_assign_val with (dst := For_val); eauto with gensym.
apply contained_cons. eauto with gensym.
apply contained_app; eauto with gensym.
(* for effects *)
exists (tmp1 ++ tmp2); split.
econstructor; eauto with gensym.
apply contained_app; eauto with gensym.
(* for test *)
exists (x1 :: tmp1 ++ tmp2); split.
repeat rewrite app_ass. simpl.
intros. eapply tr_assign_val with (dst := For_test tyl s1 s2); eauto with gensym.
apply contained_cons. eauto with gensym.
apply contained_app; eauto with gensym.
(* assignop *)
monadInv H1. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]].
exploit transl_valof_meets_spec; eauto. intros [tmp3 [E F]].
destruct dst; monadInv EQ3.
(* for value *)
exists (x2 :: tmp1 ++ tmp2 ++ tmp3); split.
intros. eapply tr_assignop_val with (dst := For_val); eauto with gensym.
apply contained_cons. eauto with gensym.
apply contained_app; eauto with gensym.
(* for effects *)
exists (tmp1 ++ tmp2 ++ tmp3); split.
econstructor; eauto with gensym.
apply contained_app; eauto with gensym.
(* for test *)
exists (x2 :: tmp1 ++ tmp2 ++ tmp3); split.
repeat rewrite app_ass. simpl.
intros. eapply tr_assignop_val with (dst := For_test tyl s1 s2); eauto with gensym.
apply contained_cons. eauto with gensym.
apply contained_app; eauto with gensym.
(* postincr *)
monadInv H0. exploit H; eauto. intros [tmp1 [A B]].
destruct dst; monadInv EQ0.
(* for value *)
exists (x0 :: tmp1); split.
econstructor; eauto with gensym.
apply contained_cons; eauto with gensym.
(* for effects *)
exploit transl_valof_meets_spec; eauto. intros [tmp2 [C D]].
exists (tmp1 ++ tmp2); split.
econstructor; eauto with gensym.
eauto with gensym.
(* for test *)
repeat rewrite app_ass; simpl.
exists (x0 :: tmp1); split.
econstructor; eauto with gensym.
apply contained_cons; eauto with gensym.
(* comma *)
monadInv H1. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]].
exists (tmp1 ++ tmp2); split.
econstructor; eauto with gensym.
apply contained_app; eauto with gensym.
(* call *)
monadInv H1. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]].
destruct dst; monadInv EQ2.
(* for value *)
exists (x1 :: tmp1 ++ tmp2); split.
econstructor; eauto with gensym. congruence.
apply contained_cons. eauto with gensym.
apply contained_app; eauto with gensym.
(* for effects *)
exists (tmp1 ++ tmp2); split.
econstructor; eauto with gensym.
apply contained_app; eauto with gensym.
(* for test *)
exists (x1 :: tmp1 ++ tmp2); split.
repeat rewrite app_ass. econstructor; eauto with gensym. congruence.
apply contained_cons. eauto with gensym.
apply contained_app; eauto with gensym.
(* loc *)
monadInv H.
(* paren *)
monadInv H0.
(* nil *)
monadInv H; exists (@nil ident); split; auto with gensym. constructor.
(* cons *)
monadInv H1. exploit H; eauto. intros [tmp1 [A B]].
exploit H0; eauto. intros [tmp2 [C D]].
exists (tmp1 ++ tmp2); split.
econstructor; eauto with gensym.
eauto with gensym.
Qed.
Lemma transl_expr_meets_spec:
forall r dst g sl a g' I,
transl_expr dst r g = Res (sl, a) g' I ->
exists tmps, forall ge e le m, tr_top ge e le m dst r sl a tmps.
Proof.
intros. exploit (proj1 transl_meets_spec); eauto. intros [tmps [A B]].
exists tmps; intros. apply tr_top_base. auto.
Qed.
Lemma transl_expression_meets_spec:
forall r g s a g' I,
transl_expression r g = Res (s, a) g' I ->
tr_expression r s a.
Proof.
intros. monadInv H. exploit transl_expr_meets_spec; eauto.
intros [tmps A]. econstructor; eauto.
Qed.
Lemma transl_expr_stmt_meets_spec:
forall r g s g' I,
transl_expr_stmt r g = Res s g' I ->
tr_expr_stmt r s.
Proof.
intros. monadInv H. exploit transl_expr_meets_spec; eauto.
intros [tmps A]. econstructor; eauto.
Qed.
Lemma transl_if_meets_spec:
forall r s1 s2 g s g' I,
transl_if r s1 s2 g = Res s g' I ->
tr_if r s1 s2 s.
Proof.
intros. monadInv H. exploit transl_expr_meets_spec; eauto.
intros [tmps A]. econstructor; eauto.
Qed.
Lemma transl_stmt_meets_spec:
forall s g ts g' I, transl_stmt s g = Res ts g' I -> tr_stmt s ts
with transl_lblstmt_meets_spec:
forall s g ts g' I, transl_lblstmt s g = Res ts g' I -> tr_lblstmts s ts.
Proof.
generalize transl_expression_meets_spec transl_expr_stmt_meets_spec transl_if_meets_spec; intros T1 T2 T3.
Opaque transl_expression transl_expr_stmt.
clear transl_stmt_meets_spec.
induction s; simpl; intros until I; intros TR;
try (monadInv TR); try (constructor; eauto).
remember (small_stmt x && small_stmt x0). destruct b.
exploit andb_prop; eauto. intros [A B].
eapply tr_ifthenelse_small; eauto.
monadInv EQ2. eapply tr_ifthenelse_big; eauto.
destruct (is_Sskip s1); monadInv EQ4.
apply tr_for_1; eauto.
apply tr_for_2; eauto.
destruct o; monadInv TR; constructor; eauto.
clear transl_lblstmt_meets_spec.
induction s; simpl; intros until I; intros TR;
monadInv TR; constructor; eauto.
Qed.
Theorem transl_function_spec:
forall f tf,
transl_function f = OK tf ->
tr_stmt f.(C.fn_body) tf.(fn_body)
/\ fn_return tf = C.fn_return f
/\ fn_params tf = C.fn_params f
/\ fn_vars tf = C.fn_vars f.
Proof.
intros until tf. unfold transl_function.
case_eq (transl_stmt (C.fn_body f) initial_generator); intros; inv H0.
simpl. intuition. eapply transl_stmt_meets_spec; eauto.
Qed.
End SPEC.
|
{-# OPTIONS --safe #-}
module Cubical.Algebra.Field.Base where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.Univalence
open import Cubical.Foundations.SIP
open import Cubical.Relation.Nullary
open import Cubical.Data.Sigma
open import Cubical.Data.Unit
open import Cubical.Data.Empty
open import Cubical.Algebra.Semigroup
open import Cubical.Algebra.Monoid
open import Cubical.Algebra.AbGroup
open import Cubical.Algebra.Ring
hiding (_$_)
open import Cubical.Algebra.CommRing
open import Cubical.Displayed.Base
open import Cubical.Displayed.Auto
open import Cubical.Displayed.Record
open import Cubical.Displayed.Universe
open import Cubical.Reflection.RecordEquiv
open Iso
private
variable
ℓ ℓ' : Level
record IsField {R : Type ℓ}
(0r 1r : R) (_+_ _·_ : R → R → R) (-_ : R → R)
(_[_]⁻¹ : (x : R) → ¬ (x ≡ 0r) → R) : Type ℓ where
constructor isfield
field
isCommRing : IsCommRing 0r 1r _+_ _·_ -_
·⁻¹≡1 : (x : R) (≢0 : ¬ (x ≡ 0r)) → x · (x [ ≢0 ]⁻¹) ≡ 1r
0≢1 : ¬ (0r ≡ 1r)
open IsCommRing isCommRing public
record FieldStr (A : Type ℓ) : Type (ℓ-suc ℓ) where
constructor fieldstr
field
0r : A
1r : A
_+_ : A → A → A
_·_ : A → A → A
-_ : A → A
_[_]⁻¹ : (x : A) → ¬ (x ≡ 0r) → A
isField : IsField 0r 1r _+_ _·_ -_ _[_]⁻¹
infix 8 -_
infixl 7 _·_
infixl 6 _+_
open IsField isField public
Field : ∀ ℓ → Type (ℓ-suc ℓ)
Field ℓ = TypeWithStr ℓ FieldStr
isSetField : (R : Field ℓ) → isSet ⟨ R ⟩
isSetField R = R .snd .FieldStr.isField .IsField.·IsMonoid .IsMonoid.isSemigroup .IsSemigroup.is-set
makeIsField : {R : Type ℓ} {0r 1r : R} {_+_ _·_ : R → R → R} { -_ : R → R}
{_[_]⁻¹ : (x : R) → ¬ (x ≡ 0r) → R}
(is-setR : isSet R)
(+-assoc : (x y z : R) → x + (y + z) ≡ (x + y) + z)
(+-rid : (x : R) → x + 0r ≡ x)
(+-rinv : (x : R) → x + (- x) ≡ 0r)
(+-comm : (x y : R) → x + y ≡ y + x)
(·-assoc : (x y z : R) → x · (y · z) ≡ (x · y) · z)
(·-rid : (x : R) → x · 1r ≡ x)
(·-rdist-+ : (x y z : R) → x · (y + z) ≡ (x · y) + (x · z))
(·-comm : (x y : R) → x · y ≡ y · x)
(·⁻¹≡1 : (x : R) (≢0 : ¬ (x ≡ 0r)) → x · (x [ ≢0 ]⁻¹) ≡ 1r)
(0≢1 : ¬ (0r ≡ 1r))
→ IsField 0r 1r _+_ _·_ -_ _[_]⁻¹
makeIsField {_+_ = _+_} is-setR +-assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-rdist-+ ·-comm ·⁻¹≡1 0≢1 =
isfield (makeIsCommRing is-setR +-assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-rdist-+ ·-comm) ·⁻¹≡1 0≢1
makeField : {R : Type ℓ} (0r 1r : R) (_+_ _·_ : R → R → R) (-_ : R → R) (_[_]⁻¹ : (x : R) → ¬ (x ≡ 0r) → R)
(is-setR : isSet R)
(+-assoc : (x y z : R) → x + (y + z) ≡ (x + y) + z)
(+-rid : (x : R) → x + 0r ≡ x)
(+-rinv : (x : R) → x + (- x) ≡ 0r)
(+-comm : (x y : R) → x + y ≡ y + x)
(·-assoc : (x y z : R) → x · (y · z) ≡ (x · y) · z)
(·-rid : (x : R) → x · 1r ≡ x)
(·-rdist-+ : (x y z : R) → x · (y + z) ≡ (x · y) + (x · z))
(·-comm : (x y : R) → x · y ≡ y · x)
(·⁻¹≡1 : (x : R) (≢0 : ¬ (x ≡ 0r)) → x · (x [ ≢0 ]⁻¹) ≡ 1r)
(0≢1 : ¬ (0r ≡ 1r))
→ Field ℓ
makeField 0r 1r _+_ _·_ -_ _[_]⁻¹ is-setR +-assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-rdist-+ ·-comm ·⁻¹≡1 0≢1 =
_ , fieldstr _ _ _ _ _ _ (makeIsField is-setR +-assoc +-rid +-rinv +-comm ·-assoc ·-rid ·-rdist-+ ·-comm ·⁻¹≡1 0≢1)
FieldStr→CommRingStr : {A : Type ℓ} → FieldStr A → CommRingStr A
FieldStr→CommRingStr (fieldstr _ _ _ _ _ _ H) = commringstr _ _ _ _ _ (IsField.isCommRing H)
Field→CommRing : Field ℓ → CommRing ℓ
Field→CommRing (_ , fieldstr _ _ _ _ _ _ H) = _ , commringstr _ _ _ _ _ (IsField.isCommRing H)
record IsFieldHom {A : Type ℓ} {B : Type ℓ'} (R : FieldStr A) (f : A → B) (S : FieldStr B)
: Type (ℓ-max ℓ ℓ')
where
-- Shorter qualified names
private
module R = FieldStr R
module S = FieldStr S
field
pres0 : f R.0r ≡ S.0r
pres1 : f R.1r ≡ S.1r
pres+ : (x y : A) → f (x R.+ y) ≡ f x S.+ f y
pres· : (x y : A) → f (x R.· y) ≡ f x S.· f y
pres- : (x : A) → f (R.- x) ≡ S.- (f x)
pres⁻¹ : (x : A) (≢0 : ¬ (x ≡ R.0r)) (f≢0 : ¬ (f x ≡ S.0r)) → f (x R.[ ≢0 ]⁻¹) ≡ ((f x) S.[ f≢0 ]⁻¹)
unquoteDecl IsFieldHomIsoΣ = declareRecordIsoΣ IsFieldHomIsoΣ (quote IsFieldHom)
FieldHom : (R : Field ℓ) (S : Field ℓ') → Type (ℓ-max ℓ ℓ')
FieldHom R S = Σ[ f ∈ (⟨ R ⟩ → ⟨ S ⟩) ] IsFieldHom (R .snd) f (S .snd)
IsFieldEquiv : {A : Type ℓ} {B : Type ℓ'}
(R : FieldStr A) (e : A ≃ B) (S : FieldStr B) → Type (ℓ-max ℓ ℓ')
IsFieldEquiv R e S = IsFieldHom R (e .fst) S
FieldEquiv : (R : Field ℓ) (S : Field ℓ') → Type (ℓ-max ℓ ℓ')
FieldEquiv R S = Σ[ e ∈ (R .fst ≃ S .fst) ] IsFieldEquiv (R .snd) e (S .snd)
_$_ : {R S : Field ℓ} → (φ : FieldHom R S) → (x : ⟨ R ⟩) → ⟨ S ⟩
φ $ x = φ .fst x
FieldEquiv→FieldHom : {A B : Field ℓ} → FieldEquiv A B → FieldHom A B
FieldEquiv→FieldHom (e , eIsHom) = e .fst , eIsHom
isPropIsField : {R : Type ℓ} (0r 1r : R) (_+_ _·_ : R → R → R) (-_ : R → R) (_[_]⁻¹ : (x : R) → ¬ (x ≡ 0r) → R)
→ isProp (IsField 0r 1r _+_ _·_ -_ _[_]⁻¹)
isPropIsField 0r 1r _+_ _·_ -_ _[_]⁻¹ (isfield RR RC RD) (isfield SR SC SD) =
λ i → isfield (isPropIsCommRing _ _ _ _ _ RR SR i)
(isPropInv RC SC i) (isProp→⊥ RD SD i)
where
isSetR : isSet _
isSetR = RR .IsCommRing.·IsMonoid .IsMonoid.isSemigroup .IsSemigroup.is-set
isPropInv : isProp ((x : _) → (≢0 : ¬ (x ≡ 0r)) → x · (x [ ≢0 ]⁻¹) ≡ 1r)
isPropInv = isPropΠ2 λ _ _ → isSetR _ _
isProp→⊥ : ∀ {A : Type ℓ} → isProp (A → ⊥)
isProp→⊥ = isPropΠ λ _ → isProp⊥
|
dotstackGrob <- function(
x = unit(0.5, "npc"), # x pos of the dotstack's origin
y = unit(0.5, "npc"), # y pos of the dotstack's origin
stackaxis = "y",
dotdia = unit(1, "npc"), # Dot diameter in the non-stack axis, should be in npc
stackposition = 0, # Position of each dot in the stack, relative to origin
stackratio = 1, # Stacking height of dots (.75 means 25% dot overlap)
default.units = "npc", name = NULL, gp = gpar(), vp = NULL)
{
if (!is.unit(x))
x <- unit(x, default.units)
if (!is.unit(y))
y <- unit(y, default.units)
if (!is.unit(dotdia))
dotdia <- unit(dotdia, default.units)
if (!is_npc(dotdia))
warn("Unit type of dotdia should be 'npc'")
grob(x = x, y = y, stackaxis = stackaxis, dotdia = dotdia,
stackposition = stackposition, stackratio = stackratio,
name = name, gp = gp, vp = vp, cl = "dotstackGrob")
}
# Only cross-version reliable way to check the unit of a unit object
is_npc <- function(x) isTRUE(grepl('^[^+^-^\\*]*[^s]npc$', as.character(x)))
#' @export
makeContext.dotstackGrob <- function(x, recording = TRUE) {
# Need absolute coordinates because when using npc coords with circleGrob,
# the radius is in the _smaller_ of the two axes. We need the radius
# to instead be defined in terms of the non-stack axis.
xmm <- convertX(x$x, "mm", valueOnly = TRUE)
ymm <- convertY(x$y, "mm", valueOnly = TRUE)
if (x$stackaxis == "x") {
dotdiamm <- convertY(x$dotdia, "mm", valueOnly = TRUE)
xpos <- xmm + dotdiamm * (x$stackposition * x$stackratio + (1 - x$stackratio) / 2)
ypos <- ymm
} else if (x$stackaxis == "y") {
dotdiamm <- convertX(x$dotdia, "mm", valueOnly = TRUE)
xpos <- xmm
ypos <- ymm + dotdiamm * (x$stackposition * x$stackratio + (1 - x$stackratio) / 2)
}
circleGrob(
x = xpos, y = ypos, r = dotdiamm / 2, default.units = "mm",
name = x$name, gp = x$gp, vp = x$vp
)
}
|
(* Title: HOL/Auth/n_germanSimp_lemma_inv__24_on_rules.thy
Author: Yongjian Li and Kaiqiang Duan, State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
Copyright 2016 State Key Lab of Computer Science, Institute of Software, Chinese Academy of Sciences
*)
header{*The n_germanSimp Protocol Case Study*}
theory n_germanSimp_lemma_inv__24_on_rules imports n_germanSimp_lemma_on_inv__24
begin
section{*All lemmas on causal relation between inv__24*}
lemma lemma_inv__24_on_rules:
assumes b1: "r \<in> rules N" and b2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__24 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
proof -
have c1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)\<or>
(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
apply (cut_tac b1, auto) done
moreover {
assume d1: "(\<exists> i d. i\<le>N\<and>d\<le>N\<and>r=n_Store i d)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_StoreVsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqS N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqSVsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__0 N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqE__part__0Vsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvReqE__part__1 N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvReqE__part__1Vsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__0 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__0Vsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInv__part__1 i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInv__part__1Vsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendInvAckVsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvInvAck i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvInvAckVsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntSVsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_SendGntE N i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_SendGntEVsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntS i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntSVsinv__24) done
}
moreover {
assume d1: "(\<exists> i. i\<le>N\<and>r=n_RecvGntE i)"
have "invHoldForRule s f r (invariants N)"
apply (cut_tac b2 d1, metis n_RecvGntEVsinv__24) done
}
ultimately show "invHoldForRule s f r (invariants N)"
by satx
qed
end
|
function [blocks,idx] = my_im2col(I,blkSize,slidingDis);
if (slidingDis==1)
blocks = im2col(I,blkSize,'sliding');
idx = [1:size(blocks,2)];
return
end
idxMat = zeros(size(I)-blkSize+1);
idxMat([[1:slidingDis:end-1],end],[[1:slidingDis:end-1],end]) = 1; % take blocks in distances of 'slidingDix', but always take the first and last one (in each row and column).
idx = find(idxMat);
[rows,cols] = ind2sub(size(idxMat),idx);
blocks = zeros(prod(blkSize),length(idx));
for i = 1:length(idx)
currBlock = I(rows(i):rows(i)+blkSize(1)-1,cols(i):cols(i)+blkSize(2)-1);
blocks(:,i) = currBlock(:);
end
|
open import FRP.JS.Bool using ( not )
open import FRP.JS.Nat using ( ) renaming ( _≟_ to _≟n_ )
open import FRP.JS.String using ( _≟_ ; _≤_ ; _<_ ; length )
open import FRP.JS.QUnit using ( TestSuite ; ok ; test ; _,_ )
module FRP.JS.Test.String where
tests : TestSuite
tests =
( test "≟"
( ok "abc ≟ abc" ("abc" ≟ "abc")
, ok "ε ≟ abc" (not ("" ≟ "abc"))
, ok "a ≟ abc" (not ("a" ≟ "abc"))
, ok "abc ≟ ABC" (not ("abc" ≟ "ABC")) )
, test "length"
( ok "length ε" (length "" ≟n 0)
, ok "length a" (length "a" ≟n 1)
, ok "length ab" (length "ab" ≟n 2)
, ok "length abc" (length "abc" ≟n 3)
, ok "length \"\\\"" (length "\"\\\"" ≟n 3)
, ok "length åäö⊢ξ∀" (length "åäö⊢ξ∀" ≟n 6)
, ok "length ⟨line-terminators⟩" (length "\r\n\x2028\x2029" ≟n 4) )
, test "≤"
( ok "abc ≤ abc" ("abc" ≤ "abc")
, ok "abc ≤ ε" (not ("abc" ≤ ""))
, ok "abc ≤ a" (not ("abc" ≤ "a"))
, ok "abc ≤ ab" (not ("abc" ≤ "a"))
, ok "abc ≤ ABC" (not ("abc" ≤ "ABC"))
, ok "ε ≤ abc" ("" ≤ "abc")
, ok "a ≤ abc" ("a" ≤ "abc")
, ok "ab ≤ abc" ("a" ≤ "abc")
, ok "ABC ≤ abc" ("ABC" ≤ "abc") )
, test "<"
( ok "abc < abc" (not ("abc" < "abc"))
, ok "abc < ε" (not ("abc" < ""))
, ok "abc < a" (not ("abc" < "a"))
, ok "abc < ab" (not ("abc" < "a"))
, ok "abc < ABC" (not ("abc" < "ABC"))
, ok "ε < abc" ("" < "abc")
, ok "a < abc" ("a" < "abc")
, ok "ab < abc" ("a" < "abc")
, ok "ABC < abc" ("ABC" < "abc") ) ) |
The limit of a sequence $a_n$ as $n$ goes to infinity is $L$ if and only if for every $\epsilon > 0$, there exists an $N$ such that for all $n > N$, we have $|a_n - L| < \epsilon$. |
[STATEMENT]
lemma "(x::nat) < y & y < z ==> x < z"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x < y \<and> y < z \<Longrightarrow> x < z
[PROOF STEP]
by linarith |
module Hedgehog.Internal.Util
import Data.DPair
import Data.List
import Data.Colist
%default total
--------------------------------------------------------------------------------
-- SafeDiv
--------------------------------------------------------------------------------
||| Interface providing a safe (total) division operation
||| by proving that the divisor is non-zero.
public export
interface Neg a => SafeDiv (0 a : Type) (0 pred : a -> Type) | a where
total safeDiv' : (n,d : a) -> (0 prf : pred d) -> a
public export
SafeDiv Int (\d => d == 0 = False) where
safeDiv' n d _ = n `div` d
public export
SafeDiv Integer (\d => d == 0 = False) where
safeDiv' n d _ = n `div` d
public export
SafeDiv Double (\d => d == 0 = False) where
safeDiv' n d _ = n / d
public export total
safeDiv : SafeDiv a pred => (n,d : a) -> {auto 0 ok : pred d} -> a
safeDiv n d = safeDiv' n d ok
public export total
fromPred : (a -> Bool) -> a -> Maybe a
fromPred p a = guard (p a) $> a
--------------------------------------------------------------------------------
-- ToInteger
--------------------------------------------------------------------------------
public export
interface Num a => ToInteger a where
toInteger : a -> Integer
toNat : a -> Nat
toNat = integerToNat . toInteger
public export
ToInteger Integer where toInteger = id
public export
ToInteger Int8 where toInteger = cast
public export
ToInteger Int16 where toInteger = cast
public export
ToInteger Int32 where toInteger = cast
public export
ToInteger Int64 where toInteger = cast
public export
ToInteger Int where toInteger = cast
public export
ToInteger Bits8 where toInteger = cast
public export
ToInteger Bits16 where toInteger = cast
public export
ToInteger Bits32 where toInteger = cast
public export
ToInteger Bits64 where toInteger = cast
public export
ToInteger Nat where
toInteger = cast
toNat = id
public export
ToInteger Double where toInteger = cast
public export
fromIntegral : ToInteger a => Num b => a -> b
fromIntegral = fromInteger . toInteger
public export
round : Num a => Double -> a
round v = let f = floor v
v' = if v - f < 0.5 then f else ceiling v
in fromInteger $ cast v'
--------------------------------------------------------------------------------
-- (Lazy) List Utilities
--------------------------------------------------------------------------------
public export
iterateBefore : (p : a -> Bool) -> (a -> a) -> (v : a) -> Colist a
iterateBefore p f = takeBefore p . iterate f
public export
iterateBefore0 : Eq a => Num a => (a -> a) -> (start : a) -> Colist a
iterateBefore0 = iterateBefore (0 ==)
||| Prepends the first list in reverse order to the
||| second list.
public export
prepRev : List a -> List a -> List a
prepRev [] ys = ys
prepRev (x :: xs) ys = prepRev xs (x :: ys)
public export
signum : Ord a => Neg a => a -> a
signum x = if x < 0
then (-1)
else if x == 0 then 0 else 1
--------------------------------------------------------------------------------
-- Colists
--------------------------------------------------------------------------------
||| Cons an element on to the front of a list unless it is already there.
public export total
consNub : Eq a => a -> Colist a -> Colist a
consNub x [] = [x]
consNub x l@(y :: xs) = if x == y then l else x :: l
public export
concatColist : Colist (Colist a) -> Colist a
concatColist ((x :: xs) :: ys) = x :: concatColist (xs :: ys)
concatColist ([] :: (x :: xs) :: ys) = x :: concatColist (xs :: ys)
concatColist _ = []
public export
concatMapColist : (a -> Colist b) -> Colist a -> Colist b
concatMapColist f = concatColist . map f
public export
fromFoldable : Foldable f => f a -> Colist a
fromFoldable = fromList . toList
--------------------------------------------------------------------------------
-- Numeric Utilities
--------------------------------------------------------------------------------
public export
IsInUnit : Double -> Bool
IsInUnit d = 0.0 < d && d < 1.0
public export
0 InUnit : Type
InUnit = Subset Double (\x => IsInUnit x = True)
export
recipBits64 : Subset Bits64 (\x => x >= 2 = True) -> InUnit
recipBits64 (Element v _) =
Element (1.0 / fromInteger (cast v)) (believe_me (Refl {x = True} ))
-- Algorithm taken from
-- https://web.archive.org/web/20151110174102/http://home.online.no/~pjacklam/notes/invnorm/
-- Accurate to about one part in 10^9.
--
-- The 'erf' package uses the same algorithm, but with an extra step
-- to get a fully accurate result, which we skip because it requires
-- the 'erfc' function.
export
invnormcdf : (p : InUnit) -> Double
invnormcdf (Element p _) =
let a1 = -3.969683028665376e+01
a2 = 2.209460984245205e+02
a3 = -2.759285104469687e+02
a4 = 1.383577518672690e+02
a5 = -3.066479806614716e+01
a6 = 2.506628277459239e+00
b1 = -5.447609879822406e+01
b2 = 1.615858368580409e+02
b3 = -1.556989798598866e+02
b4 = 6.680131188771972e+01
b5 = -1.328068155288572e+01
c1 = -7.784894002430293e-03
c2 = -3.223964580411365e-01
c3 = -2.400758277161838e+00
c4 = -2.549732539343734e+00
c5 = 4.374664141464968e+00
c6 = 2.938163982698783e+00
d1 = 7.784695709041462e-03
d2 = 3.224671290700398e-01
d3 = 2.445134137142996e+00
d4 = 3.754408661907416e+00
p_low = 0.02425
p_high = 1 - p_low
q = sqrt(-2*log(p))
in if p < p_low
then (((((c1*q+c2)*q+c3)*q+c4)*q+c5)*q+c6) /
((((d1*q+d2)*q+d3)*q+d4)*q+1)
else
if p <= p_high
then
let
q = p - 0.5
r = q*q
in
(((((a1*r+a2)*r+a3)*r+a4)*r+a5)*r+a6)*q /
(((((b1*r+b2)*r+b3)*r+b4)*r+b5)*r+1)
else
let
q = sqrt(-2*log(1-p))
in
-(((((c1*q+c2)*q+c3)*q+c4)*q+c5)*q+c6) /
((((d1*q+d2)*q+d3)*q+d4)*q+1)
|
# About
This notebook was created to follow the sympy code generation tutorial at [this link](http://www.sympy.org/scipy-2017-codegen-tutorial/)
```python
import sympy as sym
sym.init_printing()
x, y = sym.symbols('x y')
expr = 3*x**2 + sym.log(x**2 + y**2 + 1)
expr
```
```python
expr.subs({x: 17, y: 42}).evalf()
% timeit expr.subs({x: 17, y: 42}).evalf()
```
221 µs ± 948 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
```python
import math
f = lambda x, y: 3*x**2 + math.log(x**2 + y**2 + 1)
%timeit f(17, 42)
```
917 ns ± 2.67 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
```python
g = sym.lambdify([x, y], expr, modules=['math'])
g(17, 42)
```
```python
%timeit g(17, 42)
```
906 ns ± 1.64 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
```python
import numpy as np
xarr = np.linspace(17,18,5)
h = sym.lambdify([x, y], expr)
out = h(xarr, 42)
out
```
array([ 874.62754439, 900.31920442, 926.38590757, 952.82765322,
979.64444076])
lambdify constructs string representation of python code and uses python eval to compile
```python
z = z1, z2, z3 = sym.symbols('z:3')
```
```python
expr2 = x*y*(z1+z2+z3)
func2 = sym.lambdify([x, y, z], expr2)
func2(1,2, (3,4,5))
# Vector arguments can be done as tuples when using odeint... (see video/example)
```
```python
# How to efficiently deal with matrices without preconverting?
# Or just save as M, C, etc... What about pars? Third argument. Can it be dict or must it be tuple?
# How to efficiently save,
```
# Chemistry...
In example, dict is converted to tuple, both for the constants used to define the lambda, and for the tuple for evaluation. So they are in the same order
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.