text
stringlengths 0
3.34M
|
---|
#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <filesystem>
#include <qtr/parquet/parquet_primitive_row.h>
#include "qtr/schema/parquet_json_schema.h"
#include "qtr/io/parquet_file_sink.h"
#include "qtr/io/parquet_file_source.h"
using json = nlohmann::json;
int main(int argc, char *argv[]) {
std::shared_ptr<parquet::schema::GroupNode> dst_parquet_schema = qtr::load_parquet_schema("/home/saka/source/crypto-tools-cpp/schemas/tardis_option_options_chain_v1.parquet-schema.json");
//LOG(INFO) << to_string(dst_parquet_schema);
std::string src_filename = "/mnt/lab0/dataset-raw/tardis-parquet/deribit/OPTIONS/options_chain/2020/2020-01-01-deribit.OPTIONS.options_chain.parquet";
/*
if (!std::filesystem::exists(src_filename)){
std::cerr << "cannot find " << src_filename << std::endl;
return -1;
}
*/
auto source = qtr::parquet_file_source<qtr::parquet_primitive_row>(src_filename);
auto sink = qtr::parquet_file_sink<qtr::parquet_primitive_row>("/tmp/tardis_option_options_chain.parquet", dst_parquet_schema);
auto group_node = source.group_node();
std::vector<std::string> src_column_names;
for (int i =0; i!= group_node->field_count(); ++i){
src_column_names.emplace_back(group_node->field(i)->name());
}
std::vector<int> src_index;
auto dummy = qtr::parquet_primitive_row::make_unique(dst_parquet_schema);
for (size_t i=0; i!=dummy->field_count(); ++i){
int index=0;
bool found = false;
for (std::vector<std::string>::const_iterator j= src_column_names.begin(); j!=src_column_names.end(); ++j, ++index){
if (dummy->name(i) == *j){
src_index.push_back(index);
found = true;
break;
}
}
if (!found){
std::cerr << "could not find column: " << dummy->name(i) << " in source, exiting " << std::endl;
return -1;
}
}
std::vector<std::shared_ptr<parquet::schema::PrimitiveNode>> columns = dummy->primitive_nodes();
while(auto src_row = source.get_next()) {
auto dst_row = qtr::parquet_primitive_row::make_unique(dst_parquet_schema);
for (size_t i=0; i!=dst_row->field_count(); ++i){
auto item = src_row->value(src_index[i]);
dst_row->assign(i, item);
}
sink.push_back(std::move(dst_row));
}
//Cleanup
//source.close(); todo
sink.flush();
return 0;
}
|
import tensorflow as tf
import numpy as np
import cv2
import random
import PIL.Image
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from modules import *
from utils import *
from RecordReaderAll import *
from SegmentationRefinement import *
HEIGHT=192
WIDTH=256
NUM_PLANES = 20
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _float_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def writeRecordFile(split, dataset):
batchSize = 8
numOutputPlanes = 20
if split == 'train':
reader = RecordReaderAll()
filename_queue = tf.train.string_input_producer(['/mnt/vision/PlaneNet/planes_' + dataset + '_train.tfrecords'], num_epochs=1)
img_inp, global_gt_dict, _ = reader.getBatch(filename_queue, numOutputPlanes=numOutputPlanes, batchSize=batchSize, random=False, getLocal=True)
writer = tf.python_io.TFRecordWriter('/mnt/vision/PlaneNet/planes_' + dataset + '_train_temp.tfrecords')
numImages = 50000
else:
reader = RecordReaderAll()
filename_queue = tf.train.string_input_producer(['/mnt/vision/PlaneNet/planes_' + dataset + '_val.tfrecords'], num_epochs=1)
img_inp, global_gt_dict, _ = reader.getBatch(filename_queue, numOutputPlanes=numOutputPlanes, batchSize=batchSize, random=False, getLocal=True)
writer = tf.python_io.TFRecordWriter('/mnt/vision/PlaneNet/planes_' + dataset + '_val_temp.tfrecords')
numImages = 1000
pass
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
#segmentation_gt, plane_mask = fitPlaneMasksModule(global_gt_dict['plane'], global_gt_dict['depth'], global_gt_dict['normal'], width=WIDTH, height=HEIGHT, normalDotThreshold=np.cos(np.deg2rad(5)), distanceThreshold=0.05, closing=True, one_hot=True)
#global_gt_dict['segmentation'] = tf.argmax(tf.concat([segmentation_gt, 1 - plane_mask], axis=3), axis=3)
#segmentation_gt = tf.cast(tf.equal(global_gt_dict['segmentation'], tf.reshape(tf.range(NUM_PLANES), (1, 1, 1, -1))), tf.float32)
#plane_mask = tf.cast(tf.less(global_gt_dict['segmentation'], NUM_PLANES), tf.float32)
#global_gt_dict['boundary'] = findBoundaryModuleSmooth(global_gt_dict['depth'], segmentation_gt, plane_mask, global_gt_dict['smooth_boundary'], max_depth_diff = 0.1, max_normal_diff = np.sqrt(2 * (1 - np.cos(np.deg2rad(20)))))
with tf.Session() as sess:
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
for _ in range(numImages / batchSize):
img, global_gt = sess.run([img_inp, global_gt_dict])
for batchIndex in range(batchSize):
numPlanes = global_gt['num_planes'][batchIndex]
if numPlanes == 0:
print(_)
print('no plane')
continue
image = ((img[batchIndex] + 0.5) * 255).astype(np.uint8)
segmentation = np.argmax(np.concatenate([global_gt['segmentation'][batchIndex], global_gt['non_plane_mask'][batchIndex]], axis=-1), axis=-1).astype(np.uint8).squeeze()
boundary = global_gt['boundary'][batchIndex].astype(np.uint8)
semantics = global_gt['semantics'][batchIndex].astype(np.uint8)
planes = global_gt['plane'][batchIndex]
if np.isnan(planes).any():
print((global_gt['image_path'][batchIndex]))
planes, segmentation, numPlanes = removeSmallSegments(planes, np.zeros((HEIGHT, WIDTH, 3)), global_gt['depth'][batchIndex].squeeze(), np.zeros((HEIGHT, WIDTH, 3)), np.argmax(global_gt['segmentation'][batchIndex], axis=-1), global_gt['semantics'][batchIndex], global_gt['info'][batchIndex], global_gt['num_planes'][batchIndex])
if np.isnan(planes).any():
np.save('temp/plane.npy', global_gt['plane'][batchIndex])
np.save('temp/depth.npy', global_gt['depth'][batchIndex])
np.save('temp/segmentation.npy', global_gt['segmentation'][batchIndex])
np.save('temp/info.npy', global_gt['info'][batchIndex])
np.save('temp/num_planes.npy', global_gt['num_planes'][batchIndex])
print('why')
exit(1)
pass
example = tf.train.Example(features=tf.train.Features(feature={
'image_path': _bytes_feature(global_gt['image_path'][batchIndex]),
'image_raw': _bytes_feature(image.tostring()),
'depth': _float_feature(global_gt['depth'][batchIndex].reshape(-1)),
'normal': _float_feature(np.zeros((HEIGHT * WIDTH * 3))),
'semantics_raw': _bytes_feature(semantics.tostring()),
'plane': _float_feature(planes.reshape(-1)),
'num_planes': _int64_feature([numPlanes]),
'segmentation_raw': _bytes_feature(segmentation.tostring()),
'boundary_raw': _bytes_feature(boundary.tostring()),
#'plane_relation': _float_feature(planeRelations.reshape(-1)),
'info': _float_feature(global_gt['info'][batchIndex]),
}))
writer.write(example.SerializeToString())
continue
continue
pass
except tf.errors.OutOfRangeError:
print('Done training -- epoch limit reached')
finally:
# When done, ask the threads to stop.
coord.request_stop()
pass
# Wait for threads to finish.
coord.join(threads)
sess.close()
return
if __name__=='__main__':
#writeRecordFile('val', 'matterport')
#writeRecordFile('val', 'scannet')
# writeRecordFile('train', 'matterport')
#writeRecordFile('train', 'scannet')
#writeRecordFile('train', 'nyu_rgbd')
writeRecordFile('val', 'nyu_rgbd')
|
#include "../ec/builtins.hpp"
#include "../ec/mnemonic.hpp"
#include "../coin/builtins.hpp"
#include "wallet_interpreter.hpp"
#include "wallet.hpp"
#include <boost/filesystem/path.hpp>
using namespace epilog::common;
using namespace epilog::interp;
namespace epilog { namespace wallet {
wallet_interpreter::wallet_interpreter(wallet &w, const std::string &wallet_file) : interp::interpreter("wallet"), file_path_(wallet_file), wallet_(w), no_coin_security_(this->disable_coin_security()) {
init();
}
void wallet_interpreter::init()
{
set_debug_enabled();
load_builtins_file_io();
ec::builtins::load(*this);
coin::builtins::load(*this);
setup_standard_lib();
set_current_module(con_cell("wallet",0));
setup_local_builtins();
setup_wallet_impl();
// Make wallet inherit everything from wallet_impl
use_module(functor("wallet_impl",0));
set_auto_wam(true);
set_retain_state_between_queries(true);
}
void wallet_interpreter::total_reset()
{
interpreter::total_reset();
disable_coin_security();
init();
}
void wallet_interpreter::setup_local_builtins()
{
static const con_cell M("wallet",0);
load_builtin(M, con_cell("@",2), &wallet_interpreter::operator_at_2);
load_builtin(M, con_cell("@-",2), &wallet_interpreter::operator_at_silent_2);
load_builtin(M, con_cell("create",2), &wallet_interpreter::create_2);
load_builtin(M, con_cell("save",0), &wallet_interpreter::save_0);
load_builtin(M, functor("auto_save",1), &wallet_interpreter::auto_save_1);
load_builtin(M, con_cell("load",0), &wallet_interpreter::load_0);
load_builtin(M, con_cell("file",1), &wallet_interpreter::file_1);
}
void wallet_interpreter::setup_wallet_impl()
{
std::string template_source = R"PROG(
%
% New key. Increment counter.
%
newkey(PublicKey, Address) :-
wallet:numkeys(N),
retract(wallet:numkeys(_)),
N1 is N + 1,
assert(wallet:numkeys(N1)),
wallet:pubkey(N, PublicKey),
ec:address(PublicKey, Address).
'$member2'(X, Y, [X|Xs], [Y|Ys]).
'$member2'(X, Y, [_|Xs], [_|Ys]) :- '$member2'(X, Y, Xs, Ys).
%
% Sync N heap references (to frozen closures)
%
sync(N) :-
wallet:lastheap(H),
H1 is H + 1,
wallet:'@'(((frozenk(H1, N, HeapAddrs), frozen(HeapAddrs, Closures)) @ global), node),
wallet:'@'(discard, node),
HeapAddrs = [_|_], % At least one address!
(last(HeapAddrs, LastH) ->
retract(wallet:lastheap(_)), assert(wallet:lastheap(LastH)) ; true),
forall('$member2'(Closure, HeapAddress, Closures, HeapAddrs),
('$new_utxo_closure'(HeapAddress, Closure) ; true)).
%
% Iterate through next 100 frozen closures to see if we have received
% something we recognize.
%
sync :-
'$cache_addresses', sync(100), !.
sync.
sync_all :-
'$cache_addresses', sync_all0.
sync_all0 :-
sync(100), !, sync_all0.
sync_all0.
%
% Restart wallet sweep. Clean UTXO database and start from heap address 0.
% Call one sync step (which syncs 100 UTXOs)
%
resync :-
retractall(wallet:utxo(_,_,_,_)),
retractall(lastheap(_)),
assert(lastheap(0)),
sync.
%
% Compute public key addresses and store them in memory (using program database()
%
'$cache_addresses' :-
(\+ current_predicate(cache:last_address/1) -> assert(cache:last_address(0)) ; true),
cache:last_address(I),
wallet:numkeys(N),
'$cache_addresses_n'(I, N),
retract(cache:last_address(_)),
assert(cache:last_address(N)).
'$cache_addresses_n'(N, N) :- !.
'$cache_addresses_n'(I, N) :-
wallet:pubkey(I, PubKey),
ec:address(PubKey, Address),
(\+ current_predicate(cache:valid_address/2) -> assert(cache:valid_address(Address,I)) ; true),
(\+ cache:valid_address(Address,_) -> assert(cache:valid_address(Address,I)) ; true),
I1 is I + 1,
'$cache_addresses_n'(I1, N).
%
% Check this frozen closure for transaction type.
%
'$new_utxo_closure'(HeapAddress, '$freeze':F) :-
functor(F, _, Arity),
Arity >= 3,
arg(5, F, TxType),
arg(6, F, Args),
arg(8, F, Coin),
arg(1, Coin, Value),
((current_predicate(wallet:new_utxo/4), wallet:new_utxo(TxType, HeapAddress, Value, Args)) -> true
; '$new_utxo'(TxType, HeapAddress, Value, Args)
).
%
% Check for each transaction type, currently only for 'tx1'
%
'$new_utxo'(tx1, HeapAddress, Value, args(_, _, Address)) :-
current_predicate(cache:valid_address/2),
cache:valid_address(Address,_),
((current_predicate(wallet:utxo/4), wallet:utxo(HeapAddress, _,_,_)) -> true
; assert(wallet:utxo(HeapAddress, tx1, Value, Address))).
%
% Quickly get total balance
%
balance(Balance) :-
(current_predicate(wallet:utxo/4) ->
findall(utxo(Value,HeapAddr), wallet:utxo(HeapAddr,_,Value,_), Values),
'$sum_utxo'(Values, 0, Balance)
; Balance = 0
).
%
% Spending logic
%
spend_one(Address, Amount, Fee, FinalTx, ConsumedUtxos) :-
spend_many([Address], [Amount], Fee, FinalTx, ConsumedUtxos).
%
% spend_many is the generic predicate that can be used to
% spend to many addresses with different amounts.
%
spend_many(Addresses, Amounts, Fee, FinalTx, ConsumedUtxos) :-
'$cache_addresses',
% --- Get all available UTXOs from wallet,
findall(utxo(Value,HeapAddress), wallet:utxo(HeapAddress,_,Value,_),Utxos),
% --- Sort all UTXOs on value
sort(Utxos, SortedUtxos),
% --- Compute the total sum of funds that will be spent (excluding fee.)
'$sum'(Amounts, AmountToSpend),
% --- The total sum of funds that will be spent including fee.
TotalAmount is AmountToSpend + Fee,
% --- Find the UTXOs that we'd like to spend.
'$choose'(SortedUtxos, TotalAmount, ChosenUtxos),
% --- Compute its sum
'$sum_utxo'(ChosenUtxos, 0, ChosenSum),
% --- Rest is the remainder that will go back to self
Rest is ChosenSum - TotalAmount,
% --- Compute the list of instructions to open these UTXOs
% --- Signs are the created signatures
'$open_utxos'(ChosenUtxos, Hash, Coins, Signs, Commands),
% --- Append a join instruction (if more than one UTXO)
(Coins = [SumCoin] ->
Commands1 = Commands
; append(Commands, [cjoin(Coins, SumCoin)], Commands1)),
% --- Create txs for all the provided addresses (and funds.)
findall(tx(_, _, tx1, args(_,_,Address),_),
member(Address, Addresses), Txs),
% --- Collect all coin arguments for these txs into SendCoins
'$get_coins'(Txs, SendCoins),
% --- Do we get change?
(Rest > 0 ->
% --- Yes, create a new change address
newkey(_, ChangeAddr),
% --- All the different funds
AllAmounts = [Fee,Rest|Amounts],
% --- Note that SendCoins will be unified with the above
append(Commands1,[csplit(SumCoin, AllAmounts,
[FeeCoin,RestCoin|SendCoins]),
tx(RestCoin, _, tx1, args(_,_,ChangeAddr),_)|Txs],
Commands2)
; AllAmounts = [Fee|Amounts],
append(Commands1, [csplit(SumCoin,AllAmounts,[FeeCoin|SendCoins])|Txs],
Commands2)
),
% --- At this point Commands2 are all the combined instructions we need
% --- Convert list to commas
'$list_to_commas'(Commands2, Command),
% --- The combined command as a self hash predicate (i.e. the script)
'$collect_sign_vars'(Signs, SignVars),
Script = (p(Hash, SignVars, FeeCoin) :- Command),
% --- Compute the hash for this script
ec:hash(Script, HashValue),
% --- Get the required signatures to "run" this script
% --- (without them, the commitment would fail to the global sate.)
% --- One signature per opened UTXO
'$signatures'(Signs, SignVars, HashValue, SignAssigns),
% --- Prepend these signature statements to the script
append(SignAssigns, [Script], Commands3),
% --- Commands3 is the final instruction list, convert it to commas
'$list_to_commas'(Commands3, FinalTx),
% --- Return list of consumed utxos (so the user can remove them from
% --- his wallet.)
findall(H, member(utxo(_,H), ChosenUtxos), ConsumedUtxos), !.
retract_utxos([]).
retract_utxos([HeapAddr|HeapAddrs]) :-
retract(wallet:utxo(HeapAddr, _, _, _)),
retract_utxos(HeapAddrs).
'$list_to_commas'([X], C) :- !, C = X.
'$list_to_commas'([X|Xs], C) :-
C = (X, Y), '$list_to_commas'(Xs, Y).
'$signatures'([], [], _, []).
'$signatures'([sign(tx1, SignVar, PubKeyAddress)|Signs],
[SignVar|SignVars], HashValue,
[(SignVar = Signature)|Commands]) :-
cache:valid_address(PubKeyAddress, Count),
wallet:privkey(Count, PrivKey),
ec:sign(PrivKey, HashValue, Signature),
'$signatures'(Signs, SignVars, HashValue, Commands).
'$collect_sign_vars'([], []).
'$collect_sign_vars'([sign(_,SignVar,_)|Signs],[SignVar|SignVars]) :-
'$collect_sign_vars'(Signs,SignVars).
'$open_utxos'([], _, [], [], []).
'$open_utxos'([utxo(_,HeapAddress)|Utxos], Hash,
[Coin|Coins], [Sign|Signs], Commands) :-
'$open_utxo'(HeapAddress, Hash, Coin, Sign, Commands0),
'$open_utxos'(Utxos, Hash, Coins, Signs, Commands1),
append(Commands0, Commands1, Commands).
'$open_utxo'(HeapAddress, Hash, Coin, Sign, Commands) :-
wallet:utxo(HeapAddress, TxType, _, Data),
'$open_utxo_tx'(TxType, HeapAddress, Data, Hash, Coin, Sign, Commands).
'$open_utxo_tx'(tx1, HeapAddress, PubKeyAddress, Hash, Coin, sign(tx1,Signature,PubKeyAddress),Commands) :-
cache:valid_address(PubKeyAddress, Count),
wallet:pubkey(Count, PubKey),
Commands = [defrost(HeapAddress, Closure,
[Hash, args(Signature,PubKey,PubKeyAddress)]),
arg(7, Closure, Coin)].
'$choose'(_, 0, []) :- !.
'$choose'([utxo(Value,HeapAddress)|Utxos], Funds, Chosen) :-
Value =< Funds, !, Chosen = [utxo(Value,HeapAddress)|ChosenUtxos],
Funds1 is Funds - Value,
'$choose'(Utxos, Funds1, ChosenUtxos).
'$choose'([Utxo], _, [Utxo]) :- !.
'$choose'([Utxo|Utxos], Funds, ChosenUtxos) :-
'$choose'(Utxos, Funds, ChosenUtxos).
'$sum_utxo'([], Sum, Sum).
'$sum_utxo'([utxo(Value,_)|Rest], In, Out) :-
'$sum_utxo'(Rest, In, Out0),
Out is Out0 + Value.
'$get_coins'([], []).
'$get_coins'([tx(Coin,_,_,_,_)|Txs], [Coin|Coins]) :-
'$get_coins'(Txs,Coins).
'$sum'([], 0).
'$sum'([X|Xs], Sum) :-
'$sum'(Xs, Sum0),
Sum is Sum0 + X.
)PROG";
con_cell old_module = current_module();
set_current_module(functor("wallet_impl",0));
try {
load_program(template_source);
} catch (interpreter_exception &ex) {
std::cout << "Error while loading internal wallet_impl source:" << std::endl;
std::cout << ex.what() << std::endl;
} catch (term_parse_exception &ex) {
std::cout << "Error while loading internal wallet_impl source:" << std::endl;
std::cout << term_parser::report_string(*this, ex) << std::endl;
} catch (token_exception &ex) {
std::cout << "Error while loading internal wallet_impl source:" << std::endl;
std::cout << term_parser::report_string(*this, ex) << std::endl;
}
compile();
set_current_module(old_module);
}
bool wallet_interpreter::operator_at_impl(interpreter_base &interp, size_t arity, term args[], const std::string &name, interp::remote_execute_mode mode) {
static con_cell NODE("node", 0);
auto query = args[0];
term else_do;
size_t timeout;
auto where_term = args[1];
std::tie(where_term, else_do, timeout) = interpreter::deconstruct_where(interp, where_term);
if (where_term != NODE) {
return interpreter::operator_at_impl(interp, arity, args, name, mode);
}
std::string where = interp.atom_name(where_term);
#define LL(x) reinterpret_cast<wallet_interpreter &>(interp)
interp::remote_execution_proxy proxy(interp,
[](interpreter_base &interp, term query, term else_do, const std::string &where, interp::remote_execute_mode mode, size_t timeout)
{return LL(interp).get_wallet().execute_at(query, else_do, interp, where, mode, timeout);},
[](interpreter_base &interp, term query, term else_do, const std::string &where, interp::remote_execute_mode mode, size_t timeout)
{return LL(interp).get_wallet().continue_at(query, else_do, interp, where, mode, timeout);},
[](interpreter_base &interp, const std::string &where)
{return LL(interp).get_wallet().delete_instance_at(interp, where);});
proxy.set_mode(mode);
proxy.set_timeout(timeout);
return proxy.start(query, else_do, where);
}
bool wallet_interpreter::operator_at_2(interpreter_base &interp, size_t arity, term args[]) {
return operator_at_impl(interp, arity, args, "@/2", interp::MODE_NORMAL);
}
bool wallet_interpreter::operator_at_silent_2(interpreter_base &interp, size_t arity, term args[]) {
return operator_at_impl(interp, arity, args, "@-/2", interp::MODE_SILENT);
}
bool wallet_interpreter::operator_at_parallel_2(interpreter_base &interp, size_t arity, term args[]) {
return operator_at_impl(interp, arity, args, "@=/2", interp::MODE_PARALLEL);
}
bool wallet_interpreter::save_0(interpreter_base &interp, size_t arity, term args[])
{
auto &w = reinterpret_cast<wallet_interpreter &>(interp).get_wallet();
w.save();
return true;
}
bool wallet_interpreter::auto_save_1(interpreter_base &interp, size_t arity, term args[])
{
auto &w = reinterpret_cast<wallet_interpreter &>(interp).get_wallet();
static con_cell on("on",0);
static con_cell off("off",0);
if (args[0].tag().is_ref()) {
con_cell c = w.is_auto_save() ? on : off;
return interp.unify(args[0], c);
} else if (args[0] == on) {
w.set_auto_save(true);
return true;
} else if (args[0] == off) {
w.set_auto_save(false);
return true;
} else {
return false;
}
}
bool wallet_interpreter::load_0(interpreter_base &interp, size_t arity, term args[])
{
auto &w = reinterpret_cast<wallet_interpreter &>(interp).get_wallet();
w.load();
return true;
}
bool wallet_interpreter::file_1(interpreter_base &interp, size_t arity, term args[])
{
auto &w = reinterpret_cast<wallet_interpreter &>(interp).get_wallet();
if (args[0].tag().is_ref()) {
return interp.unify(args[0], interp.string_to_list(w.get_file()));
} else {
// Switch to a new file
// If the file name is relative,
// use the same directory as the current file.
if (!interp.is_string(args[0])) {
throw interp::interpreter_exception_wrong_arg_type("file/1: Argument must be a string; was " + interp.to_string(args[0]));
}
auto new_file = interp.list_to_string(args[0]);
if (new_file.empty()) {
w.set_file(new_file);
return true;
}
auto new_path = boost::filesystem::path(new_file);
if (new_path.is_relative()) {
auto p = boost::filesystem::path(w.get_file()).parent_path();
p /= new_path;
new_path = p;
}
new_file = new_path.string();
w.save(); // Save current wallet before switching to new file
w.set_file(new_file);
return true;
}
}
bool wallet_interpreter::create_2(interpreter_base &interp, size_t arity, term args[])
{
if (!interp.is_string(args[0])) {
throw interpreter_exception_wrong_arg_type(
"create/2: First argument must be a string (the password); was "
+ interp.to_string(args[0]));
}
term sentence;
ec::mnemonic mn(interp);
if (args[1].tag() == tag_t::REF) {
// Generate new sentence
mn.generate_new(256);
sentence = mn.to_sentence();
} else {
if (!mn.from_sentence(args[1])) {
throw interpreter_exception_wrong_arg_type(
"create/2: Invalid BIP39 sentence; was "
+ interp.to_string(args[1]));
}
sentence = args[1];
}
std::string passwd = interp.list_to_string(args[0]);
auto &w = reinterpret_cast<wallet_interpreter &>(interp).get_wallet();
w.create(passwd, sentence);
return interp.unify(args[1], sentence);
}
}}
|
------------------------------------------------------------------------------
-- Definition of mutual inductive predicates
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --without-K #-}
{-# OPTIONS --no-universe-polymorphism #-}
module FOTC.MutualInductivePredicates where
open import FOTC.Base
------------------------------------------------------------------------------
-- Using mutual inductive predicates
data Even : D → Set
data Odd : D → Set
data Even where
ezero : Even zero
esucc : ∀ {n} → Odd n → Even (succ₁ n)
data Odd where
osucc : ∀ {n} → Even n → Odd (succ₁ n)
-- Non-mutual induction principles
Even-ind : (A : D → Set) →
A zero →
(∀ {n} → Odd n → A (succ₁ n)) →
∀ {n} → Even n → A n
Even-ind A A0 h ezero = A0
Even-ind A A0 h (esucc On) = h On
Odd-ind : (A : D → Set) →
(∀ {n} → Even n → A (succ₁ n)) →
∀ {n} → Odd n → A n
Odd-ind A h (osucc En) = h En
-- Mutual induction principles (from Coq)
Even-mutual-ind :
(A B : D → Set) →
A zero →
(∀ {n} → Odd n → B n → A (succ₁ n)) →
(∀ {n} → Even n → A n → B (succ₁ n)) →
∀ {n} → Even n → A n
Odd-mutual-ind :
(A B : D → Set) →
A zero →
(∀ {n} → Odd n → B n → A (succ₁ n)) →
(∀ {n} → Even n → A n → B (succ₁ n)) →
∀ {n} → Odd n → B n
Even-mutual-ind A B A0 h₁ h₂ ezero = A0
Even-mutual-ind A B A0 h₁ h₂ (esucc On) = h₁ On (Odd-mutual-ind A B A0 h₁ h₂ On)
Odd-mutual-ind A B A0 h₁ h₂ (osucc En) = h₂ En (Even-mutual-ind A B A0 h₁ h₂ En)
module DisjointSum where
-- Using a single inductive predicate on D × D (see
-- Blanchette (2013)).
_+_ : Set → Set → Set
_+_ = _∨_
data EvenOdd : D + D → Set where
eozero : EvenOdd (inj₁ zero)
eoodd : {n : D} → EvenOdd (inj₁ n) → EvenOdd (inj₂ (succ₁ n))
eoeven : {n : D} → EvenOdd (inj₂ n) → EvenOdd (inj₁ (succ₁ n))
-- Induction principle
EvenOdd-ind : (A : D + D → Set) →
A (inj₁ zero) →
({n : D} → A (inj₁ n) → A (inj₂ (succ₁ n))) →
({n : D} → A (inj₂ n) → A (inj₁ (succ₁ n))) →
{n : D + D} → EvenOdd n → A n
EvenOdd-ind A A0 h₁ h₂ eozero = A0
EvenOdd-ind A A0 h₁ h₂ (eoodd EOn) = h₁ (EvenOdd-ind A A0 h₁ h₂ EOn)
EvenOdd-ind A A0 h₁ h₂ (eoeven EOn) = h₂ (EvenOdd-ind A A0 h₁ h₂ EOn)
-------------------------------------------------------------------------
-- From the single inductive predicate to the mutual inductive predicates
-- Even and Odd from EvenOdd.
Even' : D → Set
Even' n = EvenOdd (inj₁ n)
Odd' : D → Set
Odd' n = EvenOdd (inj₂ n)
-- From Even/Odd to Even'/Odd'
Even→Even' : ∀ {n} → Even n → Even' n
Odd→Odd' : ∀ {n} → Odd n → Odd' n
Even→Even' ezero = eozero
Even→Even' (esucc On) = eoeven (Odd→Odd' On)
Odd→Odd' (osucc En) = eoodd (Even→Even' En)
-- From Even'/Odd' to Even/Odd
Even'→Even : ∀ {n} → Even' n → Even n
Odd'→Odd : ∀ {n} → Odd' n → Odd n
-- Requires K.
Even'→Even eozero = ezero
Even'→Even (eoeven h) = esucc (Odd'→Odd h)
Odd'→Odd (eoodd h) = osucc (Even'→Even h)
-- TODO (03 December 2012). From EvenOdd-ind to Even-mutual-ind and
-- Odd-mutual-ind.
module FunctionSpace where
-- Using a single inductive predicate on D → D
data EvenOdd : D → D → Set where
eozero : EvenOdd zero (succ₁ zero)
eoodd : ∀ {m n} → EvenOdd m n → EvenOdd m (succ₁ m)
eoeven : ∀ {m n} → EvenOdd m n → EvenOdd (succ₁ n) n
-- Even and Odd from EvenOdd.
-- Even' : D → Set
-- Even' n = EvenOdd zero (succ₁ zero) ∨ EvenOdd (succ₁ n) n
-- Odd' : D → Set
-- Odd' n = EvenOdd n (succ₁ n)
-- -- From Even/Odd to Even'/Odd'
-- Even→Even' : ∀ {n} → Even n → Even' n
-- Odd→Odd' : ∀ {n} → Odd n → Odd' n
-- Even→Even' ezero = inj₁ eozero
-- Even→Even' (esucc On) = inj₂ (eoeven (Odd→Odd' On))
-- Odd→Odd' (osucc En) = eoodd {!!}
-- -- From Even'/Odd' to Even/Odd
-- Even'→Even : ∀ {n} → Even' n → Even n
-- Odd'→Odd : ∀ {n} → Odd' n → Odd n
-- Even'→Even (inj₁ x) = {!!}
-- Even'→Even (inj₂ x) = {!!}
-- Odd'→Odd h = {!!}
------------------------------------------------------------------------------
-- References
--
-- Blanchette, Jasmin Christian (2013). Relational analysis of
-- (co)inductive predicates, (co)algebraic datatypes, and
-- (co)recursive functions. Software Quality Journal 21.1,
-- pp. 101–126.
|
#include "irods/Hasher.hpp"
#include <iostream>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include "irods/rodsErrorTable.h"
#include "irods/irods_stacktrace.hpp"
namespace irods {
error
Hasher::init( const HashStrategy* _strategy_in ) {
_strategy = _strategy_in;
_stored_error = SUCCESS();
_stored_digest.clear();
return PASS( _strategy->init( _context ) );
}
error
Hasher::update( const std::string& _data ) {
if ( NULL == _strategy ) {
return ERROR( SYS_UNINITIALIZED, "Update called on a hasher that has not been initialized" );
}
if ( !_stored_digest.empty() ) {
return ERROR( SYS_HASH_IMMUTABLE, "Update called on a hasher that has already generated a digest" );
}
error ret = _strategy->update( _data, _context );
return PASS( ret );
}
error
Hasher::digest( std::string& _messageDigest ) {
if ( NULL == _strategy ) {
return ERROR( SYS_UNINITIALIZED, "Digest called on a hasher that has not been initialized" );
}
if ( _stored_digest.empty() ) {
_stored_error = _strategy->digest( _stored_digest, _context );
}
_messageDigest = _stored_digest;
return PASS( _stored_error );
}
}; //namespace irods
|
There is one known planet in the orbit of WASP @-@ 44 : WASP @-@ 44b . The planet is a Hot Jupiter with a mass of 0 @.@ 889 Jupiters . Its radius is 1 @.@ 14 times that of Jupiter . WASP @-@ 44b orbits its host star every 2 @.@ <unk> days at a distance 0 @.@ <unk> AU , approximately 3 @.@ 47 % the mean distance between the Earth and Sun . With an orbital inclination of <unk> , WASP @-@ 44b has an orbit that exists almost edge @-@ on to its host star with respect to Earth . <unk> @-@ 44b 's orbital eccentricity is fit to 0 @.@ 036 , indicating a mostly circular orbit .
|
(*
File: SDS_Automation.thy
Author: Manuel Eberl <[email protected]>
This theory provides a number of commands to automatically derive restrictions on the
results of Social Decision Schemes fulfilling properties like Anonymity, Neutrality,
Ex-post- or SD-efficiency, and SD-Strategy-Proofness.
*)
section \<open>Automatic Fact Gathering for Social Decision Schemes\<close>
theory SDS_Automation
imports
Preference_Profile_Cmd
QSOpt_Exact
"../Social_Decision_Schemes"
keywords
"derive_orbit_equations"
"derive_support_conditions"
"derive_ex_post_conditions"
"find_inefficient_supports"
"prove_inefficient_supports"
"derive_strategyproofness_conditions" :: thy_goal
begin
text \<open>
We now provide the following commands to automatically derive restrictions on the results
of Social Decision Schemes satisfying Anonymity, Neutrality, Efficiency, or Strategy-Proofness:
\begin{description}
\item[@{command derive_orbit_equations}] to derive equalities arising from automorphisms of the
given profiles due to Anonymity and Neutrality
\item[@{command derive_ex_post_conditions}] to find all Pareto losers and the given profiles and
derive the facts that they must be assigned probability 0 by any \textit{ex-post}-efficient
SDS
\item[@{command find_inefficient_supports}] to use Linear Programming to find all minimal SD-inefficient
(but not \textit{ex-post}-inefficient) supports in the given profiles and output a
corresponding witness lottery for each of them
\item[@{command prove_inefficient_supports}] to prove a specified set of support conditions arising from
\textit{ex-post}- or \textit{SD}-Efficiency. For conditions arising from \textit{SD}-Efficiency,
a witness lottery must be specified (e.\,g. as computed by @{command derive_orbit_equations}).
\item[@{command derive_support_conditions}] to automatically find and prove all support conditions
arising from \textit{ex-post-} and \textit{SD}-Efficiency
\item [@{command derive_strategyproofness_conditions}] to automatically derive all conditions
arising from weak Strategy-Proofness and any manipulations between the given preference
profiles. An optional maximum manipulation size can be specified.
\end{description}
All commands except @{command find_inefficient_supports} open a proof state and leave behind
proof obligations for the user to discharge. This should always be possible using the Simplifier,
possibly with a few additional rules, depending on the context.
\<close>
lemma disj_False_right: "P \<or> False \<longleftrightarrow> P" by simp
lemmas multiset_add_ac = add_ac[where ?'a = "'a multiset"]
lemma less_or_eq_real:
"(x::real) < y \<or> x = y \<longleftrightarrow> x \<le> y" "x < y \<or> y = x \<longleftrightarrow> x \<le> y" by linarith+
lemma multiset_Diff_single_normalize:
fixes a c assumes "a \<noteq> c"
shows "({#a#} + B) - {#c#} = {#a#} + (B - {#c#})"
using assms by auto
lemma ex_post_efficient_aux:
assumes "prefs_from_table_wf agents alts xss" "R \<equiv> prefs_from_table xss"
assumes "i \<in> agents" "\<forall>i\<in>agents. y \<succeq>[prefs_from_table xss i] x" "\<not>y \<preceq>[prefs_from_table xss i] x"
shows "ex_post_efficient_sds agents alts sds \<longrightarrow> pmf (sds R) x = 0"
proof
assume ex_post: "ex_post_efficient_sds agents alts sds"
from assms(1,2) have wf: "pref_profile_wf agents alts R"
by (simp add: pref_profile_from_tableI')
from ex_post interpret ex_post_efficient_sds agents alts sds .
from assms(2-) show "pmf (sds R) x = 0"
by (intro ex_post_efficient''[OF wf, of i x y]) simp_all
qed
lemma SD_inefficient_support_aux:
assumes R: "prefs_from_table_wf agents alts xss" "R \<equiv> prefs_from_table xss"
assumes as: "as \<noteq> []" "set as \<subseteq> alts" "distinct as" "A = set as"
assumes ys: "\<forall>x\<in>set (map snd ys). 0 \<le> x" "sum_list (map snd ys) = 1" "set (map fst ys) \<subseteq> alts"
assumes i: "i \<in> agents"
assumes SD1: "\<forall>i\<in>agents. \<forall>x\<in>alts.
sum_list (map snd (filter (\<lambda>y. prefs_from_table xss i x (fst y)) ys)) \<ge>
real (length (filter (prefs_from_table xss i x) as)) / real (length as)"
assumes SD2: "\<exists>x\<in>alts. sum_list (map snd (filter (\<lambda>y. prefs_from_table xss i x (fst y)) ys)) >
real (length (filter (prefs_from_table xss i x) as)) / real (length as)"
shows "sd_efficient_sds agents alts sds \<longrightarrow> (\<exists>x\<in>A. pmf (sds R) x = 0)"
proof
assume "sd_efficient_sds agents alts sds"
from R have wf: "pref_profile_wf agents alts R"
by (simp add: pref_profile_from_tableI')
then interpret pref_profile_wf agents alts R .
interpret sd_efficient_sds agents alts sds by fact
from ys have ys': "pmf_of_list_wf ys" by (intro pmf_of_list_wfI) auto
{
fix i x assume "x \<in> alts" "i \<in> agents"
with ys' have "lottery_prob (pmf_of_list ys) (preferred_alts (R i) x) =
sum_list (map snd (filter (\<lambda>y. prefs_from_table xss i x (fst y)) ys))"
by (subst measure_pmf_of_list) (simp_all add: preferred_alts_def R)
} note A = this
{
fix i x assume "x \<in> alts" "i \<in> agents"
with as have "lottery_prob (pmf_of_set (set as)) (preferred_alts (R i) x) =
real (card (set as \<inter> preferred_alts (R i) x)) / real (card (set as))"
by (subst measure_pmf_of_set) simp_all
also have "set as \<inter> preferred_alts (R i) x = set (filter (\<lambda>y. R i x y) as)"
by (auto simp add: preferred_alts_def)
also have "card \<dots> = length (filter (\<lambda>y. R i x y) as)"
by (intro distinct_card distinct_filter assms)
also have "card (set as) = length as" by (intro distinct_card assms)
finally have "lottery_prob (pmf_of_set (set as)) (preferred_alts (R i) x) =
real (length (filter (prefs_from_table xss i x) as)) / real (length as)"
by (simp add: R)
} note B = this
from wf show "\<exists>x\<in>A. pmf (sds R) x = 0"
proof (rule SD_inefficient_support')
from ys ys' show lottery1: "pmf_of_list ys \<in> lotteries" by (intro pmf_of_list_lottery)
show i: "i \<in> agents" by fact
from as have lottery2: "pmf_of_set (set as) \<in> lotteries"
by (intro pmf_of_set_lottery) simp_all
from i as SD2 lottery1 lottery2 show "\<not>SD (R i) (pmf_of_list ys) (pmf_of_set A)"
by (subst preorder_on.SD_preorder[of alts]) (auto simp: A B not_le)
from as SD1 lottery1 lottery2
show "\<forall>i\<in>agents. SD (R i) (pmf_of_set A) (pmf_of_list ys)"
by safe (auto simp: preorder_on.SD_preorder[of alts] A B)
qed (insert as, simp_all)
qed
definition pref_classes where
"pref_classes alts le = preferred_alts le ` alts - {alts}"
primrec pref_classes_lists where
"pref_classes_lists [] = {}"
| "pref_classes_lists (xs#xss) = insert (\<Union>(set (xs#xss))) (pref_classes_lists xss)"
fun pref_classes_lists_aux where
"pref_classes_lists_aux acc [] = {}"
| "pref_classes_lists_aux acc (xs#xss) = insert acc (pref_classes_lists_aux (acc \<union> xs) xss)"
lemma pref_classes_lists_append:
"pref_classes_lists (xs @ ys) = (\<union>) (\<Union>(set ys)) ` pref_classes_lists xs \<union> pref_classes_lists ys"
by (induction xs) auto
lemma pref_classes_lists_aux:
assumes "is_weak_ranking xss" "acc \<inter> (\<Union>(set xss)) = {}"
shows "pref_classes_lists_aux acc xss =
(insert acc ((\<lambda>A. A \<union> acc) ` pref_classes_lists (rev xss)) - {acc \<union> \<Union>(set xss)})"
using assms
proof (induction acc xss rule: pref_classes_lists_aux.induct [case_names Nil Cons])
case (Cons acc xs xss)
from Cons.prems have A: "acc \<inter> (xs \<union> \<Union>(set xss)) = {}" "xs \<noteq> {}"
by (simp_all add: is_weak_ranking_Cons)
from Cons.prems have "pref_classes_lists_aux (acc \<union> xs) xss =
insert (acc \<union> xs) ((\<lambda>A. A \<union> (acc \<union> xs)) `pref_classes_lists (rev xss)) -
{acc \<union> xs \<union> \<Union>(set xss)}"
by (intro Cons.IH) (auto simp: is_weak_ranking_Cons)
with Cons.prems have "pref_classes_lists_aux acc (xs # xss) =
insert acc (insert (acc \<union> xs) ((\<lambda>A. A \<union> (acc \<union> xs)) ` pref_classes_lists (rev xss)) -
{acc \<union> (xs \<union> \<Union>(set xss))})"
by (simp_all add: is_weak_ranking_Cons pref_classes_lists_append image_image Un_ac)
also from A have "\<dots> = insert acc (insert (acc \<union> xs) ((\<lambda>x. x \<union> (acc \<union> xs)) `
pref_classes_lists (rev xss))) - {acc \<union> (xs \<union> \<Union>(set xss))}"
by blast
finally show ?case
by (simp_all add: pref_classes_lists_append image_image Un_ac)
qed simp_all
lemma pref_classes_list_aux_hd_tl:
assumes "is_weak_ranking xss" "xss \<noteq> []"
shows "pref_classes_lists_aux (hd xss) (tl xss) = pref_classes_lists (rev xss) - {\<Union>(set xss)}"
proof -
from assms have A: "xss = hd xss # tl xss" by simp
from assms have "hd xss \<inter> \<Union>(set (tl xss)) = {} \<and> is_weak_ranking (tl xss)"
by (subst (asm) A, subst (asm) is_weak_ranking_Cons) simp_all
hence "pref_classes_lists_aux (hd xss) (tl xss) =
insert (hd xss) ((\<lambda>A. A \<union> hd xss) ` pref_classes_lists (rev (tl xss))) -
{hd xss \<union> \<Union>(set (tl xss))}" by (intro pref_classes_lists_aux) simp_all
also have "hd xss \<union> \<Union>(set (tl xss)) = \<Union>(set xss)" by (subst (3) A, subst set_simps) simp_all
also have "insert (hd xss) ((\<lambda>A. A \<union> hd xss) ` pref_classes_lists (rev (tl xss))) =
pref_classes_lists (rev (tl xss) @ [hd xss])"
by (subst pref_classes_lists_append) auto
also have "rev (tl xss) @ [hd xss] = rev xss" by (subst (3) A) (simp only: rev.simps)
finally show ?thesis .
qed
lemma pref_classes_of_weak_ranking_aux:
assumes "is_weak_ranking xss"
shows "of_weak_ranking_Collect_ge xss ` (\<Union>(set xss)) = pref_classes_lists xss"
proof safe
fix X x assume "x \<in> X" "X \<in> set xss"
with assms show "of_weak_ranking_Collect_ge xss x \<in> pref_classes_lists xss"
by (induction xss) (auto simp: is_weak_ranking_Cons of_weak_ranking_Collect_ge_Cons')
next
fix x assume "x \<in> pref_classes_lists xss"
with assms show "x \<in> of_weak_ranking_Collect_ge xss ` \<Union>(set xss)"
proof (induction xss)
case (Cons xs xss)
from Cons.prems consider "x = xs \<union> \<Union>(set xss)" | "x \<in> pref_classes_lists xss" by auto
thus ?case
proof cases
assume "x = xs \<union> \<Union>(set xss)"
with Cons.prems show ?thesis
by (auto simp: is_weak_ranking_Cons of_weak_ranking_Collect_ge_Cons')
next
assume x: "x \<in> pref_classes_lists xss"
from Cons.prems x have "x \<in> of_weak_ranking_Collect_ge xss ` \<Union>(set xss)"
by (intro Cons.IH) (simp_all add: is_weak_ranking_Cons)
moreover from Cons.prems have "xs \<inter> \<Union>(set xss) = {}"
by (simp add: is_weak_ranking_Cons)
ultimately have "x \<in> of_weak_ranking_Collect_ge xss `
((xs \<union> \<Union>(set xss)) \<inter> {x. x \<notin> xs})" by blast
thus ?thesis by (simp add: of_weak_ranking_Collect_ge_Cons')
qed
qed simp_all
qed
lemma eval_pref_classes_of_weak_ranking:
assumes "\<Union>(set xss) = alts" "is_weak_ranking xss" "alts \<noteq> {}"
shows "pref_classes alts (of_weak_ranking xss) = pref_classes_lists_aux (hd xss) (tl xss)"
proof -
have "pref_classes alts (of_weak_ranking xss) =
preferred_alts (of_weak_ranking xss) ` (\<Union>(set (rev xss))) - {\<Union>(set xss)}"
by (simp add: pref_classes_def assms)
also {
have "of_weak_ranking_Collect_ge (rev xss) ` (\<Union>(set (rev xss))) = pref_classes_lists (rev xss)"
using assms by (intro pref_classes_of_weak_ranking_aux) simp_all
also have "of_weak_ranking_Collect_ge (rev xss) = preferred_alts (of_weak_ranking xss)"
by (intro ext) (simp_all add: of_weak_ranking_Collect_ge_def preferred_alts_def)
finally have "preferred_alts (of_weak_ranking xss) ` (\<Union>(set (rev xss))) =
pref_classes_lists (rev xss)" .
}
also from assms have "pref_classes_lists (rev xss) - {\<Union>(set xss)} =
pref_classes_lists_aux (hd xss) (tl xss)"
by (intro pref_classes_list_aux_hd_tl [symmetric]) auto
finally show ?thesis by simp
qed
context preorder_on
begin
lemma SD_iff_pref_classes:
assumes "p \<in> lotteries_on carrier" "q \<in> lotteries_on carrier"
shows "p \<preceq>[SD(le)] q \<longleftrightarrow>
(\<forall>A\<in>pref_classes carrier le. measure_pmf.prob p A \<le> measure_pmf.prob q A)"
proof safe
fix A assume "p \<preceq>[SD(le)] q" "A \<in> pref_classes carrier le"
thus "measure_pmf.prob p A \<le> measure_pmf.prob q A"
by (auto simp: SD_preorder pref_classes_def)
next
assume A: "\<forall>A\<in>pref_classes carrier le. measure_pmf.prob p A \<le> measure_pmf.prob q A"
show "p \<preceq>[SD(le)] q"
proof (rule SD_preorderI)
fix x assume x: "x \<in> carrier"
show "measure_pmf.prob p (preferred_alts le x)
\<le> measure_pmf.prob q (preferred_alts le x)"
proof (cases "preferred_alts le x = carrier")
case False
with x have "preferred_alts le x \<in> pref_classes carrier le"
unfolding pref_classes_def by (intro DiffI imageI) simp_all
with A show ?thesis by simp
next
case True
from assms have "measure_pmf.prob p carrier = 1" "measure_pmf.prob q carrier = 1"
by (auto simp: measure_pmf.prob_eq_1 lotteries_on_def AE_measure_pmf_iff)
with True show ?thesis by simp
qed
qed (insert assms, simp_all)
qed
end
lemma (in strategyproof_an_sds) strategyproof':
assumes wf: "is_pref_profile R" "total_preorder_on alts Ri'" and i: "i \<in> agents"
shows "(\<exists>A\<in>pref_classes alts (R i). lottery_prob (sds (R(i := Ri'))) A <
lottery_prob (sds R) A) \<or>
(\<forall>A\<in>pref_classes alts (R i). lottery_prob (sds (R(i := Ri'))) A =
lottery_prob (sds R) A)"
proof -
from wf(1) interpret R: pref_profile_wf agents alts R .
from i interpret total_preorder_on alts "R i" by simp
from assms have "\<not> manipulable_profile R i Ri'" by (intro strategyproof)
moreover from wf i have "sds R \<in> lotteries" "sds (R(i := Ri')) \<in> lotteries"
by (simp_all add: sds_wf)
ultimately show ?thesis
by (fastforce simp: manipulable_profile_def strongly_preferred_def
SD_iff_pref_classes not_le not_less)
qed
lemma pref_classes_lists_aux_finite:
"A \<in> pref_classes_lists_aux acc xss \<Longrightarrow> finite acc \<Longrightarrow> (\<And>A. A \<in> set xss \<Longrightarrow> finite A)
\<Longrightarrow> finite A"
by (induction acc xss rule: pref_classes_lists_aux.induct) auto
lemma strategyproof_aux:
assumes wf: "prefs_from_table_wf agents alts xss1" "R1 = prefs_from_table xss1"
"prefs_from_table_wf agents alts xss2" "R2 = prefs_from_table xss2"
assumes sds: "strategyproof_an_sds agents alts sds" and i: "i \<in> agents" and j: "j \<in> agents"
assumes eq: "R1(i := R2 j) = R2" "the (map_of xss1 i) = xs"
"pref_classes_lists_aux (hd xs) (tl xs) = ps"
shows "(\<exists>A\<in>ps. (\<Sum>x\<in>A. pmf (sds R2) x) < (\<Sum>x\<in>A. pmf (sds R1) x)) \<or>
(\<forall>A\<in>ps. (\<Sum>x\<in>A. pmf (sds R2) x) = (\<Sum>x\<in>A. pmf (sds R1) x))"
proof -
from sds interpret strategyproof_an_sds agents alts sds .
let ?Ri' = "R2 j"
from wf j have wf': "is_pref_profile R1" "total_preorder_on alts ?Ri'"
by (auto intro: pref_profile_from_tableI pref_profile_wf.prefs_wf'(1))
from wf(1) i have "i \<in> set (map fst xss1)" by (simp add: prefs_from_table_wf_def)
with prefs_from_table_wfD(3)[OF wf(1)] eq
have "xs \<in> set (map snd xss1)" by force
note xs = prefs_from_table_wfD(2)[OF wf(1)] prefs_from_table_wfD(5,6)[OF wf(1) this]
{
fix p A assume A: "A \<in> pref_classes_lists_aux (hd xs) (tl xs)"
from xs have "xs \<noteq> []" by auto
with xs have "finite A"
by (intro pref_classes_lists_aux_finite[OF A])
(auto simp: is_finite_weak_ranking_def list.set_sel)
hence "lottery_prob p A = (\<Sum>x\<in>A. pmf p x)"
by (rule measure_measure_pmf_finite)
} note A = this
from strategyproof'[OF wf' i] eq have
"(\<exists>A\<in>pref_classes alts (R1 i). lottery_prob (sds R2) A < lottery_prob (sds R1) A) \<or>
(\<forall>A\<in>pref_classes alts (R1 i). lottery_prob (sds R2) A = lottery_prob (sds R1) A)"
by simp
also from wf eq i have "R1 i = of_weak_ranking xs"
by (simp add: prefs_from_table_map_of)
also from xs have "pref_classes alts (of_weak_ranking xs) = pref_classes_lists_aux (hd xs) (tl xs)"
unfolding is_finite_weak_ranking_def by (intro eval_pref_classes_of_weak_ranking) simp_all
finally show ?thesis by (simp add: A eq)
qed
lemma strategyproof_aux':
assumes wf: "prefs_from_table_wf agents alts xss1" "R1 \<equiv> prefs_from_table xss1"
"prefs_from_table_wf agents alts xss2" "R2 \<equiv> prefs_from_table xss2"
assumes sds: "strategyproof_an_sds agents alts sds" and i: "i \<in> agents" and j: "j \<in> agents"
assumes perm: "list_permutes ys alts"
defines "\<sigma> \<equiv> permutation_of_list ys" and "\<sigma>' \<equiv> inverse_permutation_of_list ys"
defines "xs \<equiv> the (map_of xss1 i)"
defines xs': "xs' \<equiv> map ((`) \<sigma>) (the (map_of xss2 j))"
defines "Ri' \<equiv> of_weak_ranking xs'"
assumes distinct_ps: "\<forall>A\<in>ps. distinct A"
assumes eq: "mset (map snd xss1) - {#the (map_of xss1 i)#} + {#xs'#} =
mset (map (map ((`) \<sigma>) \<circ> snd) xss2)"
"pref_classes_lists_aux (hd xs) (tl xs) = set ` ps"
shows "list_permutes ys alts \<and>
((\<exists>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (sds R2) (\<sigma>' x)) < (\<Sum>x\<leftarrow>A. pmf (sds R1) x)) \<or>
(\<forall>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (sds R2) (\<sigma>' x)) = (\<Sum>x\<leftarrow>A. pmf (sds R1) x)))"
(is "_ \<and> ?th")
proof
from perm have perm': "\<sigma> permutes alts" by (simp add: \<sigma>_def)
from sds interpret strategyproof_an_sds agents alts sds .
from wf(3) j have "j \<in> set (map fst xss2)" by (simp add: prefs_from_table_wf_def)
with prefs_from_table_wfD(3)[OF wf(3)]
have xs'_aux: "the (map_of xss2 j) \<in> set (map snd xss2)" by force
with wf(3) have xs'_aux': "is_finite_weak_ranking (the (map_of xss2 j))"
by (auto simp: prefs_from_table_wf_def)
hence *: "is_weak_ranking xs'" unfolding xs'
by (intro is_weak_ranking_map_inj permutes_inj_on[OF perm'])
(auto simp add: is_finite_weak_ranking_def)
moreover from * xs'_aux' have "is_finite_weak_ranking xs'"
by (auto simp: xs' is_finite_weak_ranking_def)
moreover from prefs_from_table_wfD(5)[OF wf(3) xs'_aux]
have "\<Union>(set xs') = alts" unfolding xs'
by (simp add: image_Union [symmetric] permutes_image[OF perm'])
ultimately have wf_xs': "is_weak_ranking xs'" "is_finite_weak_ranking xs'" "\<Union>(set xs') = alts"
by (simp_all add: is_finite_weak_ranking_def)
from this wf j have wf': "is_pref_profile R1" "total_preorder_on alts Ri'"
"is_pref_profile R2" "finite_total_preorder_on alts Ri'"
unfolding Ri'_def by (auto intro: pref_profile_from_tableI pref_profile_wf.prefs_wf'(1)
total_preorder_of_weak_ranking)
interpret R1: pref_profile_wf agents alts R1 by fact
interpret R2: pref_profile_wf agents alts R2 by fact
from wf(1) i have "i \<in> set (map fst xss1)" by (simp add: prefs_from_table_wf_def)
with prefs_from_table_wfD(3)[OF wf(1)] eq(2)
have "xs \<in> set (map snd xss1)" unfolding xs_def by force
note xs = prefs_from_table_wfD(2)[OF wf(1)] prefs_from_table_wfD(5,6)[OF wf(1) this]
from wf i wf' wf_xs' xs eq
have eq': "anonymous_profile (R1(i := Ri')) = image_mset (map ((`) \<sigma>)) (anonymous_profile R2)"
by (subst R1.anonymous_profile_update)
(simp_all add: Ri'_def weak_ranking_of_weak_ranking mset_map multiset.map_comp xs_def
anonymise_prefs_from_table prefs_from_table_map_of)
{
fix p A assume A: "A \<in> pref_classes_lists_aux (hd xs) (tl xs)"
from xs have "xs \<noteq> []" by auto
with xs have "finite A"
by (intro pref_classes_lists_aux_finite[OF A])
(auto simp: is_finite_weak_ranking_def list.set_sel)
hence "lottery_prob p A = (\<Sum>x\<in>A. pmf p x)"
by (rule measure_measure_pmf_finite)
} note A = this
from strategyproof'[OF wf'(1,2) i] eq' have
"(\<exists>A\<in>pref_classes alts (R1 i). lottery_prob (sds (R1(i := Ri'))) A < lottery_prob (sds R1) A) \<or>
(\<forall>A\<in>pref_classes alts (R1 i). lottery_prob (sds (R1(i := Ri'))) A = lottery_prob (sds R1) A)"
by simp
also from eq' i have "sds (R1(i := Ri')) = map_pmf \<sigma> (sds R2)"
unfolding \<sigma>_def by (intro sds_anonymous_neutral permutation_of_list_permutes perm wf'
pref_profile_wf.wf_update eq)
also from wf eq i have "R1 i = of_weak_ranking xs"
by (simp add: prefs_from_table_map_of xs_def)
also from xs have "pref_classes alts (of_weak_ranking xs) = pref_classes_lists_aux (hd xs) (tl xs)"
unfolding is_finite_weak_ranking_def by (intro eval_pref_classes_of_weak_ranking) simp_all
finally have "(\<exists>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (map_pmf \<sigma> (sds R2)) x) < (\<Sum>x\<leftarrow>A. pmf (sds R1) x)) \<or>
(\<forall>A\<in>ps. (\<Sum>x\<leftarrow>A. pmf (map_pmf \<sigma> (sds R2)) x) = (\<Sum>x\<leftarrow>A. pmf (sds R1) x))"
using distinct_ps
by (simp add: A eq sum.distinct_set_conv_list del: measure_map_pmf)
also from perm' have "pmf (map_pmf \<sigma> (sds R2)) = (\<lambda>x. pmf (sds R2) (inv \<sigma> x))"
using pmf_map_inj'[of \<sigma> _ "inv \<sigma> x" for x]
by (simp add: fun_eq_iff permutes_inj permutes_inverses)
also from perm have "inv \<sigma> = \<sigma>'" unfolding \<sigma>_def \<sigma>'_def
by (rule inverse_permutation_of_list_correct [symmetric])
finally show ?th .
qed fact+
ML_file \<open>randomised_social_choice.ML\<close>
ML_file \<open>sds_automation.ML\<close>
end
|
############################################################################################
"""
$(TYPEDEF)
Default Configuration for NUTS sampler.
# Fields
$(TYPEDFIELDS)
"""
struct ConfigNUTS{K<:KineticEnergy} <: AbstractConfiguration
## Global targets
"Target Acceptance Rate"
δ::Float64
"Default size for tuning iterations in each cycle."
window::ConfigTuningWindow
"Kinetic Energy used in Hamiltonian: GaussianKineticEnergy"
energy::K
function ConfigNUTS(
δ::Float64,
window::ConfigTuningWindow,
energy::K,
) where {K<:KineticEnergy}
@argcheck 0.0 < δ <= 1.0 "Acceptance rate not bounded between 0 and 1"
return new{K}(
δ,
window,
energy
)
end
end
"""
$(SIGNATURES)
Initialize NUTS custom configurations.
# Examples
```julia
```
"""
function init(
::Type{AbstractConfiguration},
mcmc::Type{NUTS},
objective::Objective,
proposalconfig::ConfigProposal;
## Target Acceptance Rate
δ=0.80,
## MCMC Phase tune variables based on standard HMC best practice target acceptance rate of 0.80
window= ConfigTuningWindow(
[1, 5, 1],
[75, 50, 25],
[Warmup(), Adaptionˢˡᵒʷ(), Adaptionᶠᵃˢᵗ(), Exploration()]
),
## Kinetic energy in Hamiltonian
energy=GaussianKineticEnergy(
init(
objective.model.info.reconstruct.default.output, proposalconfig.metric, length(objective.tagged)
)...,
)
)
return ConfigNUTS(
δ,
window,
energy
)
end
############################################################################################
#export
export ConfigNUTS
|
(*===========================================================================
Auxiliary lemmas for Hoare triples on *programs*
===========================================================================*)
Require Import ssreflect ssrbool ssrnat eqtype seq fintype.
Require Import procstate procstatemonad bitsops bitsprops bitsopsprops.
Require Import SPred septac spec spectac safe pointsto cursor instr reader instrcodec.
Require Import Setoid RelationClasses Morphisms.
Require Import program basic antiframe.
(* Morphism for program equivalence *)
Global Instance basic_progEq_m:
Proper (lequiv ==> progEq ==> lequiv ==> lequiv) basic.
Proof.
move => P P' HP c c' Hc Q Q' HQ. rewrite {1}/basic.
setoid_rewrite HQ. setoid_rewrite HP. setoid_rewrite Hc. reflexivity.
Qed.
(* Skip rule *)
Lemma basic_skip P: |-- basic P prog_skip P.
Proof.
rewrite /basic. specintros => i j.
unfold_program.
specintro => H.
rewrite emp_unit spec_reads_eq_at; rewrite <- emp_unit.
rewrite spec_at_emp. inversion H. subst. by apply limplValid.
Qed.
(* Sequencing rule *)
Lemma basic_seq (c1 c2: program) S P Q R:
S |-- basic P c1 Q ->
S |-- basic Q c2 R ->
S |-- basic P (c1;; c2) R.
Proof.
rewrite /basic. move=> Hc1 Hc2. specintros => i j.
unfold_program.
specintro => i'. rewrite -> memIsNonTop. specintros => p' EQ. subst.
specapply Hc1. by ssimpl.
specapply Hc2. by ssimpl.
rewrite <-spec_reads_frame. apply: limplAdj. apply: landL2.
by rewrite spec_at_emp.
Qed.
(* Scoped label rule *)
Lemma basic_local S P c Q:
(forall l, S |-- basic P (c l) Q) ->
S |-- basic P (prog_declabel c) Q.
Proof.
move=> H. rewrite /basic. rewrite /memIs /=. specintros => i j l.
specialize (H l). lforwardR H.
- apply lforallL with i. apply lforallL with j. reflexivity.
apply H.
Qed.
(* Needed to avoid problems with coercions *)
Lemma basic_instr S P i Q :
S |-- basic P i Q ->
S |-- basic P (prog_instr i) Q.
Proof. done. Qed.
Lemma regMissingIn_program r (i j: DWORD) (c: program):
regMissingIn r (i -- j :-> c).
Proof.
move: i j.
induction c => i j; unfold_program; by eauto with reg_not_in.
Qed.
Hint Resolve regMissingIn_program : reg_not_in.
Lemma antiframe_register_basic (r: Reg) P Q c:
regNotFree r P ->
(forall v, |-- basic (P ** r~=v) c (Q ** r~=v)) ->
|-- basic P c Q.
Proof.
rewrite /basic /spec_reads => HregNotFree H.
specintros => i j s Hs. autorewrite with push_at. apply limplValid.
apply antiframe_register with r.
- apply regNotFree_sepSP.
+ apply regNotFree_sepSP; last done. apply regNotFree_reg.
by destruct r; first destruct r.
+ apply regMissingIn_regNotFree. rewrite ->Hs. auto with reg_not_in.
- apply _.
- move => v. specialize (H v). lforwardR H.
{ apply lforallL with i. apply lforallL with j. apply lforallL with s.
apply lpropimplL; first done. reflexivity. }
specapply H; first by ssimpl. autorewrite with push_at.
rewrite spec_reads_emp. cancel1. by ssimpl.
Qed.
(* Attempts to apply "basic" lemma on a single command (basic_basic) or
on the first of a sequence (basic_seq). Note that it attempts to use sbazooka
to discharge subgoals, so be careful if existentials are exposed in the goal --
they will be instantiated! *)
Hint Unfold not : basicapply.
Hint Rewrite eq_refl : basicapply.
Ltac instRule R H :=
move: (R) => H;
repeat (autounfold with basicapply in H);
eforalls H;
autorewrite with push_at in H.
(* This is all very sensitive to use of "e" versions of apply/exact. Beware! *)
(* We ensure that we leave at most one goal remaining. *)
Ltac basicatom R tacfin :=
lazymatch goal with
| |- |-- basic ?P (prog_instr ?i) ?Q =>
(eapply basic_basic; first eapply basic_instr; [ eexact R | tacfin .. | try tacfin ])
| _ => eapply basic_basic; [ eexact R | tacfin .. | try tacfin ]
end.
Ltac basicseq R tacfin :=
lazymatch goal with
| |- |-- basic ?P (prog_seq ?p1 ?p2) ?Q => (eapply basic_seq; first basicatom R tacfin)
| _ => basicatom R tacfin
end.
Ltac basicapply R tac tacfin :=
let Hlem := fresh "Hlem" in
instRule R Hlem;
tac Hlem;
first basicseq Hlem tacfin;
clear Hlem.
Tactic Notation "basicapply" open_constr(R) "using" tactic3(tac) "side" "conditions" tactic(tacfin) := basicapply R tac tacfin.
Tactic Notation "basicapply" open_constr(R) "using" tactic3(tac) := basicapply R using (tac) side conditions by autounfold with spred; sbazooka.
Tactic Notation "basicapply" open_constr(R) "side" "conditions" tactic(tacfin) := basicapply R using (fun Hlem => autorewrite with basicapply in Hlem) side conditions tacfin.
Tactic Notation "basicapply" open_constr(R) := basicapply R using (fun Hlem => autorewrite with basicapply in Hlem).
(** Variant of [basicapply] that doesn't require that the side conditions be fully solved. *)
Tactic Notation "try_basicapply" open_constr(R) "using" tactic3(tac) := basicapply R using (tac) side conditions autounfold with spred; sbazooka.
Tactic Notation "try_basicapply" open_constr(R) := try_basicapply R using (fun Hlem => autorewrite with basicapply in Hlem).
|
#' @title Summary statistics for a quantitative variable
#' @description This function provides descriptive statistics for a quantitative
#' variable alone or seperately by groups. Any function that returns a single
#' numeric value can bue used.
#' @param data data frame
#' @param x numeric variable in data (unquoted)
#' @param statistics statistics to calculate (any function that produces a
#' numeric value), Default: \code{c("n", "mean", "sd")}
#' @param na.rm if \code{TRUE}, delete cases with missing values on x and or grouping
#' variables, Default: \code{TRUE}
#' @param digits number of decimal digits to print, Default: 2
#' @param ... list of grouping variables
#' @importFrom purrr map_dfc
#' @import dplyr
#' @importFrom purrr map_dfc
#' @import rlang
#' @import haven
#' @return a data frame, where columns are grouping variables (optional) and
#' statistics
#' @examples
#' # If no keyword arguments are provided, default values are used
#' qstats(mtcars, mpg, am, gear)
#'
#' # You can supply as many (or no) grouping variables as needed
#' qstats(mtcars, mpg)
#'
#' qstats(mtcars, mpg, am, cyl)
#'
#' # You can specify your own functions (e.g., median,
#' # median absolute deviation, minimum, maximum))
#' qstats(mtcars, mpg, am, gear,
#' stats = c("median", "mad", "min", "max"))
#' @rdname qstats
#' @export
qstats <- function(data, x, ...){
x <- enquo(x)
dots <- enquos(...)
if(!is.numeric(data %>% pull(!!x))){
stop("data$x is not numeric")
}
## stats
median <- function(xs){
ys <- sort(xs)
m <- length(xs)/2
if(length(xs) %% 2 == 0){
mean(c(ys[m], ys[m+1]))
} else {
ys[floor(m) + 1]
}
}
n <- function(xs){
length(xs)
}
## Auxiliary functions
my_sum <- function(data, col, cus_sum) {
col <- enquo(col)
cus_sum_name <- cus_sum
cus_sum <- rlang::as_function(cus_sum)
data %>%
summarise(!!cus_sum_name := cus_sum(!!col))
}
my_sums <- function(data, col, cus_sums) {
col <- enquo(col)
purrr::map_dfc(cus_sums, my_sum, data = data, col = !!col)
}
extract_list_unnamed_elems <- function(my_list){
unnamed_idxs <- (1:length(my_list))[names(my_list) == ""]
my_list[unnamed_idxs]
}
stats <- if(is.null(dots$stats)) {
c("n", "mean", "sd")
} else {
eval(rlang::quo_get_expr(dots$stats))
}
na.rm <- if(is.null(dots$na.rm)) TRUE else rlang::quo_get_expr(dots$na.rm)
digits <- if(is.null(dots$digits)) 2 else rlang::quo_get_expr(dots$digits)
grouping_vars <- extract_list_unnamed_elems(dots)
data <- data %>% select(!!x, !!!grouping_vars)
if(na.rm){
data <- stats::na.omit(data)
}
data %>%
mutate_at(vars(!!!grouping_vars), as_factor) %>%
group_by(!!!grouping_vars) %>%
group_modify(~my_sums(.x, col = !!x, cus_sums = stats)) %>%
mutate_at(vars(-group_cols()), ~ round(as.double(.x), digits = digits)) %>%
ungroup() %>% as.data.frame()
}
|
Formal statement is: lemma to_fract_0 [simp]: "to_fract 0 = 0" Informal statement is: $\text{to\_fract}(0) = 0$. |
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
neg.doPeel := true;
#F CopyPropagate(<code>)
#F Performs copy propagation and strength reduction
#F If <code> has IFs it MUST be in SSA form, i.e.,
#F SSA(<code>) must be run first.
#F
Class(SubstVarsRules, RuleSet, rec(
create := (self, varmap) >> Inherit(self,
rec(
rules := rec(
v := Rule(@(1,var,e->IsBound(varmap.(e.id))), e -> varmap.(e.id))
)
)).compile()
));
# apply linear normalization to index expressions, this will simplify cases like
# 3x + 2x = 5x
#
Class(SimpIndicesRules, RuleSet, rec(
create := (self, opts) >> Inherit(self,
rec(
rules := rec(
simp_indices := Rule(@(1, opts.simpIndicesInside), x -> GroupSummandsExp(x))
)
)).compile()
));
# Transforms nth(x, idx) to deref(x + idx)
Class(RulesDerefNth, RuleSet);
RewriteRules(RulesDerefNth, rec(
deref_nth := Rule(
[nth, @(1).cond( x -> not (x _is [Value, param]) or not IsBound(x.value)), @(2)],
e -> let(
b := @(1).val, idx := @(2).val,
Cond(
ObjId(idx) = add, deref(ApplyFunc(add, [b] :: idx.args)),
ObjId(idx) = sub, deref(ApplyFunc(add, [b] :: [idx.args[1], neg(idx.args[2])])),
deref(b + idx))))
));
# sorts the incoming array of assignments by the offset of the
# variable being assigned TO, rather than the one assigned FROM.
# improves locality hence cache performance.
_sortByIdx := function(array)
local newarray;
newarray := Copy(array);
SortParallel(
List(array, e -> Double(SubString(e.args[2].id, 2))),
newarray
);
return newarray;
end;
CopyTab := function (t)
local r, a;
r := tab();
for a in NSFields(t) do
r.(a):=Copy(t.(a));
od;
return r;
end;
Class(CopyPropagate, CSE, rec(
propagate := (self, cloc, cexp) >> let(cebase := ObjId(cexp),
((cebase in [var, Value, noneExp])
or (self.propagateNth and cebase in [nth, deref] and IsValue(cexp.idx))
or (IsBound(self.opts.autoinline) and IsBound(cloc.succ) and Length(cloc.succ)<=1)
or (IsBound(cloc.succ) and Length(cloc.succ)=0))),
# sreduce_and_subst(c.exp) can lead to inf loop - why?
procRHS := (self, x) >> self.sreduce(self.subst3(self.sreduce(self.subst2(x)))),
procLHS := (self, x) >> self.sreduce3(self.sreduce(self.subst2(x))),
# NOTE: explain this
prepVarMap := meth(self, initial_map, do_sreduce, do_init_scalarized, do_idx)
local v, varmap, rs_subst, rs2, rs_deref, rs_idx;
self.varmap := initial_map;
if do_sreduce then
# do_idx is done initially, at the same time as scalarization
# deref prevents scalarization, so must be disabled at that moment
rs_deref := When(not do_idx and self.opts.useDeref, RulesDerefNth, EmptyRuleSet);
rs_idx := When(do_idx, SimpIndicesRules.create(self.opts), EmptyRuleSet);
rs_subst := SubstVarsRules.create(self.varmap);
rs2 := MergedRuleSet(rs_subst, rs_deref);
rs_subst.__avoid__ := [Value];
rs_idx.__avoid__ := [Value];
rs2.__avoid__ := [Value];
self.subst := x -> SubstVars(x, self.varmap);
self.subst2 := x -> BU(x, rs2);
self.subst3 := x -> SubstBottomUpRules(BU(x, rs_subst), rs_idx.rules);
self.sreduce := x -> SReduce(x, self.opts);
self.sreduce3 := x -> SubstBottomUpRules(x, rs_idx.rules);
self.sreduce_and_subst := MergedRuleSet(rs_subst, rs_deref, RulesStrengthReduce);
else
self.subst := x -> SubstVars(x, self.varmap);
self.subst2 := x -> SubstVars(x, self.varmap);
self.subst3 := x -> SubstVars(x, self.varmap);
self.sreduce := x -> x;
self.sreduce_and_subst := self.subst;
fi;
if do_init_scalarized then
for v in compiler.Compile.scalarized do
self.varmap.(v.id) := noneExp(v.t);
od;
fi;
return self;
end,
assumeSSA := false,
afterSSA := self >> WithBases(self, rec(assumeSSA:=true)),
closeVarMap := meth(self, other, newcmds)
local v;
for v in UserNSFields(other.varmap) do
if (not IsBound(self.varmap.(v)) or self.varmap.(v) <> other.varmap.(v)) and SuccLoc(var(v))<>[] then
if self.assumeSSA then ;
# self.varmap.(v) := other.subst(other.varmap.(v));
# PrintLine("close ", v, " => ", other.subst(other.varmap.(v)));
else
Unbind(self.varmap.(v));
Add(newcmds.cmds, assign(var(v), other.subst(other.varmap.(v))));
fi;
fi;
od;
#Print("-----\n");
end,
init := meth(self, opts)
self.opts := opts;
self.prepVarMap(tab(), true, true, false);
self.doScalarReplacement := opts.doScalarReplacement;
self.propagateNth := opts.propagateNth;
self.flush();
return self;
end,
initial := meth(self, code, opts)
self.opts := opts;
self.prepVarMap(tab(), true, true, true);
self.doScalarReplacement := opts.doScalarReplacement;
self.propagateNth := opts.propagateNth;
self.flush();
return self.copyProp(code);
end,
__call__ := (self, code, opts) >> self.init(opts).copyProp(code),
flush := meth(self)
self.csetab := tab();
if (self.doScalarReplacement) then self.lhsCSE := CSE.init(); fi;
end,
fast := meth(self, code, opts)
self.prepVarMap(tab(), false, false, false);
self.doScalarReplacement := opts.doScalarReplacement;
self.propagateNth := opts.propagateNth;
self.opts := opts;
self.flush();
return self.copyProp(code);
end,
procAssign := meth(self, c, newcmds, live_out)
local newloc, newexp, cid, cloc, op, varmap, lkup;
varmap := self.varmap;
# NOTE: generalize this, use .in()/.out()/.inout() somehow
if IsBound(c.p) then
cid := (loc, exp) -> ObjId(c)(loc, exp, c.p);
else cid := ObjId(c); fi;
# to my current understanding, if we assign a phi function, nothing can be propagated.
# If you propagate inside a phi, you lose the branch information.
if (ObjId(c.exp)=phi) then Add(newcmds, c); return; fi;
# Run strength reduction, variable remapping, and all other rewrite rules
newexp := self.procRHS(c.exp);
cloc := When(not IsVar(c.loc) or (c.loc in c.op_inout()),
self.procLHS(c.loc), c.loc);
# check if newexp was already computed
lkup := self.cseLookup(newexp);
if lkup <> false then newexp := lkup; fi;
# if cloc is marked as live_out, save it in the list, so that its not kicked out
When(IsVar(cloc) and IsBound(cloc.live_out), AddSet(live_out, cloc));
# invalidate the LHS in the CSE tables
if (self.cseLookup(cloc) <> false)
then self.cseInvalidate(cloc); fi;
if (self.doScalarReplacement and self.lhsCSE.cseLookup(cloc) <> false)
then self.lhsCSE.cseInvalidate(cloc); fi;
# propagate
if IsVar(cloc) and cid=assign and self.propagate(cloc,newexp) then
# this should not happen due to sreduce/subst above
When(IsVar(newexp) and IsBound(varmap.(newexp.id)), Error("Should not happen"));
varmap.(cloc.id) := newexp;
# do not propagate
else
# NOTE: YSV: is this right???
# it seems that its correct, above case catches var=noneExp,
# so this looks like a mem-store, e.g., nth(..) = noneExp
if ObjId(newexp)=noneExp then return; fi;
# do not propagate AND cloc is a variable
if IsVar(cloc) and not (cloc in c.op_inout()) then
# propagate 'neg' like unary operators outwards
if IsBound(newexp.doPeel) and newexp.doPeel then
op := ObjId(newexp);
newexp := newexp.args[1];
if self.propagate(cloc, newexp) then
if IsVar(newexp) and IsBound(varmap.(newexp.id)) then
varmap.(cloc.id) := op(varmap.(newexp.id));
else
varmap.(cloc.id) := op(newexp);
fi;
else
newloc := cloc.clone();
varmap.(cloc.id) := op(newloc);
Add(newcmds, cid(newloc, newexp));
# careful! cid can be any storeop, not always <assign>
When(cid=assign, self.cseAdd(newloc, newexp));
fi;
else
# variable that is not propagated is remapped to a fresh name (to get code in SSA form)
newloc := cloc.clone();
varmap.(cloc.id) := newloc;
Add(newcmds, cid(newloc, newexp)); # cid == assign | assign_nop | ...
# careful! cid can be any storeop, not always <assign>
When(cid=assign, self.cseAdd(newloc, newexp));
fi;
# do not propagate AND cloc is *not* a variable (ie. nth(X, i)) or it is an inout variable
else
if self.doScalarReplacement or not (self.propagateNth or IsVar(newexp) or IsValue(newexp)) then
# for non-variable newexp a fresh temporary var sXX is created to hold the result
newloc := var.fresh_t("s", newexp.t);
self.cseAdd(newloc, newexp);
Add(newcmds, assign(newloc, newexp));
newexp := newloc;
fi;
if self.doScalarReplacement then
When(cid<>assign or not (ObjId(cloc) in [nth,deref]),
Error("Scalar replacement can't handle <cloc> of type ", ObjId(cloc)));
self.cseAdd(newexp, cloc);
self.lhsCSE.cseAdd(newexp, cloc);
else
Add(newcmds, cid(cloc, newexp));
fi;
fi;
fi;
end,
procIF := meth(self, c, newcmds, live_out)
local lo_map, v, orig, then_cmd, else_cmd, then_cp, else_cp;
c.cond := self.procRHS(c.cond);
if IsValue(c.cond) then
Error("This is a constant IF, it should be folded away before reaching copyprop");
# Following code should work if needed (if you uncomment the error) but it is not optimized
# self.flush(); # YSV: why is this needed??? I will comment this out.
if c.cond.v=0 or c.cond.v=false then Add(newcmds, self.copyProp(c.else_cmd));
else Add(newcmds, self.copyProp(c.then_cmd));
fi;
else
# Here the idea is that each part of the branch should work with
# the original csetab (there cannot be crossings) and the final thing
# should be restored to the original csetab
then_cp := CopyFields(self, rec(csetab := CopyTab(self.csetab)))
.prepVarMap(CopyTab(self.varmap), true, false, false);
else_cp := CopyFields(self, rec(csetab := CopyTab(self.csetab)))
.prepVarMap(CopyTab(self.varmap), true, false, false);
then_cmd := then_cp.copyProp(c.then_cmd);
self.closeVarMap(then_cp, then_cmd);
else_cmd := else_cp.copyProp(c.else_cmd);
self.closeVarMap(else_cp, else_cmd);
Add(newcmds, IF(c.cond, then_cmd, else_cmd));
#self.flush();
fi;
end,
#if we do Scalar Replacement on the fly, reinject the final writes as assigns (for now)
finalizeScalarReplacement := meth(self, newcmds)
local entry;
if IsBound(self.lhsCSE.csetab.nth) then
# MRT: sort by order of variable being assigned TO rather
# than variable assigned FROM. This reduces cache misses by
# exploiting possible locality in the output array.
#
# eg: Y[0] := a1 ===> Y[0] := a1
# Y[32] := a2 Y[1] := a3
# Y[1] := a3 Y[32] := a2
for entry in _sortByIdx(self.lhsCSE.csetab.nth) do
if Length(entry.args)=2 then
Add(newcmds,
assign(nth(entry.args[1],entry.args[2]),
entry.loc));
fi;
od;
fi;
if IsBound(self.lhsCSE.csetab.deref) then
for entry in self.lhsCSE.csetab.deref do
if Length(entry.args)=1 then
Add(newcmds,
assign(deref(entry.args[1]),
entry.loc));
fi;
od;
fi;
end,
# create the reverse mapping, to map last assignment to live_out variable
# to the actual variable intead of an SSA related substitute
substLiveOut := meth(self, newcmds, live_out)
local varmap, lo_map, active, v;
varmap := self.varmap;
lo_map := tab();
active := Set(Collect(newcmds, var)); # explain this
for v in live_out do
# NOTE: The commented out lines with #X removed extra copies
# associated with live_out variables. But it turns out that this
# does not work if a live_out variable is never actually remapped,
# but has an entry in varmap due to copy propagation.
# For example (a = t11; b = a) if a is live_out will be compiled to
# (b=t11) b CopyPropagate and converted to (b=a) by function below.
# which is incorrect
#X if not IsVar(varmap.(v.id)) or not (varmap.(v.id) in active) then
Add(newcmds, assign(v, varmap.(v.id)));
#X else
#X lo_map.(varmap.(v.id).id) := v;
#X fi;
Unbind(varmap.(v.id)); # prevent duplication of cleanup code due to closeVarMap
od;
newcmds := SubstVars(newcmds, lo_map);
return newcmds;
end,
copyProp := meth(self, code)
local c, cid, cmds, newcmds, live_out;
cmds := When(ObjId(code)=chain, code.cmds, [code]);
newcmds := [];
live_out := Set([]);
for c in cmds do
cid := ObjId(c);
if IsAssign(c) then self.procAssign(c, newcmds, live_out);
elif (cid = IF) then self.procIF(c, newcmds, live_out);
elif IsExpCommand(c) then Add(newcmds, self.procRHS(c));
elif (cid = skip) then ; # do nothing
# if .sideeffect is bound, the command is assumed have side effects
# so one has to enable array scalarization inside all its children
elif IsRec(c) and IsBound(c.sideeffect) and c.sideeffect then
Add(newcmds, map_children_safe(c, x -> self.procRHS(x)));
# the command is a container for other functions, copyprop all children
else Add(newcmds, map_children_safe(c,
x -> Cond(IsCommand(x), self.copyProp(x), self.procRHS(x))));
fi;
od;
When(self.doScalarReplacement, self.finalizeScalarReplacement(newcmds));
newcmds := self.substLiveOut(newcmds, live_out);
# self.flush();
return chain(newcmds);
end
));
|
INCLUDE "non_pp_include.f90"
PROGRAM MAINF90
CALL NON_PP_INCLUDE_SUBROUTINE
END PROGRAM MAINF90
|
[STATEMENT]
lemma non_empty_set_has_least:
"S \<subseteq> T \<Longrightarrow> S \<noteq> {} \<Longrightarrow> least S \<in> S \<and> (\<forall> y \<in> S. least S \<noteq> y \<longrightarrow> \<not> y \<prec> least S)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>S \<subseteq> T; S \<noteq> {}\<rbrakk> \<Longrightarrow> least S \<in> S \<and> (\<forall>y\<in>S. least S \<noteq> y \<longrightarrow> \<not> y \<prec> least S)
[PROOF STEP]
proof goal_cases
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>S \<subseteq> T; S \<noteq> {}\<rbrakk> \<Longrightarrow> least S \<in> S \<and> (\<forall>y\<in>S. least S \<noteq> y \<longrightarrow> \<not> y \<prec> least S)
[PROOF STEP]
case 1
[PROOF STATE]
proof (state)
this:
S \<subseteq> T
S \<noteq> {}
goal (1 subgoal):
1. \<lbrakk>S \<subseteq> T; S \<noteq> {}\<rbrakk> \<Longrightarrow> least S \<in> S \<and> (\<forall>y\<in>S. least S \<noteq> y \<longrightarrow> \<not> y \<prec> least S)
[PROOF STEP]
note A = this
[PROOF STATE]
proof (state)
this:
S \<subseteq> T
S \<noteq> {}
goal (1 subgoal):
1. \<lbrakk>S \<subseteq> T; S \<noteq> {}\<rbrakk> \<Longrightarrow> least S \<in> S \<and> (\<forall>y\<in>S. least S \<noteq> y \<longrightarrow> \<not> y \<prec> least S)
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. least S \<in> S \<and> (\<forall>y\<in>S. least S \<noteq> y \<longrightarrow> \<not> y \<prec> least S)
[PROOF STEP]
proof (rule theI', goal_cases)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<exists>!y. y \<in> S \<and> (\<forall>ya\<in>S. y \<noteq> ya \<longrightarrow> \<not> ya \<prec> y)
[PROOF STEP]
case 1
[PROOF STATE]
proof (state)
this:
goal (1 subgoal):
1. \<exists>!y. y \<in> S \<and> (\<forall>ya\<in>S. y \<noteq> ya \<longrightarrow> \<not> ya \<prec> y)
[PROOF STEP]
from non_empty_set_has_least''[OF A]
[PROOF STATE]
proof (chain)
picking this:
\<exists>!x. x \<in> S \<and> (\<forall>y\<in>S. x \<noteq> y \<longrightarrow> \<not> y \<prec> x)
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
\<exists>!x. x \<in> S \<and> (\<forall>y\<in>S. x \<noteq> y \<longrightarrow> \<not> y \<prec> x)
goal (1 subgoal):
1. \<exists>!y. y \<in> S \<and> (\<forall>ya\<in>S. y \<noteq> ya \<longrightarrow> \<not> ya \<prec> y)
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
\<exists>!y. y \<in> S \<and> (\<forall>ya\<in>S. y \<noteq> ya \<longrightarrow> \<not> ya \<prec> y)
goal:
No subgoals!
[PROOF STEP]
qed
[PROOF STATE]
proof (state)
this:
least S \<in> S \<and> (\<forall>y\<in>S. least S \<noteq> y \<longrightarrow> \<not> y \<prec> least S)
goal:
No subgoals!
[PROOF STEP]
qed |
lemma coeff_mult_degree_sum: "coeff (p * q) (degree p + degree q) = coeff p (degree p) * coeff q (degree q)" |
Require Import Coq.ZArith.ZArith Coq.micromega.Lia.
Require Import Crypto.Util.ZUtil.Hints.Core.
Require Import Crypto.Util.ZUtil.Hints.ZArith.
Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.
Local Open Scope Z_scope.
Module Z.
Lemma mod_mod_small a n m
(Hnm : (m mod n = 0)%Z)
(Hnm_le : (0 < n <= m)%Z)
(H : (a mod m < n)%Z)
: ((a mod n) mod m = a mod m)%Z.
Proof.
assert ((a mod n) < m)%Z
by (eapply Z.lt_le_trans; [ apply Z.mod_pos_bound | ]; lia).
rewrite (Z.mod_small _ m) by auto with zarith.
apply Z.mod_divide in Hnm; [ | lia ].
destruct Hnm as [x ?]; subst.
repeat match goal with
| [ H : context[(_ mod _)%Z] |- _ ]
=> revert H
end.
Z.div_mod_to_quot_rem_in_goal.
lazymatch goal with
| [ H : a = (?x * ?n * ?q) + _, H' : a = (?n * ?q') + _ |- _ ]
=> assert (q' = x * q) by nia; subst q'; nia
end.
Qed.
(** [rewrite_mod_small] is a better version of [rewrite Z.mod_small
by rewrite_mod_small_solver]; it backtracks across occurences
that the solver fails to solve the side-conditions on. *)
Ltac rewrite_mod_small_solver :=
zutil_arith_more_inequalities.
Ltac rewrite_mod_small :=
repeat match goal with
| [ |- context[?x mod ?y] ]
=> rewrite (Z.mod_small x y) by rewrite_mod_small_solver
end.
Ltac rewrite_mod_mod_small :=
repeat match goal with
| [ |- context[(?a mod ?n) mod ?m] ]
=> rewrite (mod_mod_small a n m) by rewrite_mod_small_solver
end.
Ltac rewrite_mod_small_more :=
repeat (rewrite_mod_small || rewrite_mod_mod_small).
Ltac rewrite_mod_small_in_hyps :=
repeat match goal with
| [ H : context[?x mod ?y] |- _ ]
=> rewrite (Z.mod_small x y) in H by rewrite_mod_small_solver
end.
Ltac rewrite_mod_mod_small_in_hyps :=
repeat match goal with
| [ H : context[(?a mod ?n) mod ?m] |- _ ]
=> rewrite (mod_mod_small a n m) in H by rewrite_mod_small_solver
end.
Ltac rewrite_mod_small_more_in_hyps :=
repeat (rewrite_mod_small_in_hyps || rewrite_mod_mod_small_in_hyps).
Ltac rewrite_mod_small_in_all := repeat (rewrite_mod_small || rewrite_mod_small_in_hyps).
Ltac rewrite_mod_mod_small_in_all := repeat (rewrite_mod_mod_small || rewrite_mod_mod_small_in_hyps).
Ltac rewrite_mod_small_more_in_all := repeat (rewrite_mod_small_more || rewrite_mod_small_more_in_hyps).
End Z.
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Andreas Bertsch $
// $Authors: $
// --------------------------------------------------------------------------
//
#ifndef OPENMS_MATH_STATISTICS_GAUSSFITTER_H
#define OPENMS_MATH_STATISTICS_GAUSSFITTER_H
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/DPosition.h>
#include <vector>
// gsl includes
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit_nlin.h>
namespace OpenMS
{
namespace Math
{
/**
@brief Implements a fitter for gaussian functions
This class fits a gaussian distribution to a number of data points.
The results as well as the initial guess are specified using the struct GaussFitResult.
The complete gaussian formula with the fitted parameters can be transformed into a
gnuplot formula using getGnuplotFormula after fitting.
The fitting is implemented using GSL fitting algorithms.
@ingroup Math
*/
class OPENMS_DLLAPI GaussFitter
{
public:
/// struct of parameters of a gaussian distribution
struct GaussFitResult
{
public:
/// parameter A of gaussian distribution (amplitude)
double A;
/// parameter x0 of gaussian distribution (left/right shift)
double x0;
/// parameter sigma of gaussian distribution (width)
double sigma;
};
/// Default constructor
GaussFitter();
/// Destructor
virtual ~GaussFitter();
/// sets the initial parameters used by the fit method as initial guess for the gaussian
void setInitialParameters(const GaussFitResult & result);
/**
@brief Fits a gaussian distribution to the given data points
@param points the data points used for the gaussian fitting
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
GaussFitResult fit(std::vector<DPosition<2> > & points);
/// return the gnuplot formula of the gaussian
const String & getGnuplotFormula() const;
protected:
static int gaussFitterf_(const gsl_vector * x, void * params, gsl_vector * f);
static int gaussFitterdf_(const gsl_vector * x, void * params, gsl_matrix * J);
static int gaussFitterfdf_(const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix * J);
void printState_(size_t iter, gsl_multifit_fdfsolver * s);
GaussFitResult init_param_;
String gnuplot_formula_;
private:
/// Copy constructor (not implemented)
GaussFitter(const GaussFitter & rhs);
/// Assignment operator (not implemented)
GaussFitter & operator=(const GaussFitter & rhs);
};
}
}
#endif
|
"""
# pcor
$(SIGNATURES)
Computes the partial correlation between two variables given a set of other
variables.
### Method
```julia
pcor(;
* `d::DAG` : DAG object
* `u::Vector{Symbol}` : Variables used to compute correlation
)
```
where:
u[1], u[2]: Variables used to compute correlation between, remaining variables
are the conditioning set
### Returns
```julia
* `res::Float64` : Correlation between u[1] and u[2]
```
# Extended help
### Example
### Correlation between vectors and algebra, conditioning on analysis and statistics
```julia
using StructuralCausalModels, CSV
df = DataFrame!(CSV.File(scm_path("..", "data", "marks.csv"));
S = cov(Array(df))
u = [2, 3, 4, 5]
pcor(u, S)
u = [:vectors, :algebra, :statistics, :analysis]
```
### Acknowledgements
Original author: Giovanni M. Marchetti
Translated to Julia: Rob J Goedman
### License
The R package ggm is licensed under License: GPL-2.
The Julia translation is licenced under: MIT.
Part of the api, not exported.
"""
function pcor(d::DAG, u::SymbolList)
us = String.(u)
k = inv(d.s[us, us])
-k[1,2] / sqrt(k[1,1] * k[2,2])
end
export
pcor |
type CuDNNPoolingState
pooling_desc :: CuDNN.PoolingDescriptor
inputs_desc :: Vector{CuDNN.Tensor4dDescriptor}
outputs_desc :: Vector{CuDNN.Tensor4dDescriptor}
end
function setup_etc(backend::GPUBackend, layer::PoolingLayer, inputs,
pooled_width, pooled_height)
dtype = eltype(inputs[1])
if isa(layer.pooling, Pooling.Max)
pooling_mode = CuDNN.CUDNN_POOLING_MAX
elseif isa(layer.pooling, Pooling.Mean)
pooling_mode = CuDNN.CUDNN_POOLING_AVERAGE
else
error("TODO: pooling mode $(layer.pooling) not supported by CuDNN")
end
pooling_desc = CuDNN.create_pooling_descriptor(pooling_mode, layer.kernel, layer.stride, layer.pad)
inputs_desc = Array(CuDNN.Tensor4dDescriptor, length(inputs))
outputs_desc = Array(CuDNN.Tensor4dDescriptor, length(inputs))
for i = 1:length(inputs)
width,height,channels,num = size(inputs[i])
inputs_desc[i] = CuDNN.create_tensor4d_descriptor(dtype,(width,height,channels,num))
outputs_desc[i] = CuDNN.create_tensor4d_descriptor(dtype,
(pooled_width[i],pooled_height[i],channels,num))
end
etc = CuDNNPoolingState(pooling_desc, inputs_desc, outputs_desc)
return etc
end
function shutdown(backend::GPUBackend, state::PoolingLayerState)
map(destroy, state.blobs)
map(destroy, state.blobs_diff)
CuDNN.destroy_pooling_descriotpr(state.etc.pooling_desc)
map(CuDNN.destroy_tensor4d_descriptor, state.etc.inputs_desc)
map(CuDNN.destroy_tensor4d_descriptor, state.etc.outputs_desc)
end
function forward(backend::GPUBackend, state::PoolingLayerState, inputs::Vector{Blob})
layer = state.layer
alpha = one(eltype(inputs[1]))
beta = zero(eltype(inputs[1]))
for i = 1:length(inputs)
CuDNN.pooling_forward(backend.cudnn_ctx, state.etc.pooling_desc, alpha,
state.etc.inputs_desc[i], inputs[i].ptr, beta,
state.etc.outputs_desc[i], state.blobs[i].ptr)
end
end
function backward(backend::GPUBackend, state::PoolingLayerState, inputs::Vector{Blob}, diffs::Vector{Blob})
layer = state.layer
alpha = one(eltype(inputs[1]))
beta = zero(eltype(inputs[1]))
for i = 1:length(inputs)
if isa(diffs[i], CuTensorBlob)
CuDNN.pooling_backward(backend.cudnn_ctx, state.etc.pooling_desc, alpha,
state.etc.outputs_desc[i], state.blobs[i].ptr,
state.etc.outputs_desc[i], state.blobs_diff[i].ptr,
state.etc.inputs_desc[i], inputs[i].ptr,
beta, state.etc.inputs_desc[i], diffs[i].ptr)
end
end
end
|
# Run a synthetic benchmark (Jarosch's 2013 benchmark)
using Plots, Printf
@views av(A) = 0.25*(A[1:end-1,1:end-1].+A[2:end,1:end-1].+A[1:end-1,2:end].+A[2:end,2:end])
@views av_xa(A) = 0.5.*(A[1:end-1,:].+A[2:end,:])
@views av_ya(A) = 0.5.*(A[:,1:end-1].+A[:,2:end])
@views inn(A) = A[2:end-1,2:end-1]
@views function iceflow()
# physics
s2y = 3600*24*365.25 # seconds to years
lx, ly = 30e3, 30e3
rho_i = 910.0 # ice density
g = 9.81 # gravity acceleration
npow = 3.0 # Glen's power law exponent
a0 = 1.5e-24 # Glen's law enhancement term
# numerics
nx, ny = 100, 100 # numerical grid resolution
itMax = 1e5 # number of iteration steps
nout = 200 # error check frequency
tolnl = 1e-6 # nonlinear tolerance
epsi = 1e-4 # small number
damp = 0.85 # convergence acceleration
dtausc = 1.0/2.0 # iterative dtau scaling
# derived physics
a = 2.0*a0/(npow+2)*(rho_i*g)^npow*s2y
# derived numerics
dx, dy = lx/nx, ly/ny
xc, yc = LinRange(dx/2, lx-dx/2, nx), LinRange(dy/2, ly-dy/2, ny)
(Xc,Yc) = ([x for x=xc,y=yc], [y for x=xc,y=yc])
cfl = max(dx^2,dy^2)/4.1
# array initialisation
S = zeros(nx , ny )
B = zeros(nx , ny )
M = zeros(nx , ny )
Err = zeros(nx , ny )
dSdx = zeros(nx-1, ny )
dSdy = zeros(nx , ny-1)
gradS = zeros(nx-1, ny-1)
D = zeros(nx-1, ny-1)
qHx = zeros(nx-1, ny-2)
qHy = zeros(nx-2, ny-1)
dtau = zeros(nx-2, ny-2)
ResH = zeros(nx-2, ny-2)
dHdt = zeros(nx-2, ny-2)
Vx = zeros(nx-1, ny-1)
Vy = zeros(nx-1, ny-1)
# initial condition (Jarosch's 2013 benchmark)
H = ones(nx , ny )
xm, xmB = 20e3, 7e3
M .= (((npow.*2.0./xm.^(2*npow-1)).*Xc.^(npow-1)).*abs.(xm.-Xc).^(npow-1)).*(xm.-2.0.*Xc)
M[Xc.>xm] .= 0.0
B[Xc.<xmB] .= 500
# smoothing (Mahaffy, 1976)
B[2:end-1,2:end-1] .= B[2:end-1,2:end-1] .+ 1.0./4.1.*(diff(diff(B[:,2:end-1], dims=1), dims=1) .+ diff(diff(B[2:end-1,:], dims=2), dims=2))
S .= B .+ H
# iteration loop
it = 1; err = 2*tolnl
while err>tolnl && it<itMax
Err .= H
# compute diffusivity
dSdx .= diff(S, dims=1)/dx
dSdy .= diff(S, dims=2)/dy
gradS .= sqrt.(av_ya(dSdx).^2 .+ av_xa(dSdy).^2)
D .= a*av(H).^(npow+2) .* gradS.^(npow-1)
# compute flux
qHx .= .-av_ya(D).*diff(S[:,2:end-1], dims=1)/dx
qHy .= .-av_xa(D).*diff(S[2:end-1,:], dims=2)/dy
# update ice thickness
dtau .= dtausc*min.(1.0, cfl./(epsi .+ av(D)))
ResH .= .-(diff(qHx, dims=1)/dx .+ diff(qHy, dims=2)/dy) .+ inn(M)
dHdt .= dHdt.*damp .+ ResH
H[2:end-1,2:end-1] .= max.(0.0, inn(H) .+ dtau.*dHdt)
# update surface
S .= B .+ H
# error check
if mod(it, nout)==0
Err .= Err .- H
err = (sum(abs.(Err))./nx./ny)
@printf("it = %d, error = %1.2e \n", it, err)
if isnan(err) error("NaNs") end # safeguard
end
it += 1
end
# compute velocities
Vx .= -D./(av(H) .+ epsi).*av_ya(dSdx)
Vy .= -D./(av(H) .+ epsi).*av_xa(dSdy)
# visualisation
FS = 7
xc, yc = xc./1e3, yc./1e3
xax = ((xc[1], xc[end]), font(FS, "Courier"))
yax = ((yc[1], yc[end]), font(FS, "Courier"))
p1 = heatmap(xc, yc, S' , aspect_ratio=1, xaxis=xax, yaxis=yax, c=:davos, title="Surface elev. [m]", titlefont="Courier", titlefontsize=FS)
p2 = heatmap(xc, yc, H' , aspect_ratio=1, xaxis=xax, yaxis=yax, c=:davos, title="Ice thickness [m]", titlefont="Courier", titlefontsize=FS)
# display(plot(p1, p2, size=(400,160), dpi=200))
plot(p1, p2, size=(400,160), dpi=200)
!ispath("../output") && mkdir("../output")
savefig("../output/iceflow_bench_out.png")
return
end
iceflow()
|
using ExplainableAI: augment_batch_dim, augment_indices, reduce_augmentation
using ExplainableAI: interpolate_batch
# augment_batch_dim
A = [1 2; 3 4]
B = @inferred augment_batch_dim(A, 3)
@test B == [
1 1 1 2 2 2
3 3 3 4 4 4
]
B = @inferred augment_batch_dim(A, 4)
@test B == [
1 1 1 1 2 2 2 2
3 3 3 3 4 4 4 4
]
A = reshape(1:8, 2, 2, 2)
B = @inferred augment_batch_dim(A, 3)
@test B[:, :, 1] == A[:, :, 1]
@test B[:, :, 2] == A[:, :, 1]
@test B[:, :, 3] == A[:, :, 1]
@test B[:, :, 4] == A[:, :, 2]
@test B[:, :, 5] == A[:, :, 2]
@test B[:, :, 6] == A[:, :, 2]
# augment_batch_dim
inds = [CartesianIndex(5, 1), CartesianIndex(3, 2)]
augmented_inds = @inferred augment_indices(inds, 3)
@test augmented_inds == [
CartesianIndex(5, 1)
CartesianIndex(5, 2)
CartesianIndex(5, 3)
CartesianIndex(3, 4)
CartesianIndex(3, 5)
CartesianIndex(3, 6)
]
# reduce_augmentation
A = Float32.(reshape(1:10, 1, 1, 10))
R = @inferred reduce_augmentation(A, 5)
@test R == reshape([sum(1:5), sum(6:10)] / 5, 1, 1, :)
A = Float64.(reshape(1:10, 1, 1, 1, 1, 10))
R = @inferred reduce_augmentation(A, 2)
@test R == reshape([3, 7, 11, 15, 19] / 2, 1, 1, 1, 1, :)
x = Float16.(reshape(1:4, 2, 2))
x0 = zero(x)
A = @inferred interpolate_batch(x, x0, 5)
@test A ≈ [
0.0 0.25 0.5 0.75 1.0 0.0 0.75 1.5 2.25 3.0
0.0 0.5 1.0 1.5 2.0 0.0 1.0 2.0 3.0 4.0
]
|
module Test
import Data.Vect
import System.File
import System
import Data.Buffer
import Data.String
test1 : Nat -> List String -> Vect n Int -> String
test1 1 (x :: xs) (y :: ys) = show 1 ++ show x ++ show xs ++ show y ++ show ys
test1 0 [] [x] = "m1 " ++ show x
test1 2 (x :: xs) (y :: []) = "m2 " ++ show x ++ show xs ++ show y
test1 (S k) d t = "m3 " ++ let x = test1 k (show k :: d) t in x
test1 k d t = "m4 " ++ show k ++ show d ++ show t
data MyDat = A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8
Show MyDat where
show A1 = "A1"
show A2 = "A2"
show A3 = "A3"
show A4 = "A4"
show A5 = "A5"
show A6 = "A6"
show A7 = "A7"
show A8 = "A8"
ansiColorStr : String -> Vect 3 Int -> String
ansiColorStr str [r, g, b] = "\x1b[38;2;" ++ show r ++ ";" ++ show g ++ ";" ++ show b ++ "m" ++ str ++ "\x1b[0m"
namespace Either
public export
ignoreErr : (Show a) => IO (Either a b) -> IO b
ignoreErr io =
do
(Right ok) <- io
| Left err =>
do
putStrLn $ show err
exitFailure
pure ok
namespace Maybe
public export
ignoreErr : IO (Maybe a) -> IO a
ignoreErr io =
do
(Just ok) <- io
| Nothing =>
do
putStrLn "Got nothing"
exitFailure
pure ok
main : IO ()
main = do
let aα = the Nat 5
putStrLn $ show aα
putStrLn $ test1 1 ["a", "b"] [2, 3, 4, 5]
putStrLn $ test1 0 [] [6]
putStrLn $ test1 2 ["c", "d", "e"] [1]
putStrLn $ test1 3 ["p", "t"] [0]
putStrLn $ test1 4 ["a"] [0, 1, 2, 3]
putChar 'c'
putChar 'b'
putChar '\n'
putStrLn $ show A1
putStrLn $ show A8
putStrLn $ show A6
f <- ignoreErr $ openFile "data4.txt" Read
putStrLn $ show !(fGetLine f)
putStrLn $ show !(fEOF f)
ignore $ fPutStrLn stdout "\x1b[38;2;255;100;0mThis is error\x1b[0m"
ignore $ closeFile f
ignore $ writeFile "data.txt" $ ansiColorStr "red\n" [255, 0, 0]
++ ansiColorStr "green\n" [0, 255, 0]
++ ansiColorStr "blue" [0, 0, 255]
putStrLn $ show (the Int 257)
putStrLn $ show !(ignoreErr $ readFile "data.txt")
buf <- ignoreErr $ createBufferFromFile "data.txt"
size <- rawSize buf
putStrLn $ "buf size " ++ show size
putStrLn $ "buf contents:\n" ++ !(getString buf 0 size)
let i64s = 8
ibuf <- ignoreErr $ newBuffer (i64s * 10)
putStrLn $ "init size" ++ show !(rawSize ibuf)
let list = [0..9]
traverse_ (\i => do setInt ibuf (i64s * i) i;putStrLn $ "next size" ++ show !(rawSize ibuf)) list
--setInt31 ibuf 114 (-991133)
setInt ibuf 114 (-567)
setDouble ibuf 122 (-241.123456789)
setString ibuf 80 "hi there !"
setString ibuf 90 "русский язык"
dat2 <- ignoreErr $ openFile "data2.txt" WriteTruncate
ignore $ writeBufferData dat2 ibuf 0 !(rawSize ibuf)
putStrLn $ show $ !(getInt ibuf 0 )
putStrLn $ show $ !(getInt ibuf 8 )
putStrLn $ show $ !(getInt ibuf (8 * 9) )
ignore $ closeFile dat2
ibuf <- ignoreErr $ createBufferFromFile "data2.txt"
putStrLn $ show $ !(getInt ibuf 0 )
putStrLn $ show $ !(getInt ibuf 8 )
putStrLn $ show $ !(getInt ibuf (8 * 9) )
putStrLn $ show !(rawSize ibuf)
putStrLn !(getString ibuf 80 10)
putStrLn !(getString ibuf 90 24)
putStrLn $ show !(getInt ibuf 114)
putStrLn $ show !(getDouble ibuf 122)
|
module probdata_module
use amrex_fort_module, only : rt => amrex_real
! Tagging variables
integer, save :: max_num_part
! Use these to define the spheroid
real(rt), save :: center(3)
real(rt), save :: a1, a3
end module probdata_module
|
mutable struct GFSimulateState
trace::GFTrace
score::Float64
visitor::AddressVisitor
params::Dict{Symbol,Any}
end
function GFSimulateState(params::Dict{Symbol,Any})
GFSimulateState(GFTrace(), 0., AddressVisitor(), params)
end
get_args_change(state::GFSimulateState) = nothing
get_addr_change(state::GFSimulateState, addr) = nothing
set_ret_change!(state::GFSimulateState, value) = begin end
function addr(state::GFSimulateState, dist::Distribution{T}, args, addr, arg_change) where {T}
visit!(state.visitor, addr)
retval::T = random(dist, args...)
score = logpdf(dist, retval, args...)
call = CallRecord(score, retval, args)
state.trace = assoc_primitive_call(state.trace, addr, call)
state.trace.has_choices = true
state.score += score
retval
end
function addr(state::GFSimulateState, gen::Generator{T,U}, args, addr, arg_change) where {T,U}
visit!(state.visitor, addr)
trace::U = simulate(gen, args)
call::CallRecord = get_call_record(trace)
state.trace = assoc_subtrace(state.trace, addr, trace)
state.trace.has_choices = state.trace.has_choices || has_choices(trace)
state.score += call.score
call.retval::T
end
splice(state::GFSimulateState, gf::GenFunction, args::Tuple) = exec(gf, state, args)
function simulate(gen::GenFunction, args)
state = GFSimulateState(gen.params)
retval = exec(gen, state, args)
# TODO add return type annotation for gen functions
call = CallRecord{Any}(state.score, retval, args)
state.trace.call = call
state.trace
end
|
#!/usr/bin/env python3
from vision.modules.base import ModuleBase
from vision import options
from vision.stdlib import *
import shm
import math
import time
import cv2 as cv2
import numpy as np
from collections import namedtuple
from cash_in_shared import *
module_options = [
options.IntOption('gaussian_kernel', 2, 1, 40),
options.IntOption('gaussian_stdev', 10, 0, 40),
options.IntOption('min_area', 100, 1, 2000),
options.DoubleOption('min_circularity', 0.4, 0, 1),
]
class RandomPinger(ModuleBase):
last_run = 0
def process(self, img):
curr_time = time.time()
print(curr_time - self.last_run)
if curr_time - self.last_run < .2:
print("skipping")
# self.last_run = curr_time
return
self.last_run = curr_time
img = img[::2, ::2, :]
# uimg = cv2.UMat(img)
h, w, _ = img.shape
shm.camera.downward_height.set(h)
shm.camera.downward_width.set(w)
# self.post("Original", img)
luv = cv2.cvtColor(img, cv2.COLOR_BGR2LUV)
(luv_l, luv_u, luv_v) = cv2.split(luv)
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
(lab_l, lab_a, lab_b) = cv2.split(lab)
k_size = self.options["gaussian_kernel"]
k_std = self.options["gaussian_stdev"]
blurred = cv2.GaussianBlur(lab_l, (k_size * 2 + 1, k_size * 2 + 1), k_std, k_std)
p1 = 70
canny = cv2.Canny(blurred, p1, p1 / 2)
# self.post("Canny", canny)
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, 1, 50, param1=p1, param2=50, minRadius=15, maxRadius=175)
final = img.copy()
found = False
if circles is not None:
for circle in circles[0, :]:
if circle[2]:
found = True
print(circle[2])
# draw the outer circle
cv2.circle(final, (circle[0], circle[1]), circle[2], (0, 255, 0), 2)
# draw the center of the circle
cv2.circle(final, (circle[0], circle[1]), 2, (0, 0, 255), 3)
found_img = img.copy()
found_img[:, :] = (COLORS["RED"], COLORS["GREEN"])[found]
self.post("found", found_img)
self.post("Final", final)
if __name__ == '__main__':
RandomPinger("downward", module_options)()
|
-- examples in "Type-Driven Development with Idris"
-- chapter 15, section 15.2
import ProcessLib
-- check that all functions are total
%default total
record WCData where
constructor MkWCData
wordCount : Nat
lineCount : Nat
doCount : (content : String) -> WCData
doCount content = let lcount = length (lines content)
wcount = length (words content) in
MkWCData lcount wcount
data WC = CountFile String
| GetData String
WCType : WC -> Type
WCType (CountFile x) = ()
WCType (GetData x) = Maybe WCData
countFile : List (String, WCData) -> String ->
Process WCType (List (String, WCData)) Sent Sent
countFile files fname =
do Right content <- Action (readFile fname)
| Left err => Pure files
let count = doCount content
Action (putStrLn ("Counting complete for " ++ fname))
Pure ((fname, doCount content) :: files)
total
wcService : (loaded : List (String, WCData)) -> Service WCType ()
wcService loaded
= do msg <- Respond (\msg => case msg of
CountFile fname => Pure ()
GetData fname =>
Pure (lookup fname loaded))
newLoaded <- case msg of
Just (CountFile fname) =>
countFile loaded fname
_ => Pure loaded
Loop (wcService newLoaded)
procMain : Client ()
procMain = do Just wc <- Spawn (wcService [])
| Nothing => Action (putStrLn "Spawn failed")
Action (putStrLn "Counting test.txt")
Request wc (CountFile "test.txt")
Action (putStrLn "Processing")
Just wcdata <- Request wc (GetData "test.txt")
| Nothing => Action (putStrLn "File error")
Action (putStrLn ("Words: " ++ show (wordCount wcdata)))
Action (putStrLn ("Lines: " ++ show (lineCount wcdata)))
-- run with:
-- :exec runProc procMain
|
""" Vertical circulation associated with horizontal velocities u, v. """
@inline Γᶠᶠᵃ(i, j, k, grid, u, v) = δxᶠᵃᵃ(i, j, k, grid, Δy_vᶜᶠᵃ, v) - δyᵃᶠᵃ(i, j, k, grid, Δx_uᶠᶜᵃ, u)
""" Vertical vorticity associated with horizontal velocities u, v. """
@inline ζ₃ᶠᶠᵃ(i, j, k, grid, u, v) = Γᶠᶠᵃ(i, j, k, grid, u, v) / Azᶠᶠᵃ(i, j, k, grid)
|
theory CorresHelper
imports
UpdateSemHelper
CogentCRefinement.Cogent_Corres
begin
section "C wp helpers"
lemma whileLoopE_add_invI:
assumes "\<lbrace> P \<rbrace> whileLoopE_inv c b init I (measure M) \<lbrace> Q \<rbrace>, \<lbrace> R \<rbrace>!"
shows "\<lbrace> P \<rbrace> whileLoopE c b init \<lbrace> Q \<rbrace>, \<lbrace> R \<rbrace>!"
by (metis assms whileLoopE_inv_def)
lemma validNF_select_UNIV:
"\<lbrace>\<lambda>s. \<forall>x. Q x s\<rbrace> select UNIV \<lbrace>Q\<rbrace>!"
apply (subst select_UNIV_unknown)
apply (rule validNF_unknown)
done
section "Simplification of corres definition for abstract functions"
context update_sem_init begin
definition
"abs_fun_rel \<Xi>' srel afun_name \<xi>' afun_mon \<sigma> st x x'
= (proc_ctx_wellformed \<Xi>' \<longrightarrow> \<xi>' matches-u \<Xi>' \<longrightarrow> (\<sigma>,st) \<in> srel \<longrightarrow>
(\<forall>r' w'. val_rel x x'
\<and> \<Xi>', \<sigma> \<turnstile> x :u fst (snd (snd (snd (\<Xi>' afun_name)))) \<langle>r', w'\<rangle>
\<longrightarrow> \<not> snd (afun_mon x' st)
\<and> (\<forall>st' y'. (y', st') \<in> fst (afun_mon x' st)
\<longrightarrow> (\<exists>\<sigma>' y. \<xi>' afun_name (\<sigma>, x) (\<sigma>', y)
\<and> val_rel y y' \<and> (\<sigma>', st') \<in> srel))))"
lemma absfun_corres:
"abs_fun_rel \<Xi>' srel s \<xi>' afun' \<sigma> st (\<gamma> ! i) v'
\<Longrightarrow> i < length \<gamma> \<Longrightarrow> val_rel (\<gamma> ! i) v'
\<Longrightarrow> \<Gamma>' ! i = Some (fst (snd (snd (snd (\<Xi>' s)))))
\<Longrightarrow> corres srel
(App (AFun s [] []) (Var i))
(do x \<leftarrow> afun' v'; gets (\<lambda>s. x) od)
\<xi>' \<gamma> \<Xi>' \<Gamma>' \<sigma> st"
apply (clarsimp simp: corres_def abs_fun_rel_def)
apply (frule matches_ptrs_length, simp)
apply (frule(2) matches_ptrs_proj_single')
apply clarsimp
apply (erule impE, blast)
apply clarsimp
apply (elim allE, drule mp, blast)
apply clarsimp
apply (intro exI conjI[rotated], assumption+)
apply (rule u_sem_abs_app)
apply (rule u_sem_afun)
apply (rule u_sem_var)
apply simp
done
lemma abs_fun_rel_def':
"abs_fun_rel \<Xi>' srel afun_name \<xi>' afun_mon \<sigma> st x x'
= (proc_ctx_wellformed \<Xi>' \<longrightarrow> \<xi>' matches-u \<Xi>' \<longrightarrow> (\<sigma>,st) \<in> srel \<longrightarrow>
(\<forall>r' w'. val_rel x x' \<and>
\<Xi>', \<sigma> \<turnstile> x :u fst (snd (snd (snd (\<Xi>' afun_name)))) \<langle>r', w'\<rangle>
\<longrightarrow> \<lbrace>\<lambda>s0. s0 = st\<rbrace>
afun_mon x'
\<lbrace>\<lambda>y' s'. \<exists>\<sigma>' y. \<xi>' afun_name (\<sigma>, x) (\<sigma>', y) \<and> (\<sigma>',s') \<in> srel \<and> val_rel y y'\<rbrace>!))"
by (fastforce simp: abs_fun_rel_def validNF_def valid_def no_fail_def)
end (* of context *)
section "Ordering on abstract function specification properties for corres"
lemma (in update_sem_init) corres_rel_leqD:
"\<lbrakk>rel_leq \<xi>a \<xi>b; corres srel c m \<xi>a \<gamma> \<Xi>' \<Gamma> \<sigma> s\<rbrakk> \<Longrightarrow> corres srel c m \<xi>b \<gamma> \<Xi>' \<Gamma> \<sigma> s"
unfolding corres_def
apply clarsimp
apply (erule impE, rule rel_leq_matchesuD, assumption, assumption)
apply (erule impE, intro exI, assumption)
apply clarsimp
apply (elim allE, erule impE, assumption)
apply clarsimp
apply (drule u_sem_u_sem_all_rel_leqD; simp?)
apply (intro exI conjI; assumption)
done
end |
import tactic general set_lemmas linear_algebra.basis new_free ring_theory.principal_ideal_domain torsion primes
run_cmd tactic.skip
open_locale classical
variables {R : Type*} [integral_domain R] [is_principal_ideal_ring R]
noncomputable def projection {ι : Type*} {M : Type*} [add_comm_group M] [module R M]
(v : ι → M) (hv : is_basis R v) (a : ι) :
linear_map R M M :=
{ to_fun := λ x, x - hv.repr x a • v a,
map_add' := λ x y, by {show (x + y) - hv.repr (x + y) a • v a = (x - _) + (y - _),
rw linear_map.map_add, erw add_smul, abel, },
map_smul' := λ c x, by {show c • x - hv.repr (c • x) a • v a = c • (x - _),
rw linear_map.map_smul, rw smul_sub, rw ←mul_smul, refl, } }
theorem proj_mem {ι : Type*} {M : Type*} [add_comm_group M] [module R M]
{s : set ι} {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M)) {a : ι} (ha : a ∈ s) {x : M} :
projection _ hv ⟨a, ha⟩ x ∈ submodule.span R (set.range (v ∘ subtype.val : (s \ {a} → M))) :=
begin
show _ - _ ∈ _,
conv {to_lhs, congr, rw ←hv.total_repr x},
cases classical.em ((⟨a, ha⟩ : s) ∈ (hv.repr x).support),
rw finsupp.total_apply, unfold finsupp.sum,
rw ←finset.insert_erase h,
erw finset.sum_insert (finset.not_mem_erase (⟨a, ha⟩ : s) (hv.repr x).support),
simp only [add_sub_cancel', function.comp_app],
refine @submodule.sum_mem R M _ _ _ _ (submodule.span R (set.range (v ∘ subtype.val))) (((hv.repr) x).support.erase ⟨a, ha⟩)
(λ (y : s), ((hv.repr) x) y • v y.val) _,
intros y hy, dsimp,
apply submodule.smul_mem (submodule.span R (set.range (v ∘ subtype.val))) _,
apply submodule.subset_span, use y,
rw set.mem_diff, split,
exact y.2,
intro hya,
have hyan : y = ⟨a, ha⟩ := subtype.ext_iff.2 hya,
exact (finset.ne_of_mem_erase hy) hyan,
rw finsupp.not_mem_support_iff.1 h, rw zero_smul, rw sub_zero,
refine @submodule.sum_mem R M _ _ _ _ (submodule.span R (set.range (v ∘ subtype.val)))
(((hv.repr) x).support)
(λ (y : s), ((hv.repr) x) y • v y.val) _,
intros y hy, dsimp,
apply submodule.smul_mem (submodule.span R (set.range (v ∘ subtype.val))) _,
apply submodule.subset_span, use y,
rw set.mem_diff, split,
exact y.2,
intro hya,
have hyan : y = ⟨a, ha⟩ := subtype.ext_iff.2 hya,
rw hyan at hy, exact h hy,
end
lemma proj_ker {ι : Type*} {M : Type*} [add_comm_group M] [module R M]
{s : set ι} {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M)) {a : ι} (ha : a ∈ s) :
(projection _ hv ⟨a, ha⟩).ker = submodule.span R {v a} :=
begin
ext,
split,
intro hx,
rw linear_map.mem_ker at hx,
erw sub_eq_zero at hx,
rw submodule.mem_span_singleton,
use hv.repr x ⟨a, ha⟩,
exact hx.symm,
intro hx,
rw submodule.mem_span_singleton at hx,
cases hx with r hr,
rw linear_map.mem_ker,
erw sub_eq_zero,
rw ←hr, rw linear_map.map_smul,
have := @is_basis.repr_eq_single _ _ _ _ _ _ _ hv ⟨a, ha⟩,
have hh : hv.repr ((v ∘ subtype.val) (⟨a, ha⟩ : s)) (⟨a, ha⟩ : s) = (1 : R) := by
rw this; exact finsupp.single_eq_same,
simp only [finsupp.smul_apply, algebra.id.smul_eq_mul, function.comp_app],
rw mul_comm,
rw mul_smul,
rw hh, rw one_smul,
end
lemma projective_of_has_basis {ι : Type*} {M : Type*} [add_comm_group M] [module R M]
{v : ι → M} (hv : is_basis R v) :
projective R M :=
begin
intros _ _ _ _ _ _ _ _ hg,
let F' := λ i : ι, classical.some (hg (f (v i))),
let F := @is_basis.constr _ _ _ _ _ _ _ _inst_6 _ _inst_7 hv F',
use F,
have huh : ∀ i : ι, g (F $ v i) = f (v i) := by {
intro i, rw constr_basis, exact classical.some_spec (hg (f $ v i))},
have : @linear_map.comp R M A B _ _ (@add_comm_group.to_add_comm_monoid A _inst_6)
(@add_comm_group.to_add_comm_monoid B _inst_7_1) _ _ _ g F = f := @is_basis.ext
_ _ _ _ _ _ _ _inst_7_1 _ _inst_7_2 (@linear_map.comp R M A B _ _
(@add_comm_group.to_add_comm_monoid A _inst_6) (@add_comm_group.to_add_comm_monoid B _inst_7_1)
_ _ _ g F) f
hv (λ x, huh x),
intro x,
rw ←this,
refl,
end
lemma split_of_left_inv {M : Type*} [add_comm_group M] [module R M] (A : submodule R M)
{B : Type*} [add_comm_group B] [module R B] (f : M →ₗ[R] B) (H : A.subtype.range = f.ker)
(g : B →ₗ[R] M) (hfg : f.comp g = linear_map.id) (hf : f.range = ⊤) :
A ⊓ g.range = ⊥ ∧ A ⊔ g.range = ⊤ :=
begin
split,
rw eq_bot_iff,
intros x hx,
refine (submodule.mem_bot R).2 _,
cases hx.2 with y hy,
have : f x = 0, by {rw ←linear_map.mem_ker, rw ←H, exact ⟨⟨x, hx.1⟩, trivial, rfl⟩},
rw ←hy.2 at this, rw ←linear_map.comp_apply at this,
rw hfg at this,
rw linear_map.id_apply at this,
rw ←hy.2,
rw this,
rw g.map_zero,
rw eq_top_iff,
intros x _,
apply submodule.mem_sup.2,
clear a,
use x - g (f x),
split,
rw ←submodule.range_subtype A, rw H,
rw linear_map.mem_ker,
rw linear_map.map_sub,
show f x - f.comp g (f x) = 0,
rw hfg,
exact sub_self (f x),
use g (f x),
split,
exact linear_map.mem_range.2 ⟨f x, rfl⟩,
rw sub_add_cancel,
end
variables {ι : Type*} {M : Type*} (s : set ι)
[fintype ι] [add_comm_group M]
[module R M] (v : ι → M)
(a : ι)
variables (R)
def wtf' (i : (s \ ({a} : set ι) : set ι)) : submodule.span R
(set.range (v ∘ subtype.val : s \ {a} → M)) :=
subtype.mk ((v ∘ subtype.val) i) (submodule.subset_span $ set.mem_range_self i)
variables {R}
lemma is_basis_diff {n : ℕ} {ι : Type*} {M : Type*} {s : set ι}
[fintype ι] (hs : fintype.card ↥s = nat.succ n) [add_comm_group M]
[module R M] {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M))
{a : ι} (ha : a ∈ s) :
is_basis R (wtf' R s v a ∘ (subtype.val : (@set.univ (s \ ({a} : set ι) : set ι) : set _) →
(s \ ({a} : set ι) : set ι))) :=
begin
split,
refine linear_independent.comp _ subtype.val subtype.val_injective,
apply linear_independent_span,
dsimp,
cases hv with hv1 hv2,
have := linear_independent.to_subtype_range hv1,
have H := linear_independent.mono (show (set.range (v ∘ subtype.val : s \ {a} → M) ⊆
set.range (v ∘ subtype.val : s → M)), by
{rw set.range_subset_iff, intro y,
exact ⟨⟨(y : ι), set.diff_subset _ _ y.2⟩, rfl⟩}) this,
refine linear_independent.of_subtype_range _ H,
have hi := linear_independent.injective hv1,
intros x y h,
have hxy : (⟨(x : ι), set.diff_subset _ _ x.2⟩ : s) = (⟨(y : ι), set.diff_subset _ _ y.2⟩ : s) :=
hi (by simpa only [function.comp_app] using h),
apply subtype.ext_iff.2, simpa only [] using hxy,
refine linear_map.map_injective (submodule.ker_subtype _) _,
rw submodule.map_subtype_top, rw ←submodule.span_image,
rw ←set.range_comp, congr' 1,
ext,
split,
rintro ⟨y, hy⟩, simp only [submodule.subtype_apply, function.comp_app, wtf'] at hy,
rw ←hy, use y.1, refl,
rintro ⟨y, hy⟩,
rw ←hy, use y, simp only [wtf', submodule.subtype_apply, submodule.coe_mk, function.comp_app],
end
theorem free_subm0 (ι : Type*) [fintype ι] (s : set ι) (hs : fintype.card s = 0)
(M : Type*) [add_comm_group M] [module R M] (v : ι → M)
(hv : is_basis R (v ∘ (subtype.val : s → ι)))
(S : submodule R M) : ∃ (t : set M), linear_independent R (λ x, x : t → M) ∧
submodule.span R (set.range (λ x, x : t → M)) = S :=
begin
use ∅,
split,
exact linear_independent_empty R M,
cases hv with hv1 hv2,
have hs := fintype.card_eq_zero_iff.1 hs,
erw subtype.range_coe_subtype, erw submodule.span_empty,
suffices : ∀ x : M, x = 0, by {symmetry, rw eq_bot_iff, intros x hx, apply (submodule.mem_bot R).2,
exact this (x : M)},
intro x,
have : set.range (v ∘ (subtype.val : s → ι )) = ∅ :=
by {apply set.range_eq_empty.2, intro h, cases h with y hy, exact hs y },
rw this at hv2, rw submodule.span_empty at hv2,
apply (submodule.mem_bot R).1, rw hv2, exact submodule.mem_top,
end
noncomputable def free_equiv {ι : Type*} (x : ι)
{M : Type*} [add_comm_group M] [module R M] {v : ι → M}
(hv : is_basis R (v ∘ (subtype.val : ({x}: set ι) → ι))) :
linear_equiv R R M :=
equiv_of_is_basis (@is_basis_singleton_one ({x} : set ι) R
(set.unique_singleton x) _) hv (equiv.refl _)
lemma free_subm1 (ι : Type*) [fintype ι] (s : set ι) (hs : ¬ 1 < fintype.card s)
(M : Type*) [add_comm_group M] [module R M] (v : ι → M) (hv : is_basis R (v ∘ (subtype.val : s → ι)))
(S : submodule R M) : ∃ (t : set M), linear_independent R (λ x, x : t → M) ∧
submodule.span R (set.range (λ x, x : t → M)) = S :=
begin
cases classical.em (S = ⊥),
use ∅, split, exact linear_independent_empty _ _, rw h, simp,
have : fintype.card s = 0 ∨ fintype.card s = 1 := by omega,
cases this with hl hr, exact free_subm0 ι s hl M v hv S,
cases fintype.card_eq_one_iff.1 hr with y hy,
have hrange : set.range (v ∘ subtype.val) = {(v ∘ subtype.val) y} := by {rw ←set.image_univ,
convert set.image_singleton, symmetry, rw ←set.univ_subset_iff, intros t ht, exact hy t,},
have hys : {(y : ι)} = s := by {ext a, split, intro ha, convert y.2, intro ha,
exact subtype.ext_iff.1 (hy ⟨a, ha⟩)},
let Smap := S.map (@free_equiv R _ _ ι (y : ι) M _ _ v (hys.symm ▸ hv)).symm.to_linear_map,
cases submodule.is_principal.principal Smap with c hc,
let C := @free_equiv R _ _ ι (y : ι) M _ _ v (hys.symm ▸ hv) c,
use {C},
have hCy : C ∈ submodule.span R {(v ∘ subtype.val) y} := by {rw ←hrange, rw hv.2,
exact submodule.mem_top,},
cases submodule.mem_span_singleton.1 hCy with r hr,
have hCS : S = submodule.span R {C} := by {simp only [Smap, C] at hc ⊢, rw ←set.image_singleton,
erw submodule.span_image,
rw ←hc, rw ←submodule.map_comp, symmetry, convert submodule.map_id S, ext z,
exact linear_equiv.apply_symm_apply (@free_equiv R _ _ ι (y : ι) M _ _ v (hys.symm ▸ hv)) z,},
have hC0 : C ≠ 0 := λ hC0, by {rw hC0 at hCS, change S = submodule.span R (⊥ : submodule R M) at hCS,
erw submodule.span_eq at hCS, exact h hCS},
have hr0 : r ≠ 0 := λ hr0, by {rw hr0 at hr, rw zero_smul at hr, apply hC0, exact hr.symm},
split,
refine linear_independent.mono _ _, exact {r • v (y : ι)}, rw ←hr,
rw set.singleton_subset_iff, exact set.mem_singleton _,
have hry : {r • v (y : ι)} = set.range (λ m : s, r • (v ∘ subtype.val) m) :=
by {rw ←set.image_univ, erw ←@set.image_singleton _ _ (λ m : s, r • (v ∘ subtype.val) m) y,
congr, exact set.eq_univ_of_forall hy},
rw hry,
apply linear_independent.to_subtype_range, rw linear_independent_iff,
have hv1 := linear_independent_iff.1 hv.1, intros l hl,
let L : {x // x ∈ s} →₀ R := finsupp.map_range (λ m, r • m) (smul_zero r) l,
have hvL := hv1 L (by {rw finsupp.total_apply at hl ⊢, unfold finsupp.sum,
simp only [finsupp.map_range_apply],
rw finset.sum_subset (finsupp.support_map_range), convert hl,dsimp,
simp only [mul_comm r, mul_smul], refl,
intros X hX hX0, have hm := finsupp.not_mem_support_iff.1 hX0,
rw finsupp.map_range_apply at hm,rw hm, rw zero_smul,
}),
ext,
rw finsupp.ext_iff at hvL, specialize hvL a,
exact or.resolve_left (mul_eq_zero.1 hvL) hr0,
convert hCS.symm,
simp only [subtype.range_coe_subtype], refl,
end
lemma one_empty {n : ℕ} {ι : Type*} {M : Type*} {s : set ι} [hι : fintype ι]
(hs : fintype.card ↥s = n.succ)
[add_comm_group M] [module R M] {v : ι → M} (hv : is_basis R (v ∘ subtype.val : s → M))
{S : submodule R M} (h1 : 1 < fintype.card ↥s) {b : ι} (hb : b ∈ s)
{t : set ↥(submodule.span R (set.range (v ∘ subtype.val : s \ {b} → M)))}
(ht : linear_independent R (λ (x : t), (↑x : submodule.span R (set.range
(v ∘ subtype.val : s \ {b} → M)))) ∧ submodule.span R (set.range (λ (x : ↥t),
(↑x : submodule.span R (set.range
(v ∘ subtype.val : s \ {b} → M))))) =
submodule.map
(linear_map.cod_restrict (submodule.span R (set.range (v ∘ subtype.val)))
(projection (v ∘ subtype.val) hv ⟨b, hb⟩)
(λ c, proj_mem hv hb))
S)
{l : set ↥((projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker)}
(hl :
linear_independent R (λ (x : ↥l), (↑x : (projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker)) ∧
submodule.span R (set.range (λ (x : ↥l), (↑x : (projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker))) =
((submodule.of_le $ @inf_le_right _ _ S (projection _ hv ⟨b, hb⟩).ker).range))
(h : l = ∅) :
∃ (t : set M),
linear_independent R (λ (x : ↥t), (↑x : M)) ∧ submodule.span R (set.range (λ (x : ↥t), ↑x)) = S :=
begin
use (submodule.span R (set.range (v ∘ subtype.val : s \ {b} → M))).subtype '' t,
split,
apply linear_independent.image_subtype,
exact ht.1,
simp only [disjoint_bot_right, submodule.ker_subtype],
simp only [submodule.subtype_apply, subtype.range_coe_subtype],
show submodule.span R ((submodule.span R (set.range (v ∘ subtype.val))).subtype '' t) = S,
rw submodule.span_image,
apply le_antisymm,
rw submodule.map_le_iff_le_comap,
intros y hy,
simp only [submodule.mem_comap, submodule.subtype_apply],
sorry, sorry,
end
theorem free_subm (ι : Type*) [fintype ι] (s : set ι) (n : ℕ) (hs : fintype.card s = n)
(M : Type*) [add_comm_group M] [module R M] (v : ι → M) (hv : is_basis R (v ∘ (subtype.val : s → ι)))
(S : submodule R M) : ∃ (t : set M), linear_independent R (λ x, x : t → M) ∧ submodule.span R (set.range (λ x, x : t → M)) = S :=
begin
unfreezingI {revert ι M s,
induction n using nat.case_strong_induction_on with n hn},
intros ι M s hι h0 inst inst' v hv S,
exact @free_subm0 _ _ _ ι hι s h0 M inst inst' v hv S,
intros ι M s hι hs _ _ v hv S,
resetI,
cases (classical.em (1 < fintype.card s)) with h1 h1,
rcases fintype.card_pos_iff.1 (show 0 < fintype.card s, by omega) with ⟨b, hb⟩,
rcases hn n (nat.le_refl n) (s \ ({b} : set ι) : set ι)
(submodule.span R (set.range (v ∘ subtype.val : (s \ ({b} : set ι)) → M))) (set.univ)
(by {
apply (add_right_inj 1).1, rw add_comm 1 n, rw ←nat.succ_eq_add_one n, rw ← hs,
erw univ_card'', rw add_comm,
rw (card_insert' (s \ ({b} : set ι)) not_mem_diff_singleton).symm,
congr, rw ←eq_insert_erase_of_mem s b hb, apply_instance, apply_instance})
(λ i, ⟨v i, submodule.subset_span $ set.mem_range_self i⟩)
(by convert is_basis_diff hs hv hb)
(S.map $ (projection _ hv ⟨b, hb⟩).cod_restrict (submodule.span R (set.range
(v ∘ subtype.val : (s \ ({b} : set ι)) → M)))
(λ c, proj_mem hv hb)) with ⟨t, ht⟩,
rcases hn 1 (by omega) ({b} : set ι) (projection _ hv ⟨b, hb⟩).ker set.univ sorry
(λ x, ⟨v x, by {rw proj_ker,apply submodule.subset_span,convert set.mem_singleton _, exact x.2.symm}⟩)
(by {split,
suffices : linear_independent R (v ∘ subtype.val : ({b} : set ι) → M), by
{ apply linear_independent.comp _ subtype.val subtype.val_injective,
erw linear_independent_comp_subtype at this,
rw linear_independent_iff,intros l hl,
specialize this (finsupp.emb_domain (function.embedding.subtype ({b} : set ι)) l)
(by {rw finsupp.mem_supported, rw finsupp.support_emb_domain,
intros x hx, rcases finset.mem_map.1 hx with ⟨y, hym, hy⟩,
rw ←hy, exact y.2}), rw finsupp.total_apply at hl,
rw finsupp.total_emb_domain at this,rw finsupp.total_apply at this,
simp only [function.comp_app] at this,
change ((l.sum (λ (i : ({b} : set ι)) (c : R), c • v (↑i : ι)) = 0) →
(finsupp.emb_domain (function.embedding.subtype ({b} : set ι)) l = 0)) at this,
specialize this (by {rw subtype.ext_iff at hl,dsimp at hl,rw ←hl,
show _ = submodule.subtype _ _,
conv_rhs {rw ←finsupp.total_apply},
rw linear_map.map_finsupp_total, rw finsupp.total_apply,
apply finset.sum_congr rfl, intros x hx, simp only [submodule.subtype_apply, submodule.coe_mk,
function.comp_app], }),
rw finsupp.ext_iff at this,ext,specialize this a,erw finsupp.emb_domain_apply at this,
rw this,simp only [finsupp.zero_apply], },
have huh := linear_independent.to_subtype_range hv.1,
have hm := linear_independent.mono (show set.range (v ∘ subtype.val : ({b} : set ι) → M) ⊆
set.range (v ∘ subtype.val : s → M), by
{rw set.range_subset_iff, intro y, use b, exact hb, rw ←subtype.eta y y.2, simp only
[function.comp_app, subtype.eta],
exact congr_arg v y.2.symm,
}) huh,
apply linear_independent.of_subtype_range, intros c d hcd,
rw subtype.ext_iff, rw (show (c : ι) = b, from c.2), symmetry, exact d.2, exact hm,
apply linear_map.map_injective (projection _ hv ⟨b, hb⟩).ker.ker_subtype,
rw submodule.map_subtype_top, rw ←submodule.span_image, symmetry,
convert proj_ker hv hb,
rw ←set.range_comp,
ext m,
split,
rintro ⟨k, hk⟩,
rw ← hk, show _ = _, simpa only [] using congr_arg v k.1.2,
intro hm, use b, exact set.mem_singleton _, rw (show _ = _, from hm), refl,
})
(submodule.of_le $ @inf_le_right _ _ S (projection _ hv ⟨b, hb⟩).ker).range with ⟨l, hl⟩,
cases (classical.em (l = ∅)),
exact one_empty hs hv h1 hb ht hl h,
let V := (submodule.span R (set.range (v ∘ subtype.val : (s \ ({b} : set ι)) → M))).subtype '' t,
let W := (projection (v ∘ subtype.val) hv ⟨b, hb⟩).ker.subtype '' l,
use V ∪ W,
refine union_is_basis_of_gen_compl S ((submodule.span R (set.range (v ∘ subtype.val :
(s \ ({b} : set ι)) → M))).comap S.subtype) V (submodule.comap S.subtype $
linear_map.ker (projection (v ∘ subtype.val) hv ⟨b, hb⟩)) W _ _ _ _ _ _,
rw submodule.map_comap_subtype,
sorry,
rw submodule.map_comap_subtype, sorry,
refine linear_independent.image_subtype _ _,
exact ht.1, sorry,
refine linear_independent.image_subtype _ _,
exact hl.1, sorry,
rw ←submodule.comap_inf,
rw eq_bot_iff,
intros x hx, rw submodule.mem_bot,
cases hx with hxl hxr,
simp at hxr,
sorry,
sorry,
exact free_subm1 ι s h1 M v hv S,
end
lemma tf_iff {M : Type*} [add_comm_group M] [module R M] :
tors R M = ⊥ ↔ ∀ (x : M) (r : R), r • x = 0 → r = 0 ∨ x = 0 :=
begin
split,
intro h,
rw eq_bot_iff at h,
intros x r hx,
cases (classical.em (r = 0)),
left, assumption,
right,
exact (submodule.mem_bot R).1 (h ⟨r, h_1, hx⟩),
intros h,
rw eq_bot_iff,
intros x hx,
cases hx with r hr,
exact (submodule.mem_bot R).2 (or.resolve_left (h x r hr.2) hr.1)
end
theorem fg_quotient {M : Type*} [add_comm_group M] [module R M]
(S : submodule R M) (Hfg : S.fg) (A : submodule R S) : (⊤ : submodule R A.quotient).fg :=
@is_noetherian.noetherian _ _ _ _ _
(is_noetherian_of_quotient_of_noetherian R S A $ is_noetherian_of_fg_of_noetherian S Hfg) ⊤
lemma span_insert_zero_eq' {s : set M} :
submodule.span R (insert (0 : M) s) = submodule.span R s :=
begin
rw ←set.union_singleton,
rw submodule.span_union,
rw submodule.span_singleton_eq_bot.2 rfl,
rw sup_bot_eq,
end
lemma card_pos_of_ne_bot {M : Type*} [add_comm_group M] [module R M] {s : finset M}
{S : submodule R M} (h : S ≠ ⊥) (hs : submodule.span R (↑s : set M) = S) :
0 < (s.erase 0).card :=
begin
rw nat.pos_iff_ne_zero,
intro h0,
rw finset.card_eq_zero at h0,
cases classical.em ((0 : M) ∈ s) with hl hr,
rw ←finset.insert_erase hl at hs,
rw insert_to_set' at hs,
rw span_insert_zero_eq' at hs,
rw h0 at hs, erw submodule.span_empty at hs, exact h hs.symm,
rw finset.erase_eq_of_not_mem hr at h0,
rw h0 at hs, erw submodule.span_empty at hs,
exact h hs.symm,
end
lemma subset_singleton' {c : M} {l : finset M} (h : l ⊆ {c}) : l = ∅ ∨ l = {c} :=
begin
cases (finset.eq_empty_or_nonempty l),
left,
exact h_1,
right,
erw finset.eq_singleton_iff_unique_mem,
cases h_1 with w hw,
have := finset.mem_singleton.1 (h hw),
rw ←this,
split,
exact hw,
intros x hx,
rw this,
exact finset.mem_singleton.1 (h hx),
end
lemma single_of_singleton_support {α : Type*} {l : α →₀ R} {x : α}
(h : l.support = {x}) : l = finsupp.single x (l x) :=
begin
ext,
cases classical.em (a = x),
rw h_1, simp only [finsupp.single_eq_same],
rw finsupp.not_mem_support_iff.1 (by rw h; exact finset.not_mem_singleton.2 h_1),
rw finsupp.single_eq_of_ne (ne.symm h_1),
end
def WHY (s : finset M) : set M := @has_lift.lift _ _ finset.has_lift s
noncomputable def finsupp_insert {s : finset M} {x : M} {l : (set.insert x (WHY s)) →₀ R}
(hx : x ∉ s) (hl : l.2 (⟨x, set.mem_insert x (WHY s)⟩ : set.insert x (WHY s)) = 0) :
WHY s →₀ R :=
{ support := subtype_mk' (finset.image subtype.val l.support) (WHY s) (by {intros y hy,
erw finset.mem_image at hy, rcases hy with ⟨z, hzm, hz⟩, rw ←hz, exact
or.resolve_left z.2 (by {intro hzx, rw finsupp.mem_support_iff at hzm, apply hzm, rw ←hl,
congr, rw subtype.ext_iff, exact hzx})}),
to_fun := λ x, l ⟨x, set.subset_insert _ _ x.2⟩,
mem_support_to_fun := λ y, by {split, intros h h0, erw finset.mem_image at h,
rcases h with ⟨b, hmb, hb⟩, cases b with b1 b2, erw finset.mem_image at b2, rcases b2 with ⟨c, hmc, hc⟩,
apply finsupp.mem_support_iff.1 hmc, rw ←subtype.eta c c.2, rw ←h0, congr' 1,
rw subtype.mk_eq_mk, rw hc, rw ←hb, refl,
intros h0, apply finset.mem_image.2, use (y : M), apply finset.mem_image.2,
use ⟨y, set.subset_insert _ _ y.2⟩,
split, exact finsupp.mem_support_iff.2 h0, refl,
split, exact finset.mem_univ _, rw subtype.ext_iff, refl,} }
lemma finsupp_insert_apply {s : finset M} {x : M} {l : (set.insert x (WHY s)) →₀ R}
(hx : x ∉ s) (hl : l.2 (⟨x, set.mem_insert x (WHY s)⟩ : set.insert x (WHY s)) = 0)
{y : M} (hy : y ∈ s) : finsupp_insert hx hl ⟨y, hy⟩ = l ⟨y, set.subset_insert _ _ hy⟩ :=
rfl
lemma finsupp_insert_total {s : finset M} {x : M} {l : (set.insert x (WHY s)) →₀ R}
(hx : x ∉ s) (hl : l.2 (⟨x, set.mem_insert x (WHY s)⟩ : set.insert x (WHY s)) = 0)
: finsupp.total (WHY s) M R subtype.val (finsupp_insert hx hl) =
finsupp.total (set.insert x (WHY s)) M R subtype.val l :=
begin
rw finsupp.total_apply,
rw finsupp.total_apply,
unfold finsupp.sum,
show (subtype_mk' _ _ _).sum (λ (z : WHY s), l ⟨z, set.subset_insert _ _ z.2⟩ • (z : M)) = _,
sorry,
end
variables (ρ : finset M) (T : set M)
instance fucksake2 (s : finset M) : fintype (WHY s) :=
finset_coe.fintype s
noncomputable def dep_coeff_map {M : Type*} [add_comm_group M] [module R M] (s : finset M) (z : M)
(h : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker = ⊥) :
(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker :=
@classical.some (finsupp.total (set.insert z (WHY s)) M R subtype.val).ker (λ f, f ≠ 0) (by {
have h' : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker ≤ ⊥, from λ h', h (eq_bot_iff.2 h'),
rcases submodule.not_le_iff_exists.1 h' with ⟨y, hym, hy⟩, use y,exact hym,
intro hy0, rw subtype.ext_iff at hy0,
exact hy hy0})
noncomputable def dep_coeff {M : Type*} [add_comm_group M] [module R M] (s : finset M) (z : M)
(h : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker = ⊥) : R :=
dep_coeff_map s z h ⟨z, (set.mem_insert z _)⟩
theorem dep_coeff_spec {M : Type*} [add_comm_group M] [module R M] (s : finset M) (z : M)
(h : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker = ⊥) :
dep_coeff_map s z h ≠ 0 :=
@classical.some_spec (finsupp.total (set.insert z (WHY s)) M R subtype.val).ker (λ f, f ≠ 0) (by {
have h' : ¬(finsupp.total (set.insert z (WHY s)) M R subtype.val).ker ≤ ⊥,
from λ h', h (eq_bot_iff.2 h'),
rcases submodule.not_le_iff_exists.1 h' with ⟨y, hym, hy⟩, use y,
exact hym, intro hy0, rw subtype.ext_iff at hy0,
exact hy hy0})
lemma prod_ne_zero {M : Type*} [add_comm_group M] [module R M] (Y s : finset M)
(h : ∀ z : M, z ∈ Y \ s → ¬(finsupp.total (set.insert (z : M) (WHY s)) M R subtype.val).ker = ⊥)
(hli : (finsupp.total (WHY s) M R subtype.val).ker = ⊥) :
finset.prod (finset.image (λ w : (WHY (Y \ s)), dep_coeff s (w : M) $ h w w.2)
(@finset.univ (WHY (Y \ s)) _)) id ≠ 0 :=
begin
intro hr0,
have hr := finset_prod_eq_zero_iff.1 hr0,
rw finset.mem_image at hr, rcases hr with ⟨x, hxm, hx⟩,
rw eq_bot_iff at hli,
have H := classical.not_not.2 hli,
apply H,
rw submodule.not_le_iff_exists,
let F := @finsupp_insert R _ _ _ _ _ s x (dep_coeff_map s x (h x x.2)) (finset.mem_sdiff.1 x.2).2 hx,
use F,
split,
rw linear_map.mem_ker,
erw finsupp_insert_total (finset.mem_sdiff.1 x.2).2 hx,
have huh := (dep_coeff_map s (x : M) (h x x.2)).2,
rw linear_map.mem_ker at huh, exact huh,
intro hF0,
apply dep_coeff_spec s (x : M) (h x x.2),
rw submodule.mem_bot at hF0,
rw subtype.ext_iff,
rw submodule.coe_zero,
ext,
cases (set.mem_insert_iff.1 a.2),
rw finsupp.zero_apply, rw ←hx, congr, rw subtype.ext_iff, exact h_1,
have huh := finsupp.ext_iff.1 hF0 ⟨a, h_1⟩,
rw finsupp_insert_apply at huh,
rw subtype.coe_eta at huh, rw huh, refl,
end
lemma prod_smul_mem {M : Type*} [add_comm_group M] [module R M] (Y s : finset M)
(h : ∀ z : M, z ∈ Y \ s → ¬(finsupp.total (set.insert (z : M) (WHY s)) M R subtype.val).ker = ⊥)
(hli : (finsupp.total (WHY s) M R subtype.val).ker = ⊥)
{y} (hy : y ∈ Y) :
finset.prod (finset.image (λ w : (WHY (Y \ s)), dep_coeff s (w : M) $ h w w.2)
(@finset.univ (WHY (Y \ s)) _)) id • y ∈ submodule.span R (↑s : set M) :=
begin
sorry,
end
variables {r : R} (S : submodule R M)
noncomputable def r_equiv (htf : ∀ (x : S) (r : R), r • x = 0 → r = 0 ∨ x = 0) (r : R) (hr : r ≠ 0) :=
linear_equiv.of_injective ((r • linear_map.id).comp S.subtype) (by {
rw linear_map.ker_eq_bot', intros m hm, exact or.resolve_left
(htf m r $ subtype.ext_iff.2 $ by {dsimp at hm, rw ←submodule.coe_smul at hm,
rw ←@submodule.coe_zero _ _ _ _ _ S at hm, exact hm}) hr})
lemma equiv_apply (htf : ∀ (x : S) (r : R), r • x = 0 → r = 0 ∨ x = 0) (r : R) (hr : r ≠ 0) {x : S} :
(r_equiv S htf r hr x : M) = r • x := rfl
theorem free_of_tf (M : Type*) [add_comm_group M] [module R M] (S : submodule R M)
(hfg : S.fg) (htf : ∀ (x : S) (r : R), r • x = 0 → r = 0 ∨ x = 0) :
∃ (t : set M), linear_independent R (λ x, x : t → M) ∧
submodule.span R (set.range (λ x, x : t → M)) = S :=
begin
cases (classical.em (S = ⊥)),
{ use ∅,
split,
exact linear_independent_empty _ _,
rw h, simp only [subtype.range_coe_subtype], exact submodule.span_empty},
cases hfg with X hX,
set Y := X.erase 0,
have hY : (↑Y : set M) ⊆ S := set.subset.trans (finset.erase_subset 0 X) (hX ▸ submodule.subset_span),
set n := nat.find_greatest (λ n, ∃ s : finset M, s ⊆ Y ∧
linear_independent R (λ x, x : (WHY s) → M) ∧ s.card = n) Y.card,
cases @nat.find_greatest_spec (λ n, ∃ s : finset M, s ⊆ Y ∧
linear_independent R (λ x, x : (WHY s) → M) ∧ s.card = n) _ Y.card
⟨1, nat.succ_le_of_lt $ card_pos_of_ne_bot h hX, by
{cases finset.card_pos.1 (card_pos_of_ne_bot h hX) with c hc,
use {c}, split,
exact finset.singleton_subset_iff.2 hc, split,
rw linear_independent_subtype, intros l hlm hl,
cases subset_singleton ((finsupp.mem_supported _ _).1 hlm) with hl0 hlc,
rw ←finsupp.support_eq_empty, exact hl0,
rw single_of_singleton_support hlc at hl ⊢,
rw finsupp.total_single at hl,
rw finsupp.single_eq_zero,
exact or.resolve_right (htf ⟨c, hY hc⟩ (l c) (subtype.ext_iff.2 $ hl))
(λ h0, (finset.mem_erase.1 hc).1 $ subtype.ext_iff.1 h0),
exact finset.card_singleton _,
}⟩ with s hs,
cases (classical.em (∃ x, x ∈ Y \ s)),
cases h_1 with z hz,
have hnl : ∀ z, z ∈ Y \ s → ¬(linear_independent R $ (λ y, y : (set.insert z (WHY s) : set M) → M)) :=
λ x hx hnl,
by {have huh := @nat.find_greatest_is_greatest (λ n, ∃ s : finset M, s ⊆ Y ∧
linear_independent R (λ x, x : (WHY s) → M) ∧ s.card = n) _ Y.card
⟨1, nat.succ_le_of_lt $ card_pos_of_ne_bot h hX, by
{cases finset.card_pos.1 (card_pos_of_ne_bot h hX) with c hc,
use {c}, split,
exact finset.singleton_subset_iff.2 hc, split,
rw linear_independent_subtype, intros l hlm hl,
cases subset_singleton ((finsupp.mem_supported _ _).1 hlm) with hl0 hlc,
rw ←finsupp.support_eq_empty, exact hl0,
rw single_of_singleton_support hlc at hl ⊢,
rw finsupp.total_single at hl,
rw finsupp.single_eq_zero,
exact or.resolve_right (htf ⟨c, hY hc⟩ (l c) (subtype.ext_iff.2 $ hl))
(λ h0, (finset.mem_erase.1 hc).1 $ subtype.ext_iff.1 h0),
exact finset.card_singleton _,
}⟩ n.succ (by {split, exact nat.lt_succ_self _, rw nat.succ_le_iff, simp only [n], erw ←hs.2.2,
apply finset.card_lt_card, rw finset.ssubset_iff_of_subset, use x,
rw ←finset.mem_sdiff, exact hx, exact hs.1}),
exact huh ⟨(insert x s), by {split, rw finset.insert_subset,split,
exact (finset.mem_sdiff.1 hx).1, exact hs.1, split,
simp only [*, not_exists, set.diff_singleton_subset_iff, submodule.mem_coe,
finset.coe_erase, not_and, finset.mem_sdiff, ne.def,
set.insert_eq_of_mem, submodule.zero_mem, finset.mem_erase] at *, convert hnl,
all_goals {try {exact finset.coe_insert _ _}},
rw finset.card_insert_of_not_mem, rw hs.2.2, exact (finset.mem_sdiff.1 hx).2,
}⟩, },
unfold linear_independent at hnl,
set r : R := finset.prod (finset.image (λ w : (↑(Y \ s) : set M),
dep_coeff s (w : M) $ hnl w w.2) (@finset.univ (↑(Y \ s) : set M) _)) id,
have hr0 : r ≠ 0 := prod_ne_zero Y s hnl hs.2.1,
have hrX : ∀ x, x ∈ X → r • x ∈ submodule.span R (↑s : set M) := sorry,
have hrS : ∀ x, x ∈ S → r • x ∈ submodule.span R (↑s : set M) := λ w hw,
by {rw ←hX at hw, rw ←set.image_id (↑X : set M) at hw, rcases
(finsupp.mem_span_iff_total R).1 hw with ⟨f, hfm, hf⟩,
rw ←hf, rw finsupp.total_apply, rw finsupp.smul_sum,
apply submodule.sum_mem (submodule.span R (↑s : set M)), intros c hc,
dsimp, rw ←mul_smul, rw mul_comm, rw mul_smul,
apply submodule.smul_mem (submodule.span R (↑s : set M)) (f c),
exact hrX c (hfm hc)
},
cases free_subm (↑s : set M) set.univ s.card (by { rw univ_card s, rw finset.card_univ,
apply fintype.card_congr, symmetry,
exact (equiv.set.univ _).symm,
}) (submodule.span R (↑s : set M) : set M) (λ x, ⟨x, submodule.subset_span x.2⟩)
⟨sorry, sorry⟩ (submodule.comap (submodule.span R (↑s : set M)).subtype
(submodule.map (r • linear_map.id) S)) with t ht,
let T := (λ x, r • x)⁻¹' (subtype.val '' t),
use T,
split, simp only [],
unfold linear_independent at *,
rw eq_bot_iff at *,
by_contradiction,
rcases submodule.not_le_iff_exists.1 a with ⟨f, hfm, hf⟩,
refine absurd ht.1 _,
apply submodule.not_le_iff_exists.2,
let sset : finset t := @finset.preimage _ _ (subtype.val ∘ subtype.val)
(finset.image (λ x : T, r • (x : M)) f.1) sorry,
let func : t → R := λ x, f.2 ⟨r • x, sorry⟩,
let F : t →₀ R := ⟨sset, func, sorry⟩,
use F,
split,
sorry, sorry,
ext i, split,
intro hmem,
sorry, sorry,
use (↑s : set M),
split,
exact hs.2.1,
rw ←hX,
have hsY : s = Y := le_antisymm hs.1 sorry,
rw hsY,
sorry,
end
theorem torsion_decomp {M : Type*} [add_comm_group M] [module R M] (S : submodule R M)
(hfg : S.fg) : ∃ t : set S, linear_independent R (λ x, x : t → S) ∧
(tors R S) ⊓ (submodule.span R t) = ⊥ ∧ (tors R S) ⊔ (submodule.span R t) = ⊤ :=
begin
cases free_of_tf (tors R S).quotient ⊤ (fg_quotient S hfg (tors R S))
(tf_iff.1 $ eq_bot_iff.2 $ λ b hb, by {have := eq_bot_iff.1 (tors_free_of_quotient R S),
rcases hb with ⟨c, hc⟩,
have h0 : c • (b : (tors R S).quotient) = 0 := by {rw ←submodule.coe_smul,
rw ←@submodule.coe_zero R (tors R S).quotient _ _ _ ⊤, congr, exact hc.2 },
have ffs := this ⟨c, hc.1, h0⟩,
rw submodule.mem_bot at ffs ⊢, rw subtype.ext_iff,
rw ffs, refl}
) with t ht,
cases (projective_of_has_basis ht S (tors R S).quotient linear_map.id (tors R S).mkq
(λ x, quotient.induction_on' x $ λ y, ⟨y, rfl⟩)) with f hf,
have HP := split_of_left_inv (tors R S) (tors R S).mkq (by {rw submodule.ker_mkq,
rw submodule.range_subtype}) f (linear_map.ext hf) (submodule.range_mkq _),
use (set.range ((f : _ → S) ∘ subtype.val : t → S)),
split,
apply linear_independent.to_subtype_range,
apply linear_independent.restrict_of_comp_subtype,
rw linear_independent_comp_subtype,
intros l hlm hl,
apply (linear_independent_subtype.1 ht.1 l hlm),
rw finsupp.total_apply at *,
apply f.to_add_monoid_hom.injective_iff.1 (function.left_inverse.injective hf),
rw ←hl,
erw (finset.sum_hom l.support f).symm,
apply finset.sum_congr rfl,
intros x hx, dsimp,
rw linear_map.map_smul,
convert HP, all_goals
{rw ←set.image_univ,
rw set.image_comp, rw submodule.span_image,
show _ = (⊤ : submodule R (tors R S).quotient).map f,
congr, convert ht.2, rw set.image_univ, refl},
end
def tf_basis {M : Type*} [add_comm_group M] [module R M] (S : submodule R M)
(hfg : S.fg) := classical.some (torsion_decomp S hfg)
theorem tf_basis_is_basis {M : Type*} [add_comm_group M] [module R M] (S : submodule R M)
(hfg : S.fg) : linear_independent R (λ x, x : tf_basis S hfg → S) :=
(classical.some_spec (torsion_decomp S hfg)).1
theorem disjoint_tors_tf {M : Type*} [add_comm_group M] [module R M] {S : submodule R M}
(hfg : S.fg) : (tors R S) ⊓ (submodule.span R $ tf_basis S hfg) = ⊥ :=
(classical.some_spec (torsion_decomp S hfg)).2.1
theorem tors_tf_span {M : Type*} [add_comm_group M] [module R M] {S : submodule R M}
(hfg : S.fg) : (tors R S) ⊔ (submodule.span R $ tf_basis S hfg) = ⊤ :=
(classical.some_spec (torsion_decomp S hfg)).2.2 |
(* ------------------------------------------------------- *)
(** #<hr> <center> <h1>#
The double time redundancy (DTR) transformation
#</h1>#
- Main properties and theorem
Dmitry Burlyaev - Pascal Fradet - 2015
#</center> <hr># *)
(* ------------------------------------------------------- *)
Add LoadPath "..\..\Common\".
Add LoadPath "..\..\TMRProof\".
Add LoadPath "..\Transf\".
Add LoadPath "..\controlBlock\".
Add LoadPath "..\inputBuffers\".
Add LoadPath "..\outputBuffers\".
Add LoadPath "..\memoryBlocks\".
Require Import dtrTransform relationPred.
Require Import inputLib controlLib outputLib memoryLib.
Require Import globalInv globalStep globalLem1 globalSeqs.
Set Implicit Arguments.
(* ------------------------------------------------------- *)
Lemma stepg_In1: forall S T (i0 i1 i2 i3 i4 i5: {|S|})
(o0 o1 o2 o3 o4 o5: {|T|})
(oo1 oo2 oo3 oo4 oo5 oo6 oo7 oo8 oo9:{|T # (T # T)|})
(c0 c1 c2 c3 c4 c5 c6: circuit S T)
(cc1 cc2 cc2' cc3 cc3' cc4 cc4' cc5 cc5' cc6: circuit S (T # (T # T))),
pure_bset {i0,i1,i2,i3,i4,i5,o0,o1,o2,o3,o4,o5}
-> Dtrs1 (ibs1 i1 i0) (obs1 o1 o0) c0 c1 c2 cc1
-> step c1 i1 o1 c2
-> step c2 i2 o2 c3
-> step c3 i3 o3 c4
-> step c4 i4 o4 c5
-> step c5 i5 o5 c6
-> stepg cc1 i1 oo1 cc2
-> step cc2 i2 oo2 cc2'
-> step cc2' i2 oo3 cc3
-> step cc3 i3 oo4 cc3'
-> step cc3' i3 oo5 cc4
-> step cc4 i4 oo6 cc4'
-> step cc4' i4 oo7 cc5
-> step cc5 i5 oo8 cc5'
-> step cc5' i5 oo9 cc6
-> atleast2 o0 oo1
/\ atleast2 o1 oo3
/\ atleast2 o2 oo5
/\ atleast2 o3 oo7
/\ atleast2 o4 oo9
/\ Dtrs0 (ibs0 i5) (obs0 o5 o4) c5 c6 cc6.
Proof.
introv P D (* S1 *) S2 S3 S4 S5 S6.
introv SS1 SS2 SS3 SS4 SS5 SS6 SS7 SS8 SS9. SimpS.
Inverts D. Inverts SS1. Inverts H19. Inverts H21.
(* Glitch occuring inside *)
- eapply glitch_in_GC. 2:exact H22. 2:exact H18. 2:exact H20. 2:exact H19.
2: exact S2. 2:exact S3. 2:exact S4. 2:exact S5.
2:exact S6. 2:exact SS2. 2:exact SS3. 2:exact SS4.
2:exact SS5. 2:exact SS6. 2:exact SS7. 2:exact SS8.
2:exact SS9. 2:exact H23. CheckPure.
(* possible glitch in the triplicated fail signal to control block *)
- eapply glitch_in_3fail. 2: exact H22. 2: exact H18. 2: exact H20. 2: exact H23.
2: exact H19. 2: exact S2. 2: exact S3. 2: exact S4.
2: exact S5. 2: exact S6. 2: exact SS2. 2: exact SS3.
2: exact SS4. 2: exact SS5. 2: exact SS6. 2: exact SS7.
2: exact SS8. 2: exact SS9. 2: exact H24. CheckPure.
- Inverts H23.
eapply invstepcore in H24; try easy.
unfold PexInvDTR1 in H24. SimpS.
Inverts H20.
+ eapply step1_tcbv_i in H12; try (solve [constructor]). SimpS.
Apply step_ibs in H11; try apply pure_buildBus. SimpS. Purestep H13.
Apply step1_mb with H22 S2 in H13. SimpS. Purestep H14.
Apply step_obs_sf in H14. SimpS.
Apply invstepDTRc in SS2. SimpS.
Apply step0_tcbv_C in H14. SimpS.
Apply step_ibs in H11; try apply pure_buildBus. SimpS.
Apply step0_mb with H20 S3 in H18. SimpS.
Apply step0_obs_sbf in H21. SimpS.
assert (D: Dtrs1 (ibs1 i2 i1) (obs1 o2 o1) c1 c2 c3
(globcir (false,false,false) cbs1 (ibs1 i2 i1) x43 (obs1 o2 o1)))
by (constructor; try easy).
Apply step_Dtrs1 with S3 SS3 in D. SimpS.
split. easy. split. easy.
eapply sixsteps. 2:exact H18. 2:exact S4. 2:exact S5. 2:exact S6.
2:exact SS4. 2:exact SS5. 2:exact SS6. 2:exact SS7.
2:exact SS8. 2:exact SS9. CheckPure.
(* no glitch *)
+ eapply step1_tcbv in H12; try (solve [constructor]). SimpS.
Apply step_ibs in H11; try apply pure_buildBus. SimpS.
Apply step1_mb with H22 S2 in H13. SimpS.
Apply step_obs_sf in H14.
assert (X: pure_bset (orS {bool2bset x21, bool2bset (negb (beq_buset_t o1 o0))}))
by (Apply pure_orS). SimpS.
assert (D: Dtrs0 (ibs0 i1) (obs0 o1 o0) c1 c2
(globcir (b',b',b') cbs0 (ibs0 i1) x42 (obs0 o1 o0)))
by (constructor; try easy).
split. easy.
eapply eightsteps. 2:exact D. 2:exact S3. 2:exact S4. 2:exact S5. 2:exact S6.
2: exact SS2. 2:exact SS3. 2:exact SS4. 2:exact SS5.
2:exact SS6. 2:exact SS7. 2:exact SS8. 2:exact SS9. CheckPure.
- Inverts H20. Inverts H23.
Apply invstepcore in H24.
unfold PexInvDTR1 in H24. SimpS.
Inverts H18.
+ eapply step1_tcbv_i in H12; try (solve [constructor]). SimpS.
Apply step_ibs in H11; try apply pure_buildBus. SimpS. Purestep H13.
Apply step1_mb with H22 S2 in H13. SimpS. Purestep H14.
Apply step_obs_sf in H14. SimpS.
Apply invstepDTRc in SS2. SimpS.
Apply step0_tcbv_C in H14. SimpS.
Apply step_ibs in H11; try apply pure_buildBus. SimpS.
Apply step0_mb with H18 S3 in H19. SimpS.
Apply step0_obs_sbf in H21. SimpS.
assert (D: Dtrs1 (ibs1 i2 i1) (obs1 o2 o1) c1 c2 c3
(globcir (false,false,false) cbs1 (ibs1 i2 i1) x43 (obs1 o2 o1)))
by (constructor; try easy).
Apply step_Dtrs1 with S3 SS3 in D. SimpS.
split. easy. split. easy.
eapply sixsteps. 2:exact H19. 2:exact S4. 2:exact S5. 2:exact S6.
2:exact SS4. 2:exact SS5. 2:exact SS6. 2:exact SS7.
2:exact SS8. 2:exact SS9. CheckPure.
+ (* no glitch *)
eapply step1_tcbv in H12; try (solve [constructor]). SimpS.
Apply step_ibs in H11; try apply pure_buildBus. SimpS.
Apply step1_mb with H22 S2 in H13. SimpS.
Apply step_obs_sf in H14.
assert (X: pure_bset (orS {bool2bset x21, bool2bset (negb (beq_buset_t o1 o0))}))
by (Apply pure_orS). SimpS.
assert (D: Dtrs0 (ibs0 i1) (obs0 o1 o0) c1 c2
(globcir (b',b',b') cbs0 (ibs0 i1) x42 (obs0 o1 o0)))
by (constructor; try easy).
split. easy.
eapply eightsteps. 2:exact D. 2:exact S3. 2:exact S4. 2:exact S5. 2:exact S6.
2: exact SS2. 2:exact SS3. 2:exact SS4. 2:exact SS5.
2:exact SS6. 2:exact SS7. 2:exact SS8. 2:exact SS9. CheckPure.
Qed.
|
Formal statement is: theorem Cauchy_integral_formula_convex_simple: assumes "convex S" and holf: "f holomorphic_on S" and "z \<in> interior S" "valid_path \<gamma>" "path_image \<gamma> \<subseteq> S - {z}" "pathfinish \<gamma> = pathstart \<gamma>" shows "((\<lambda>w. f w / (w - z)) has_contour_integral (2*pi * \<i> * winding_number \<gamma> z * f z)) \<gamma>" Informal statement is: If $f$ is holomorphic on a convex set $S$ and $z$ is an interior point of $S$, then the Cauchy integral formula holds for $f$ and $z$. |
module PowerMethod where
import Control.Monad as M
import Data.Complex
import Data.List as L
import Numeric.LinearAlgebra as NL
import System.Environment
import System.Random
import Text.Printf
{-# INLINE iterateM #-}
iterateM :: Int -> (b -> a -> IO a) -> b -> a -> IO a
iterateM 0 _ _ x = return x
iterateM n f x y = do
z <- f x y
iterateM (n - 1) f x $! z
{-# INLINE getComplexStr #-}
getComplexStr :: (Complex Double) -> String
getComplexStr (a :+ b) = printf "%.2f :+ %.2f" a b
{-# INLINE getComplexStr' #-}
getComplexStr' :: (Complex Double) -> String
getComplexStr' x =
let (a, b) = polar x
in printf "(%.2f, %.2f)" a b
{-# INLINE getListStr #-}
getListStr :: (a -> String) -> [a] -> String
getListStr f (x:xs) =
printf "[%s%s]" (f x) . L.concatMap (\x -> " ," L.++ f x) $ xs
main = do
(nStr:_) <- getArgs
let range = (-1, 1)
matInit1 <- M.replicateM 4 (randomRIO range) :: IO [Double]
matInit2 <- M.replicateM 4 (randomRIO range) :: IO [Double]
vecInit1 <- M.replicateM 2 (randomRIO range) :: IO [Double]
vecInit2 <- M.replicateM 2 (randomRIO range) :: IO [Double]
let n = read nStr :: Int
mat' = (2 >< 2) $ L.zipWith (:+) matInit1 matInit2
vec' = NL.fromList $ L.zipWith (:+) vecInit1 vecInit2
(eigVal, eigVec) = eig mat'
eigVecs = toColumns eigVec
print mat'
out <-
iterateM
n
(\mat vec -> do
let newVec = mat #> vec
maxMag = L.maximum . L.map magnitude . NL.toList $ newVec
(a:b:_) = NL.toList newVec
phaseNorm x =
let (m, p) = polar x
in mkPolar 1 p
norm =
if magnitude a > magnitude b
then a
else b
normalizedNewVec = newVec / (scalar norm)
printf
"Maximum magnitude: %.2f %s\n"
maxMag
(getListStr getComplexStr' . NL.toList $ normalizedNewVec)
return normalizedNewVec)
mat'
vec'
let s = sqrt . L.sum . L.map (\x -> (magnitude x) ^ 2) . NL.toList $ out
printf
"%s\n"
(getListStr getComplexStr' . L.map (/ (s :+ 0)) . NL.toList $ out)
M.zipWithM_
(\val vec ->
printf
"%.2f %s\n"
(magnitude val)
(getListStr getComplexStr' . NL.toList $ vec))
(NL.toList eigVal)
eigVecs
print eigVal
print eigVecs
|
---
author: Nathan Carter ([email protected])
---
This answer assumes you have imported SymPy as follows.
```python
from sympy import * # load all math functions
init_printing( use_latex='mathjax' ) # use pretty math output
```
Let's consider the example of the unit circle, $x^2+y^2=1$.
To plot it, SymPy first expects us to move everything to the left-hand side
of the equation, so in this case, we would have $x^2+y^2-1=0$.
We then use that left hand side to represent the equation as a single formula,
and we can plot it with SymPy's `plot_implicit` function.
```python
var( 'x y' )
formula = x**2 + y**2 - 1 # to represent x^2+y^2=1
plot_implicit( formula )
```
|
[STATEMENT]
lemma if_eval_elim':
"\<lbrakk> \<langle>If e c\<^sub>1 c\<^sub>2, mds, mem\<rangle> \<leadsto> \<langle>c', mds', mem'\<rangle> \<rbrakk> \<Longrightarrow>
((c' = c\<^sub>1 \<and> ev\<^sub>B mem e) \<or> (c' = c\<^sub>2 \<and> \<not> ev\<^sub>B mem e)) \<and> mds' = mds \<and> mem' = mem"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<langle>Stmt.If e c\<^sub>1 c\<^sub>2, mds, mem\<rangle> \<leadsto> \<langle>c', mds', mem'\<rangle> \<Longrightarrow> (c' = c\<^sub>1 \<and> ev\<^sub>B mem e \<or> c' = c\<^sub>2 \<and> \<not> ev\<^sub>B mem e) \<and> mds' = mds \<and> mem' = mem
[PROOF STEP]
using if_eval_elim [where annos = "[]"]
[PROOF STATE]
proof (prove)
using this:
\<langle>Stmt.If ?e ?c\<^sub>1 ?c\<^sub>2 \<otimes> [], ?mds, ?mem\<rangle> \<leadsto> \<langle>?c', ?mds', ?mem'\<rangle> \<Longrightarrow> (?c' = ?c\<^sub>1 \<and> ev\<^sub>B ?mem ?e \<or> ?c' = ?c\<^sub>2 \<and> \<not> ev\<^sub>B ?mem ?e) \<and> ?mds' = ?mds \<oplus> [] \<and> ?mem' = ?mem
goal (1 subgoal):
1. \<langle>Stmt.If e c\<^sub>1 c\<^sub>2, mds, mem\<rangle> \<leadsto> \<langle>c', mds', mem'\<rangle> \<Longrightarrow> (c' = c\<^sub>1 \<and> ev\<^sub>B mem e \<or> c' = c\<^sub>2 \<and> \<not> ev\<^sub>B mem e) \<and> mds' = mds \<and> mem' = mem
[PROOF STEP]
by auto |
lemma map_poly_map_poly: assumes "f 0 = 0" "g 0 = 0" shows "map_poly f (map_poly g p) = map_poly (f \<circ> g) p" |
lemma cball_empty [simp]: "e < 0 \<Longrightarrow> cball x e = {}" |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Brief background for derivation of the cable equation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
See \cite{lindsay_2004} for a detailed derivation of the cable equation, and extensions to the one-dimensional model that account for radial variation of potential.
The one-dimensional cable equation introduced later in equations~\eq{eq:cable} and~\eq{eq:cable_balance} is based on the following expression in three dimensions (based on Maxwell's equations adapted for neurological modelling)
\begin{equation}
\nabla \cdot \vv{J} = 0,
\label{eq:J}
\end{equation}
where $\vv{J}$ is current density (units $A/m^2$).
Current density is in turn defined in terms of electric field $\vv{E}$ (units $V/m$)
\begin{equation}
\vv{J} = \sigma \vv{E},
\end{equation}
where $\sigma$ is the specific electrical conductivity of intra-cellular fluid (typically 3.3 $S/m$).
The derivation of the cable equation is based on two assumptions:
\begin{enumerate}
\item that charge disperion is effectively instantaneous for the purposes of dendritic modelling.
\item that diffusion of magnetic field is instant, i.e. it behaves quasi-statically in the sense that it is determined by the electric field through the Maxwell equations.
\end{enumerate}
Under these conditions, $\vv{E}$ is conservative, and as such can be expressed in terms of a potential field
\begin{equation}
\vv{E} = \nabla \phi,
\end{equation}
where the extra/intra-cellular potential field $\phi$ has units $mV$.
The derivation of the one-dimensional conservation equation \eq{eq:cable_balance} is based on the assumption that the intra-cellular potential (i.e. inside the cell) does not vary radially.
That is, potential is a function of the axial distance $x$ alone
\begin{equation}
\vv{E} = \nabla \phi = \pder{V}{x}.
\end{equation}
This is not strictly true, because a potential field that is a variable of $x$ and $t$ alone can't support the axial gradients required to drive the potential difference over the cell membrane.
I am still trying to get my head around the assumptions made in mapping a three-dimensional problem to a pseudo one-dimensional one.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{The cable equation}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The cable equation is a nonlinear parabolic PDE that can be written in the form
\begin{equation}
\label{eq:cable}
c_m \pder{V}{t} = \frac{1}{2\pi a r_{L}} \pder{}{x} \left( a^2 \pder{V}{x} \right) - i_m + i_e,
\end{equation}
where
\begin{itemize}
\item $V$ is the potential relative to the ECM $[mV]$
\item $a$ is the cable radius $(mm)$, and can vary with $x$
\item $c_m$ is the {specific membrane capacitance}, approximately the same for all neurons $\approx 10~nF/mm^2$. Related to \emph{membrane capacitance} $C_m$ by the relationship $C_m=c_{m}A$, where $A$ is the surface area of the cell.
\item $i_m$ is the membrane current $[A\cdot/mm^{2}]$ per unit area. The total contribution from ion and synaptic channels is expressed as a the product of current per unit area $i_m$ and the surface area.
\item $i_e$ is the electrode current flowing into the cell, divided by surface area, i.e. $i_e=I_e/A$.
\item $r_L$ is intracellular resistivity, typical value $1~k\Omega \text{cm}$
\end{itemize}
Note that the standard convention is followed, whereby membrane and synapse currents ($i_m$) are positive when outward, and electrod currents ($i_e$) are positive inward.
The PDE in (\ref{eq:cable}) is derived by integrating~\eq{eq:J} over the volume of segment $i$:
\begin{equation*}
\int_{\Omega_i}{\nabla \cdot \vv{J} } \deriv{v} = 0,
\end{equation*}
Then applying the divergence theorem to turn the volume integral on the lhs into a surface integral
\begin{equation}
\sum_{j\in\mathcal{N}_i} {\int_{\Gamma_{i,j}} J_{i,j} \deriv{s} }
+ \int_{\Gamma_{i}} {J_m} \deriv{s} = 0
\label{eq:cable_balance_intermediate}
\end{equation}
where
\begin{itemize}
\item $\int_\Omega \cdot \deriv{v}$ is shorthand for the volume integral over the segment $\Omega_i$
\item $\int_\Gamma \cdot \deriv{s}$ is shorthand for the surface integral over the surface $\Gamma$
\item $J_{i,j}=-\frac{1}{r_L}\pder{V}{x} n_{i,j}$ is the flux per unit area of current \emph{from segment $i$ to segment $j$} over the interface $\Gamma_{i,j}$ between the two segments.
\item the set $\mathcal{N}_i$ is the set of segments that are neighbours of $\Omega_i$
\end{itemize}
The transmembrane current density $J_m=\vv{J}\cdot\vv{n}$ is a function of the membrane potential
\begin{equation}
J_m = c_m\pder{V}{t} + i_m - i_e,
\label{eq:Jm}
\end{equation}
which has contributions from the ion channels and synapses ($i_m$), electrodes ($i_e$) and capacitive current due to polarization of the membrane whose bi-layer lipid structure causes it to behave locally like a parallel plate capacitor.
Substituting~\eq{eq:Jm} into~\eq{eq:cable_balance_intermediate} and rearanging gives
\begin{equation}
\int_{\Gamma_{i}} {c_m\pder{V}{t}} \deriv{s}
= - \sum_{j\in\mathcal{N}_i} {\int_{\Gamma_{i,j}} J_{i,j} \deriv{s} }
- \int_{\Gamma_{i}} {(i_m - i_e)} \deriv{s}
\label{eq:cable_balance}
\end{equation}
The surface of the cable segment is sub-divided into the internal and external surfaces.
The external surface $\Gamma_{i}$ is the cell membrane at the interface between the extra-cellular and intra-cellular regions.
The current, which is the conserved quantity in our conservation law, over the surface is composed of the synapse and ion channel contributions.
This is derived from a thin film approximation to the cell membrane, whereby the membrane is treated as an infinitesimally thin interface between the intra and extra cellular regions.
Note that some information is lost when going from a three-dimensional description of a neuron to a system of branching one-dimensional cable segments.
If the cell is represented by cylinders or frustrums\footnote{a frustrum is a truncated cone, where the truncation plane is parallel to the base of the cone.}, the three-dimensional values for volume and surface area at branch points can't be retrieved from the one-dimensional description.
\begin{figure}
\begin{center}
\includegraphics[width=0.5\textwidth]{./images/cable.pdf}
\end{center}
\caption{A single segment, or control volume, on an unbranching dendrite.}
\label{fig:segment}
\end{figure}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Finite volume discretization}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The finite volume method is a natural choice for the solution of the conservation law in~\eq{eq:cable_balance}.
\begin{itemize}
\item the $x_i$ are spaced uniformly with distance $x_{i+1}-x_{i} = \Delta x$
\item control volumes are formed by locating the boundaries between adjacent points at $(x_{i+1}+x_{i})/2$
\item this discretization differs from the finite differences used in Neuron because the equation is explicitly solved for at the end of cable segments, and because the finite volume discretization is applied to all points. Neuron uses special algebraic \emph{zero area} formulation for nodes at branch points.
\end{itemize}
%-------------------------------------------------------------------------------
\subsubsection{Temporal derivative}
%-------------------------------------------------------------------------------
The integral on the lhs of~\eq{eq:cable_balance} can be approximated by assuming that the average transmembrane potential $V$ in $\Omega_i$ is equal to the potential $V_i$ defined at the centre of the segment:
\begin{equation}
\int_{\Gamma_i}{c_m \pder{V}{t} } \deriv{v} \approx \sigma_i \cmi \pder{V_i}{t},
\label{eq:dvdt}
\end{equation}
where $\sigma_i$ is the surface area, and $\cmi$ is the average specific membrane capacitance, respectively of the surface $\Gamma_i$.
Each control volume is composed of \emph{sub control volumes}, which are illustrated as the coloured sub-regions in \fig{fig:segment}.
\begin{equation*}
\Omega_i = \bigcup_{j\in\mathcal{N}_i}{\Omega_i^j}.
\end{equation*}
Likewise, the surface $\Gamma_i$ is composed of subsufaces as follows
\begin{equation*}
\Gamma_i = \bigcup_{j\in\mathcal{N}_i}{\Gamma_i^j},
\end{equation*}
where $\Gamma_i^j$ is the surface of each of the sub-control volumes in $\Omega_i$.
Thus, the surface area of the CV as
\begin{equation*}
\sigma_i = \sum_{i\in\mathcal{N}_i}{\sigma_i^j},
\end{equation*}
where $\sigma_i^j$ is the area of $\Gamma_i^j$, and the average specific membrane capacitance $\cmi$ is
\begin{equation*}
\cmi = \frac{1}{\sigma_i}\sum_{i\in\mathcal{N}_i}{\sigma_i^j c_m^{i,j}}.
\end{equation*}
\todo{This is included as a placeholder, we really need more illustrations to show how CV averages are computed for quantities that vary between sub-control volumes of the same CV.}
%-------------------------------------------------------------------------------
\subsubsection{Intra-cellular flux}
%-------------------------------------------------------------------------------
The intracellular flux terms in~\eq{eq:cable_balance} are sum of the flux over the interfaces between compartment $i$ and its set of neighbouring compartments $\mathcal{N}_i$ is
\begin{equation}
\sum_{j\in\mathcal{N}_i} { \int_{\Gamma_{i,j}} { J_{i,j} \deriv{s} } }.
\end{equation}
where the flux per unit area from compartment $i$ to compartment $j$ is
\begin{align}
J_{i,j} = - \frac{1}{r_L}\pder{V}{x} n_{i,j}.
\label{eq:J_ij_exact}
\end{align}
The derivative with respect to the outward-facing normal can be approximated as follows
\begin{equation*}
\pder{V}{x} n_{i,j} \approx \frac{V_j - V_i}{\Delta x_{i,j}}
\end{equation*}
where $\Delta x_{i,j}$ is the distance between $x_i$ and $x_j$, i.e. $\Delta x_{i,j}=|x_i-x_j|$.
Using this approximation for the derivative, the flux over the surface in~\eq{eq:J_ij_exact} is approximated as
\begin{align}
J_{i,j} \approx \frac{1}{r_L}\frac{V_i - V_j}{\Delta x_{i,j}}.
\label{eq:J_ij_intermediate}
\end{align}
The terms inside the integral in equation~\eq{eq:J_ij_intermediate} are constant everywhere on the surface $\Gamma_{i,j}$, so the integral becomes
\begin{align}
J_{i,j} &\approx \int_{\Gamma_{i,j}} \frac{1}{r_L}\frac{V_i-V_j}{\Delta x_{i,j}} \deriv{s} \nonumber \\
&= \frac{1}{r_L \Delta x_{i,j}}(V_i-V_j) \int_{\Gamma_{i,j}} 1 \deriv{s} \nonumber \\
&= \frac{\sigma_{ij}}{r_L \Delta x_{i,j}}(V_i-V_j) \nonumber \\
\label{eq:J_ij}
\end{align}
where $\sigma_{i,j}=\pi a_{i,j}^2$ is the area of the surface $\Gamma_{i,j}$, which is a circle of radius $a_{i,j}$.
Some symmetries
\begin{itemize}
\item $\sigma_{i,j}=\sigma_{j,i}$ : surface area of $\Gamma_{i,j}$
\item $\Delta x_{i,j}=\Delta x_{j,i}$ : distance between $x_i$ and $x_j$
\item $n_{i,j}=-n_{j,i}$ : surface ``norm''/orientation
\item $J_{i,j}=n_{j,i}\cdot J_{i,j}=-J_{j,i}$ : charge flux over $\Gamma_{i,j}$
\end{itemize}
%-------------------------------------------------------------------------------
\subsubsection{Cell membrane flux}
%-------------------------------------------------------------------------------
The final term in~\eq{eq:cable_balance} with an integral is the cell membrane flux contribution
\begin{equation}
\int_{\Gamma_{ext}} {(i_m - i_e)} \deriv{s},
\end{equation}
where the current $i_m$ is due to ion channel and synapses, and $i_e$ is any artificial electrode current.
The $i_m$ term is dependent on the potential difference over the cell membrane $V_i$.
The current terms are an average per unit area, therefore the total flux
\begin{equation}
\int_{\Gamma_{ext}} {(i_m - i_e)} \deriv{s}
\approx
\sigma_i(i_m(V_i) - i_e(x_i)),
\label{eq:J_im}
\end{equation}
where $\sigma_i$ is the surface area the of the exterior of the cable segment, i.e. the surface corresponding to the cell membrane.
Each cable segment is a conical frustrum, as illustrated in \fig{fig:segment}.
The lateral surface area of a frustrum with height $\Delta x_i$ and radii of is
The area of the external surface $\Gamma_{i}$ is
\begin{equation}
\sigma_i = \pi (a_{i,\ell} + a_{i,r}) \sqrt{\Delta x_i^2 + (a_{i,\ell} - a_{i,r})^2},
\label{eq:cv_volume}
\end{equation}
where $a_{i,\ell}$ and $a_{i,r}$ are the radii of at the left and right end of the segment respectively (see~\eq{eq:frustrum_area} for derivation of this formula).
%-------------------------------------------------------------------------------
\subsubsection{Putting it all together}
%-------------------------------------------------------------------------------
By substituting the volume averaging of the temporal derivative in~\eq{eq:dvdt} approximations for the flux over the surfaces in~\eq{eq:J_ij} and~\eq{eq:cv_volume} respectively into the conservation equation~\eq{eq:cable_balance} we get the following ODE defined for each node in the cell
\begin{equation}
\sigma_i \cmi \dder{V_i}{t}
= -\sum_{j\in\mathcal{N}_i} {\frac{\sigma_{i,j}}{r_L \Delta x_{i,j}} (V_i-V_j)} - \sigma_i\cdot(i_m(V_i) - i_e(x_i)),
\label{eq:ode}
\end{equation}
where
\begin{equation}
\sigma_{i,j} = \pi a_{i,j}^2
\label{eq:sigma_ij}
\end{equation}
is the area of the surface between two adjacent segments $i$ and $j$, and
\begin{equation}
\sigma_{i} = \pi(a_{i,\ell} + a_{i,r}) \sqrt{\Delta x_i^2 + (a_{i,\ell} - a_{i,r})^2},
\label{eq:sigma_i}
\end{equation}
is the lateral area of the conical frustrum describing segment $i$.
%-------------------------------------------------------------------------------
\subsubsection{Time Stepping}
%-------------------------------------------------------------------------------
The finite volume discretization approximates spatial derivatives, reducing the original continuous formulation into the set of ODEs, with one ODE for each compartment, in equation~\eq{eq:ode}.
Here we employ an implicit euler temporal integration sheme, wherby the temporal derivative on the lhs is approximated using forward differences
\begin{align}
\sigma_i c_m \frac{V_i^{k+1}-V_i^{k}}{\Delta t}
= & -\sum_{j\in\mathcal{N}_i} {\frac{\sigma_{i,j}}{r_L \Delta x_{i,j}} (V_i^{k+1}-V_j^{k+1})} \nonumber \\
& - \sigma_i\cdot(i_m(V_i^{k}) - i_e),
\label{eq:ode_subs}
\end{align}
Where $V^k$ is the value of $V$ in compartment $i$ at time step $k$.
Note that on the rhs the value of $V$ at the target time step $k+1$ is used, with the exception of calculating the ion channel and synaptic currents $i_m$.
The current $i_m$ is often a nonlinear function of voltage, so if it was formulated in terms of $V^{k+1}$ the system in~\eq{eq:ode_subs} would be nonlinear, requiring Newton iterations to resolve.
The equations can be rearranged to have all unknown voltage values on the lhs, and values that can be calculated directly on the rhs:
\begin{align}
& \frac{\sigma_i \cmi}{\Delta t} V_i^{k+1} + \sum_{j\in\mathcal{N}_i} {\alpha_{ij} (V_i^{k+1}-V_j^{k+1})}
\nonumber \\
= & \frac{\sigma_i \cmi}{\Delta t} V_i^k - \sigma_i(i_m^{k} - i_e),
\label{eq:ode_linsys}
\end{align}
where the value
\begin{equation}
\alpha_{ij} = \alpha_{ji} = \frac{\sigma_{ij}}{ r_L \Delta x_{ij}}
\label{eq:alpha_linsys}
\end{equation}
is a constant that can be computed for each interface between adjacent compartments during set up.
The left hand side of \eq{eq:ode_linsys} can be rearranged
\begin{equation}
\left[ \frac{\sigma_i \cmi}{\Delta t} + \sum_{j\in\mathcal{N}_i} {\alpha_{ij}} \right] V_i^{k+1}
- \sum_{j\in\mathcal{N}_i} { \alpha_{ij} V_j^{k+1}},
\label{eq:rhs_linsys}
\end{equation}
which gives the coefficients for the linear system.
The capacitance of the cell membrane, $\sigma_i \cmi$, varies between control volumes, while the $\alpha_{i,j}$ term in symmetric (i.e. $\alpha_{i,j}=\alpha_{j,i}$.)
With this in mind, we can see that when the linear system is written in the form~\eq{eq:ode_linsys}, the matrix is symmetric.
Furthermore, because $\alpha_{i,j} > 0$, the linear system is diagonally dominant for sufficiently small $\Delta t$.
%-------------------------------------------------------------------------------
\subsubsection{The Soma}
%-------------------------------------------------------------------------------
We model the soma as a sphere with a centre $\vv{x}_s$ and a radius $r_s$.
The soma is conceptually treated as the center of the cell: the point from which all other parts of the cell branch.
It requires special treatment, because of its size relative to the radius of the dendrites and axons that branch off from it.
Though the soma is usually visualized as a sphere, it is \emph{worth noting} that Neuron models the soma as a cylinder
\begin{itemize}
\item A cylinder that has the same diameter as length ($L=2r$) has the same area as a sphere with radius $r$, i.e. $4\pi r^2$.
\item However a sphere has 4/3 times the volume of the cylinder.
\end{itemize}
If the soma is modelled as a single compartment the potential is assumed constant throughout the cell.
This is exactly the same model used to handle branches, with the main difference being how the area and volume of the control volume centred on the soma are calculated as a result of the spherical model.
\begin{figure}
\begin{center}
\includegraphics[width=0.5\textwidth]{./images/soma.pdf}
\end{center}
\caption{A soma with two dendrites.}
\label{fig:soma}
\end{figure}
\fig{fig:soma} shows a soma that is attached to two unbranched dendrites.
In this example the simplest possible compartment model is used, with three compartments: one for the soma and one for each of the dendrites.
The soma CV extends to half way along each dendrite.
To calculate the flux from the soma compartment to the dendrites the flux over the CV face half way along each dendrite has to be computed.
For this we use the voltage defined at each end of the dendrite, which raises the question about what value to use for the end of the dendrite that is attached to the soma.
For this we use the voltage as defined for the soma, i.e. we use the same value at the start for each dendrite, as illustrated in \fig{fig:soma}.
This effectivly of ``collapses'' the node that defines the start of dendrites attached to the soma onto the soma in the mathematical formulation.
This requires a little slight of hand when loading the cell description from file (for example a \verb!.swc! file).
In such file formats there would be 5 points used to describe the cell in \fig{fig:soma}:
\begin{itemize}
\item 1 to describe the center of the soma.
\item 2 for each dendrite: 1 describing where the dendrite is attached to the soma, and 1 for the terminal end.
\end{itemize}
However, in the mathematical formulation there are only 3 values that are solved for: the soma and one for each of the dendrites.
On a side note, one possible extension is to model the soma as a set of shells, like an onion.
Conceptually this would look like an additional branch from the surface of the soma, with the central core being the terminal of the branch.
However, the cable equation would have to be reformulated in spherical coordinates.
%-------------------------------------------------------------------------------
\subsubsection{Handling Branches}
%-------------------------------------------------------------------------------
The value of the lateral area $\sigma_i$ in~\eq{eq:sigma_i} is the sum of the areaof each branch at branch points.
\todo{a picture of a branching point to illustrate}
\todo{a picture of a soma to illustrate the ball and stick model with a sphere for the soma and sticks for the dendrites branching off the soma.}
\begin{equation}
\sigma_i = \sum_{j\in\mathcal{N}_i} {\dots}
\end{equation}
|
module Js.Json
{-
import public Lightyear
import public Lightyear.Char
import public Lightyear.Strings
import Pruviloj.Core
import public Data.SortedMap
public export
data JsonValue = JsonString String
| JsonNumber Double
| JsonBool Bool
| JsonNull
| JsonArray (List JsonValue)
| JsonObject (SortedMap String JsonValue)
{-
export
Eq JsonValue where
(==) (JsonString x) (JsonString y) = x == y
(==) (JsonNumber x) (JsonNumber y) = x == y
(==) JsonNull JsonNull = True
(==) (JsonArray x) (JsonArray y) = x == y
(==) (JsonObject x) (JsonObject y) = toList x == toList y
(==) _ _ = False
-}
export
Show JsonValue where
show (JsonString s) = show s
show (JsonNumber x) = show x
show (JsonBool True ) = "true"
show (JsonBool False) = "false"
show JsonNull = "null"
show (JsonArray xs) = show xs
show (JsonObject xs) =
"{" ++ intercalate ", " (map fmtItem $ SortedMap.toList xs) ++ "}"
where
intercalate : String -> List String -> String
intercalate sep [] = ""
intercalate sep [x] = x
intercalate sep (x :: xs) = x ++ sep ++ intercalate sep xs
fmtItem (k, v) = show k ++ ": " ++ show v
hex : Parser Int
hex = do
c <- map (ord . toUpper) $ satisfy isHexDigit
pure $ if c >= ord '0' && c <= ord '9' then c - ord '0'
else 10 + c - ord 'A'
hexQuad : Parser Int
hexQuad = do
a <- hex
b <- hex
c <- hex
d <- hex
pure $ a * 4096 + b * 256 + c * 16 + d
specialChar : Parser Char
specialChar = do
c <- satisfy (const True)
case c of
'"' => pure '"'
'\\' => pure '\\'
'/' => pure '/'
'b' => pure '\b'
'f' => pure '\f'
'n' => pure '\n'
'r' => pure '\r'
't' => pure '\t'
'u' => map chr hexQuad
_ => fail "expected special char"
jsonString' : Parser (List Char)
jsonString' = (char '"' *!> pure Prelude.List.Nil) <|> do
c <- satisfy (/= '"')
if (c == '\\') then map (::) specialChar <*> jsonString'
else map (c ::) jsonString'
jsonString : Parser String
jsonString = char '"' *> map pack jsonString' <?> "JSON string"
-- inspired by Haskell's Data.Scientific module
record Scientific where
constructor MkScientific
coefficient : Integer
exponent : Integer
scientificToFloat : Scientific -> Double
scientificToFloat (MkScientific c e) = fromInteger c * exp
where exp = if e < 0 then 1 / pow 10 (fromIntegerNat (- e))
else pow 10 (fromIntegerNat e)
parseScientific : Parser Scientific
parseScientific = do sign <- maybe 1 (const (-1)) `map` opt (char '-')
digits <- some digit
hasComma <- isJust `map` opt (char '.')
decimals <- if hasComma then some digit else pure Prelude.List.Nil
hasExponent <- isJust `map` opt (char 'e')
exponent <- if hasExponent then integer else pure 0
pure $ MkScientific (sign * fromDigits (digits ++ decimals))
(exponent - cast (length decimals))
where fromDigits : List (Fin 10) -> Integer
fromDigits = foldl (\a, b => 10 * a + cast b) 0
jsonNumber : Parser Double
jsonNumber = map scientificToFloat parseScientific
jsonBool : Parser Bool
jsonBool = (char 't' >! string "rue" *> pure True)
<|> (char 'f' >! string "alse" *> pure False) <?> "JSON Bool"
jsonNull : Parser ()
jsonNull = (char 'n' >! string "ull" >! pure ()) <?> "JSON Null"
mutual
jsonArray : Parser (List JsonValue)
jsonArray = char '[' *!> (jsonValue `sepBy` (char ',')) <* char ']'
keyValuePair : Parser (String, JsonValue)
keyValuePair = do
key <- spaces *> jsonString <* spaces
char ':'
value <- jsonValue
pure (key, value)
jsonObject : Parser (SortedMap String JsonValue)
jsonObject = map fromList (char '{' >! (keyValuePair `sepBy` char ',') <* char '}')
jsonValue' : Parser JsonValue
jsonValue' = (map JsonString jsonString)
<|> (map JsonNumber jsonNumber)
<|> (map JsonBool jsonBool)
<|> (pure JsonNull <* jsonNull)
<|>| map JsonArray jsonArray
<|>| map JsonObject jsonObject
jsonValue : Parser JsonValue
jsonValue = spaces *> jsonValue' <* spaces
jsonToplevelValue : Parser JsonValue
jsonToplevelValue = (map JsonArray jsonArray) <|> (map JsonObject jsonObject)
export
parsJson : String -> Either String JsonValue
parsJson s = parse jsonValue s
public export
interface ToJson a where
toJson : a -> JsonValue
public export
interface FromJson a where
fromJson : JsonValue -> Either String a
export
interface (ToJson a, FromJson a) => BothJson a where
export
(ToJson a, FromJson a) => BothJson a where
export
FromJson String where
fromJson (JsonString s) = Right s
fromJson o = Left $ "fromJson: " ++ show o ++ " is not a String"
export
ToJson String where
toJson s = JsonString s
export
FromJson JsonValue where
fromJson = Right
export
ToJson JsonValue where
toJson = id
export
FromJson () where
fromJson JsonNull = Right ()
export
ToJson () where
toJson () = JsonNull
export
ToJson a => ToJson (List a) where
toJson x = JsonArray $ map toJson x
export
FromJson a => FromJson (List a) where
fromJson (JsonArray x) = sequence $ map fromJson x
export
ToJson a => ToJson (Vect n a) where
toJson x = JsonArray $ toList $ map toJson x
vectFromJson : FromJson a => JsonValue -> Either String (Vect n a)
vectFromJson {n} {a} (JsonArray x) =
let p1 = the (List (Either String a)) $ map fromJson x
p2 = sequence $ fromList p1
in case exactLength n <$> p2 of
Right (Just z) => Right z
export
FromJson a => FromJson (Vect n a) where
fromJson = vectFromJson
export
(ToJson a, ToJson b) => ToJson (a,b) where
toJson (x, y) = JsonArray [toJson x, toJson y]
export
(FromJson a, FromJson b) => FromJson (a, b) where
fromJson (JsonArray [x, y]) = MkPair <$> fromJson x <*> fromJson y
export
decode : FromJson a => String -> Either String a
decode x = parsJson x >>= fromJson
export
encode : ToJson a => a -> String
encode x = show $ toJson x
-}
|
program main
implicit none
integer :: name
integer :: age
print *, '==== Enter you're name ===='
read(*,*) name
print *, '==== Enter you're age ==='
read(*,*) age
print *, 'Hello there ', name
IF (age > 18) THEN
print *, 'age => ', age
print *, 'you are NOT below 18'
ELSE IF (age < 18)
print *, 'age => ', age
print *, 'you are blow 18'
END IF
end program main
|
From discprob.basic Require Import base order.
From discprob.prob Require Import prob countable finite stochastic_order.
From discprob.monad Require Import monad monad_cost quicksort monad_cost_hoare.
From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div choice fintype.
From mathcomp Require Import tuple finfun bigop prime binomial finset.
From mathcomp Require Import path.
Require Import Coq.omega.Omega Coq.Program.Wf.
(* Shocked this is not in the ssreflect library? *)
Lemma perm_eq_cat {A: eqType} (l1a l1b l2a l2b: seq A) :
perm_eq l1a l2a →
perm_eq l1b l2b →
perm_eq (l1a ++ l1b) (l2a ++ l2b).
Proof.
move /perm_eqP => Hpa.
move /perm_eqP => Hpb.
apply /perm_eqP.
intros x. rewrite ?count_cat. rewrite (Hpa x) (Hpb x). done.
Qed.
Lemma sorted_cat {A: eqType} (l1 l2: seq A) (R: rel A):
sorted R l1 → sorted R l2 →
(∀ n1 n2, n1 \in l1 → n2 \in l2 → R n1 n2) →
sorted R (l1 ++ l2).
Proof.
revert l2. induction l1 => //=.
intros l2 HP Hsorted Hle.
rewrite cat_path. apply /andP; split; auto.
induction l2 => //=. apply /andP; split; auto.
apply Hle.
- apply mem_last.
- rewrite in_cons eq_refl //.
Qed.
Lemma quicksort_correct (l: list nat): mspec (qs l) (λ l', (sorted leq l' && perm_eq l l'):Prop).
Proof.
remember (size l) as k eqn:Heq.
revert l Heq.
induction k as [k IH] using (well_founded_induction lt_wf) => l Heq.
destruct l as [| a l].
- rewrite //= => b. rewrite mem_seq1. move /eqP => -> //=.
- destruct l as [| b0 l0].
{ rewrite //= => b. rewrite mem_seq1. move /eqP => -> //=. }
rewrite qs_unfold.
remember (b0 :: l0) as l eqn:Hl0. clear l0 Hl0.
tbind (λ x, sval x \in a :: l).
{ intros (?&?) => //. }
intros (pv&Hin) _.
tbind (λ x, lower (sval x) = [ seq n <- (a :: l) | ltn n pv] ∧
middle (sval x) = [ seq n <- (a :: l) | n == pv] ∧
upper (sval x) = [ seq n <- (a :: l) | ltn pv n]).
{ remember (a :: l) as l0 eqn:Heql0.
apply mspec_mret => //=. clear. induction l0 as [|a l]; first by rewrite //=.
rewrite //=; case (ltngtP a pv) => //= ?;
destruct (IHl) as (?&?&?); repeat split; auto; f_equal; done.
}
remember (a :: l) as l0 eqn:Heql0.
intros (spl&Hin'). rewrite //=. intros (Hl&Hm&Hu).
tbind (λ x, sorted leq x && perm_eq (lower spl) x).
{ rewrite //=.
(* TODO: should probably just have an induction principle justifying this,
we already had to prove that the list was smaller to justify that the defn
was terminating *)
eapply (IH (size (lower spl))); auto.
rewrite Heq.
move /andP in Hin'.
destruct Hin' as (pf1&pf2); move /implyP in pf2.
rewrite -(perm_eq_size pf1) //= ?size_cat -?plusE //;
assert (Hlt: (lt O (size (middle spl)))) by
( apply /ltP; apply pf2 => //=; destruct p; eauto; subst; rewrite //=).
rewrite //= in Hlt. omega.
}
intros ll. move /andP => [Hllsorted Hllperm].
tbind (λ x, sorted leq x && perm_eq (upper spl) x).
{ rewrite //=.
eapply (IH (size (upper spl))); auto.
rewrite Heq.
move /andP in Hin'.
destruct Hin' as (pf1&pf2); move /implyP in pf2.
rewrite -(perm_eq_size pf1) //= ?size_cat -?plusE //;
assert (Hlt: (lt O (size (middle spl)))) by
( apply /ltP; apply pf2 => //=; destruct p; eauto; subst; rewrite //=).
rewrite //= in Hlt. omega.
}
intros lu. move /andP => [Hlusorted Hluperm].
apply mspec_mret => //=. apply /andP; split.
* apply sorted_cat; [| apply sorted_cat |]; auto.
** rewrite Hm. clear. induction l0 => //=.
case: ifP; auto.
move /eqP => ->. rewrite //=.
clear IHl0.
induction l0 => //=.
case: ifP; auto. move /eqP => -> //=. rewrite leqnn IHl0 //.
** rewrite Hm => a' b'; rewrite mem_filter.
move /andP => [Heqpv Hin1 Hin2]. move /eqP in Heqpv.
move: Hin2.
rewrite -(perm_eq_mem Hluperm) Hu mem_filter.
move /andP => [Hgtpv ?]. move /ltP in Hgtpv.
rewrite Heqpv. apply /leP. omega.
** intros a' b'. rewrite -(perm_eq_mem Hllperm) Hl mem_filter.
move /andP => [Hgtpv ?]. move /ltP in Hgtpv.
rewrite mem_cat. move /orP => [].
*** rewrite Hm; rewrite mem_filter.
move /andP => [Heqpv ?]. move /eqP in Heqpv.
rewrite Heqpv. apply /leP. omega.
*** rewrite -(perm_eq_mem Hluperm) Hu mem_filter.
move /andP => [Hltpv ?]. move /ltP in Hltpv.
apply /leP. omega.
* move /andP in Hin'. destruct Hin' as (Hperm&_).
rewrite perm_eq_sym in Hperm.
rewrite (perm_eq_trans Hperm) //.
repeat apply perm_eq_cat; auto.
Qed. |
C
C $Id: vectd.f,v 1.4 2008-07-27 00:23:03 haley Exp $
C
C Copyright (C) 2000
C University Corporation for Atmospheric Research
C All Rights Reserved
C
C The use of this Software is governed by a License Agreement.
C
SUBROUTINE VECTD (X,Y)
C USER ENTRY POINT.
CALL FL2INT (X,Y,IIX,IIY)
CALL FDVDLD (2,IIX,IIY)
RETURN
END
|
! @(#) test some object-related procedures
program sobj
!(LICENSE:PD)
use M_draw
character(len=20) :: device
write(*,*)"Fortran: Enter output device: "
read(*,*)device
call prefsize(300, 300)
call prefposition(100, 100)
call vinit(device) ! set up device
call color(7) ! set current color
call clear() ! clear screen to current color
call makeobj(3)
call polyfill(.true.)
call color(2)
call circle(0.0,0.0,4.0)
call closeobj()
! juaspct(-5.0,-5.0,5.0,5.0)
call ortho2(-5.1,5.3,-5.2,5.4)
call callobj(3)
call move2(-5.0,-5.0)
call draw2(5.0,5.0)
call move2(-5.0,5.0)
call draw2(5.0,-5.0)
call saveobj(3,"fthree.obj")
if(isobj(3))then
write(*,*)' 3 is an object (CORRECT)'
else
write(*,*)' 3 is not an object (ERROR)'
endif
if(isobj(4))then
write(*,*)' 4 is an object (ERROR)'
else
write(*,*)' 4 is not an object (CORRECT)'
endif
idum=getkey()! wait for some input
call vexit()! set the screen back to its original state
end program sobj
|
# Motor selection
*Written by Marc Budinger (INSA Toulouse) and Scott Delbecq (ISAE-SUPAERO), Toulouse, France.*
**Sympy** package permits us to work with symbolic calculation.
```python
from math import pi
from sympy import Symbol
from sympy import *
```
## Design graph
The following diagram represents the design graph of the motor’s selection. The mean speed/thrust (Ωmoy & Tmoy), the max speed/thrust (Ωmax & Tmax) and the battery voltage are assumed to be known here.
> **Questions:**
* Give the 2 main sizing problems you are able to detect here.
* Propose one or multiple solutions (which can request equation manipulation, addition of design variables, addition of constraints)
* Orientate the arrows and write equations order, inputs/outputs at each step of this part of sizing procedure, additional constraints
### Sizing code and optimization
> Exercice: propose a sizing code for the selection of a motor.
```python
# Specifications
# Reference parameters for scaling laws
# Motor reference
# Ref : AXI 5325/16 GOLD LINE
T_nom_mot_ref = 2.32 # [N.m] rated torque
T_max_mot_ref = 85./70.*T_nom_mot_ref # [N.m] max torque
R_mot_ref = 0.03 # [Ohm] resistance
M_mot_ref = 0.575 # [kg] mass
K_mot_ref = 0.03 # [N.m/A] torque coefficient
T_mot_fr_ref = 0.03 # [N.m] friction torque (zero load, nominal speed)
# Assumption
T_pro_to=1.0#[N.m] Propeller Torque during takeoff
Omega_pro_to=1.0#[rad/s] Propeller speed during takeoff
T_pro_hov=1.0#[N.m] Propeller Torque during hover
Omega_pro_hov=1.0#[rad/s] Propeller speed during hover
U_bat_est= 4.0#[V] Battery voltage value (estimation)
```
Define the design variables as a symbol under `variableExample= Symbol('variableExample')`
```python
#Design variables
k_mot=Symbol('k_mot')#[-] over sizing coefficient on the motor torque (1,400)
k_speed_mot=Symbol('k_speed_mot')#[-] over sizing coefficient on the motor speed (1,10)
```
```python
#Equations:
#-----
T_nom_mot = k_mot * T_pro_hov # [N.m] Motor nominal torque per propeller
M_mot = M_mot_ref * (T_nom_mot/T_nom_mot_ref)**(3./3.5) # [kg] Motor mass
# Selection with take-off speed
K_mot = U_bat_est / (k_speed_mot*Omega_pro_to) # [N.m/A] or [V/(rad/s)] Kt motor
R_mot = R_mot_ref * (T_nom_mot/T_nom_mot_ref)**(-5./3.5)*(K_mot/K_mot_ref)**2. # [Ohm] motor resistance
T_mot_fr = T_mot_fr_ref * (T_nom_mot/T_nom_mot_ref)**(3./3.5) # [N.m] Friction torque
T_max_mot = T_max_mot_ref * (T_nom_mot/T_nom_mot_ref)
# Hover current and voltage
I_mot_hov = (T_pro_hov+T_mot_fr) / K_mot # [I] Current of the motor per propeller
U_mot_hov = R_mot*I_mot_hov + Omega_pro_hov*K_mot # [V] Voltage of the motor per propeller
P_el_mot_hov = U_mot_hov*I_mot_hov # [W] Hover : electrical power
# Takeoff current and voltage
I_mot_to = (T_pro_to+T_mot_fr) / K_mot # [I] Current of the motor per propeller
U_mot_to = R_mot*I_mot_to + Omega_pro_to*K_mot # [V] Voltage of the motor per propeller
P_el_mot_to = U_mot_to*I_mot_to # [W] Takeoff : electrical power
```
|
import Pkg; Pkg.activate("../..")
using StatsPlots
import Random
Random.seed!(0)
X = cumsum(randn(10, 4) .+ 1, dims=1) * .1 .+ [1 2 3 4]
plot(X, legendfontsize=10, m=:square, ms=1, msc=:white, legend=:outerright,
lw=5, palette=:tab10, msw=0)
|
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
⊢ StrongRankCondition R
[PROOFSTEP]
suffices ∀ n, ∀ f : (Fin (n + 1) → R) →ₗ[R] Fin n → R, ¬Injective f by rwa [strongRankCondition_iff_succ R]
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
this : ∀ (n : ℕ) (f : (Fin (n + 1) → R) →ₗ[R] Fin n → R), ¬Injective ↑f
⊢ StrongRankCondition R
[PROOFSTEP]
rwa [strongRankCondition_iff_succ R]
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
⊢ ∀ (n : ℕ) (f : (Fin (n + 1) → R) →ₗ[R] Fin n → R), ¬Injective ↑f
[PROOFSTEP]
intro n f
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
⊢ ¬Injective ↑f
[PROOFSTEP]
by_contra hf
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
⊢ False
[PROOFSTEP]
let g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := (ExtendByZero.linearMap R castSucc).comp f
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
⊢ False
[PROOFSTEP]
have hg : Injective g := (extend_injective Fin.strictMono_castSucc.injective _).comp hf
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
⊢ False
[PROOFSTEP]
have hnex : ¬∃ i : Fin n, castSucc i = last n := fun ⟨i, hi⟩ => ne_of_lt (castSucc_lt_last i) hi
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
⊢ False
[PROOFSTEP]
let a₀ := (minpoly R g).coeff 0
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
⊢ False
[PROOFSTEP]
have : a₀ ≠ 0 := minpoly_coeff_zero_of_injective hg
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
this : a₀ ≠ 0
⊢ False
[PROOFSTEP]
have : a₀ = 0 := by
-- Evaluate `(minpoly R g) g` at the vector `(0,...,0,1)`
have heval := LinearMap.congr_fun (minpoly.aeval R g) (Pi.single (Fin.last n) 1)
obtain ⟨P, hP⟩ := X_dvd_iff.2 (erase_same (minpoly R g) 0)
rw [← monomial_add_erase (minpoly R g) 0, hP] at heval
replace heval :=
congr_fun heval
(Fin.last n)
-- Porting note: ...it's just that this line gives a timeout without slightly raising heartbeats
simpa [hnex] using heval
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
this : a₀ ≠ 0
⊢ a₀ = 0
[PROOFSTEP]
have heval := LinearMap.congr_fun (minpoly.aeval R g) (Pi.single (Fin.last n) 1)
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
this : a₀ ≠ 0
heval : ↑(↑(aeval g) (minpoly R g)) (Pi.single (last n) 1) = ↑0 (Pi.single (last n) 1)
⊢ a₀ = 0
[PROOFSTEP]
obtain ⟨P, hP⟩ := X_dvd_iff.2 (erase_same (minpoly R g) 0)
[GOAL]
case intro
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
this : a₀ ≠ 0
heval : ↑(↑(aeval g) (minpoly R g)) (Pi.single (last n) 1) = ↑0 (Pi.single (last n) 1)
P : R[X]
hP : erase 0 (minpoly R g) = X * P
⊢ a₀ = 0
[PROOFSTEP]
rw [← monomial_add_erase (minpoly R g) 0, hP] at heval
[GOAL]
case intro
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
this : a₀ ≠ 0
P : R[X]
heval : ↑(↑(aeval g) (↑(monomial 0) (coeff (minpoly R g) 0) + X * P)) (Pi.single (last n) 1) = ↑0 (Pi.single (last n) 1)
hP : erase 0 (minpoly R g) = X * P
⊢ a₀ = 0
[PROOFSTEP]
replace heval :=
congr_fun heval
(Fin.last n)
-- Porting note: ...it's just that this line gives a timeout without slightly raising heartbeats
[GOAL]
case intro
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
this : a₀ ≠ 0
P : R[X]
hP : erase 0 (minpoly R g) = X * P
heval :
↑(↑(aeval g) (↑(monomial 0) (coeff (minpoly R g) 0) + X * P)) (Pi.single (last n) 1) (last n) =
↑0 (Pi.single (last n) 1) (last n)
⊢ a₀ = 0
[PROOFSTEP]
simpa [hnex] using heval
[GOAL]
R : Type u_1
inst✝¹ : CommRing R
inst✝ : Nontrivial R
n : ℕ
f : (Fin (n + 1) → R) →ₗ[R] Fin n → R
hf : Injective ↑f
g : (Fin (n + 1) → R) →ₗ[R] Fin (n + 1) → R := LinearMap.comp (ExtendByZero.linearMap R castSucc) f
hg : Injective ↑g
hnex : ¬∃ i, castSucc i = last n
a₀ : R := coeff (minpoly R g) 0
this✝ : a₀ ≠ 0
this : a₀ = 0
⊢ False
[PROOFSTEP]
contradiction
|
/-
Copyright (c) 2022 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
! This file was ported from Lean 3 source module topology.bornology.constructions
! leanprover-community/mathlib commit e3d9ab8faa9dea8f78155c6c27d62a621f4c152d
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Topology.Bornology.Basic
/-!
# Bornology structure on products and subtypes
In this file we define `Bornology` and `BoundedSpace` instances on `α × β`, `Π i, π i`, and
`{x // p x}`. We also prove basic lemmas about `Bornology.cobounded` and `Bornology.IsBounded`
on these types.
-/
open Set Filter Bornology Function
open Filter
variable {α β ι : Type _} {π : ι → Type _} [Fintype ι] [Bornology α] [Bornology β]
[∀ i, Bornology (π i)]
instance : Bornology (α × β)
where
cobounded' := (cobounded α).coprod (cobounded β)
le_cofinite' :=
@coprod_cofinite α β ▸ coprod_mono ‹Bornology α›.le_cofinite ‹Bornology β›.le_cofinite
instance : Bornology (∀ i, π i)
where
cobounded' := Filter.coprodᵢ fun i => cobounded (π i)
le_cofinite' := @coprodᵢ_cofinite ι π _ ▸ Filter.coprodᵢ_mono fun _ => Bornology.le_cofinite _
/-- Inverse image of a bornology. -/
@[reducible]
def Bornology.induced {α β : Type _} [Bornology β] (f : α → β) : Bornology α
where
cobounded' := comap f (cobounded β)
le_cofinite' := (comap_mono (Bornology.le_cofinite β)).trans (comap_cofinite_le _)
#align bornology.induced Bornology.induced
instance {p : α → Prop} : Bornology (Subtype p) :=
Bornology.induced (Subtype.val : Subtype p → α)
namespace Bornology
/-!
### Bounded sets in `α × β`
-/
theorem cobounded_prod : cobounded (α × β) = (cobounded α).coprod (cobounded β) :=
rfl
#align bornology.cobounded_prod Bornology.cobounded_prod
theorem isBounded_image_fst_and_snd {s : Set (α × β)} :
IsBounded (Prod.fst '' s) ∧ IsBounded (Prod.snd '' s) ↔ IsBounded s :=
compl_mem_coprod.symm
#align bornology.is_bounded_image_fst_and_snd Bornology.isBounded_image_fst_and_snd
variable {s : Set α} {t : Set β} {S : ∀ i, Set (π i)}
theorem IsBounded.fst_of_prod (h : IsBounded (s ×ˢ t)) (ht : t.Nonempty) : IsBounded s :=
fst_image_prod s ht ▸ (isBounded_image_fst_and_snd.2 h).1
#align bornology.is_bounded.fst_of_prod Bornology.IsBounded.fst_of_prod
theorem IsBounded.prod (hs : IsBounded s) (ht : IsBounded t) : IsBounded (s ×ˢ t) :=
isBounded_image_fst_and_snd.1
⟨hs.subset <| fst_image_prod_subset _ _, ht.subset <| snd_image_prod_subset _ _⟩
#align bornology.is_bounded.prod Bornology.IsBounded.prod
theorem isBounded_prod_of_nonempty (hne : Set.Nonempty (s ×ˢ t)) :
IsBounded (s ×ˢ t) ↔ IsBounded s ∧ IsBounded t :=
⟨fun h => ⟨h.fst_of_prod hne.snd, h.snd_of_prod hne.fst⟩, fun h => h.1.prod h.2⟩
#align bornology.is_bounded_prod_of_nonempty Bornology.isBounded_prod_of_nonempty
theorem isBounded_prod : IsBounded (s ×ˢ t) ↔ s = ∅ ∨ t = ∅ ∨ IsBounded s ∧ IsBounded t := by
rcases s.eq_empty_or_nonempty with (rfl | hs); · simp
rcases t.eq_empty_or_nonempty with (rfl | ht); · simp
simp only [hs.ne_empty, ht.ne_empty, isBounded_prod_of_nonempty (hs.prod ht), false_or_iff]
#align bornology.is_bounded_prod Bornology.isBounded_prod
theorem isBounded_prod_self : IsBounded (s ×ˢ s) ↔ IsBounded s := by
rcases s.eq_empty_or_nonempty with (rfl | hs); · simp
exact (isBounded_prod_of_nonempty (hs.prod hs)).trans (and_self_iff _)
#align bornology.is_bounded_prod_self Bornology.isBounded_prod_self
/-!
### Bounded sets in `Π i, π i`
-/
theorem cobounded_pi : cobounded (∀ i, π i) = Filter.coprodᵢ fun i => cobounded (π i) :=
rfl
#align bornology.cobounded_pi Bornology.cobounded_pi
theorem forall_isBounded_image_eval_iff {s : Set (∀ i, π i)} :
(∀ i, IsBounded (eval i '' s)) ↔ IsBounded s :=
compl_mem_coprodᵢ.symm
#align bornology.forall_is_bounded_image_eval_iff Bornology.forall_isBounded_image_eval_iff
theorem IsBounded.pi (h : ∀ i, IsBounded (S i)) : IsBounded (pi univ S) :=
forall_isBounded_image_eval_iff.1 fun i => (h i).subset eval_image_univ_pi_subset
#align bornology.is_bounded.pi Bornology.IsBounded.pi
theorem isBounded_pi_of_nonempty (hne : (pi univ S).Nonempty) :
IsBounded (pi univ S) ↔ ∀ i, IsBounded (S i) :=
⟨fun H i => @eval_image_univ_pi _ _ _ i hne ▸ forall_isBounded_image_eval_iff.2 H i, IsBounded.pi⟩
#align bornology.is_bounded_pi_of_nonempty Bornology.isBounded_pi_of_nonempty
theorem isBounded_pi : IsBounded (pi univ S) ↔ (∃ i, S i = ∅) ∨ ∀ i, IsBounded (S i) := by
by_cases hne : ∃ i, S i = ∅
· simp [hne, univ_pi_eq_empty_iff.2 hne]
· simp only [hne, false_or_iff]
simp only [not_exists, ← Ne.def, ← nonempty_iff_ne_empty, ← univ_pi_nonempty_iff] at hne
exact isBounded_pi_of_nonempty hne
#align bornology.is_bounded_pi Bornology.isBounded_pi
/-!
### Bounded sets in `{x // p x}`
-/
theorem isBounded_induced {α β : Type _} [Bornology β] {f : α → β} {s : Set α} :
@IsBounded α (Bornology.induced f) s ↔ IsBounded (f '' s) :=
compl_mem_comap
#align bornology.is_bounded_induced Bornology.isBounded_induced
theorem isBounded_image_subtype_val {p : α → Prop} {s : Set { x // p x }} :
IsBounded (Subtype.val '' s) ↔ IsBounded s :=
isBounded_induced.symm
#align bornology.is_bounded_image_subtype_coe Bornology.isBounded_image_subtype_val
end Bornology
/-!
### Bounded spaces
-/
open Bornology
instance [BoundedSpace α] [BoundedSpace β] : BoundedSpace (α × β) := by
simp [← cobounded_eq_bot_iff, cobounded_prod]
instance [∀ i, BoundedSpace (π i)] : BoundedSpace (∀ i, π i) := by
simp [← cobounded_eq_bot_iff, cobounded_pi]
theorem boundedSpace_induced_iff {α β : Type _} [Bornology β] {f : α → β} :
@BoundedSpace α (Bornology.induced f) ↔ IsBounded (range f) := by
rw [← @isBounded_univ _ (Bornology.induced f), isBounded_induced, image_univ]
-- porting note: had to explicitly provided the bornology to `isBounded_univ`.
#align bounded_space_induced_iff boundedSpace_induced_iff
theorem boundedSpace_subtype_iff {p : α → Prop} :
BoundedSpace (Subtype p) ↔ IsBounded { x | p x } := by
rw [boundedSpace_induced_iff, Subtype.range_coe_subtype]
#align bounded_space_subtype_iff boundedSpace_subtype_iff
theorem boundedSpace_val_set_iff {s : Set α} : BoundedSpace s ↔ IsBounded s :=
boundedSpace_subtype_iff
#align bounded_space_coe_set_iff boundedSpace_val_set_iff
alias boundedSpace_subtype_iff ↔ _ Bornology.IsBounded.boundedSpace_subtype
#align bornology.is_bounded.bounded_space_subtype Bornology.IsBounded.boundedSpace_subtype
alias boundedSpace_val_set_iff ↔ _ Bornology.IsBounded.boundedSpace_val
#align bornology.is_bounded.bounded_space_coe Bornology.IsBounded.boundedSpace_val
instance [BoundedSpace α] {p : α → Prop} : BoundedSpace (Subtype p) :=
(IsBounded.all { x | p x }).boundedSpace_subtype
/-!
### `Additive`, `Multiplicative`
The bornology on those type synonyms is inherited without change.
-/
instance : Bornology (Additive α) :=
‹Bornology α›
instance : Bornology (Multiplicative α) :=
‹Bornology α›
instance [BoundedSpace α] : BoundedSpace (Additive α) :=
‹BoundedSpace α›
instance [BoundedSpace α] : BoundedSpace (Multiplicative α) :=
‹BoundedSpace α›
/-!
### Order dual
The bornology on this type synonym is inherited without change.
-/
instance : Bornology αᵒᵈ :=
‹Bornology α›
instance [BoundedSpace α] : BoundedSpace αᵒᵈ :=
‹BoundedSpace α›
|
State Before: α : Type u_1
inst✝ : DivisionRing α
n d : ℕ
inv✝ : Invertible ↑d
⊢ ↑(Int.negOfNat n) * ⅟↑d = -(↑n / ↑d) State After: no goals Tactic: simp [div_eq_mul_inv] |
A_bounds = [-eye(3);
1,1,1];
b_bounds = [0;0;0;1];
lb = [0;0;0];
ub = [1;1;1];
[C, d] = iris.inner_ellipsoid.mosek_nofusion(A_bounds, b_bounds);
assert(det(C) > 0.01);
iris.drawing.draw_3d(A_bounds, b_bounds, C, d, [], lb, ub);
|
program demo_repeat
implicit none
write(*,*) repeat("x", 5) ! "xxxxx"
end program demo_repeat
|
/-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
! This file was ported from Lean 3 source module category_theory.closed.functor
! leanprover-community/mathlib commit cea27692b3fdeb328a2ddba6aabf181754543184
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.CategoryTheory.Closed.Cartesian
import Mathbin.CategoryTheory.Limits.Preserves.Shapes.BinaryProducts
import Mathbin.CategoryTheory.Adjunction.FullyFaithful
/-!
# Cartesian closed functors
Define the exponential comparison morphisms for a functor which preserves binary products, and use
them to define a cartesian closed functor: one which (naturally) preserves exponentials.
Define the Frobenius morphism, and show it is an isomorphism iff the exponential comparison is an
isomorphism.
## TODO
Some of the results here are true more generally for closed objects and for closed monoidal
categories, and these could be generalised.
## References
https://ncatlab.org/nlab/show/cartesian+closed+functor
https://ncatlab.org/nlab/show/Frobenius+reciprocity
## Tags
Frobenius reciprocity, cartesian closed functor
-/
namespace CategoryTheory
open Category Limits CartesianClosed
universe v u u'
variable {C : Type u} [Category.{v} C]
variable {D : Type u'} [Category.{v} D]
variable [HasFiniteProducts C] [HasFiniteProducts D]
variable (F : C ⥤ D) {L : D ⥤ C}
noncomputable section
/-- The Frobenius morphism for an adjunction `L ⊣ F` at `A` is given by the morphism
L(FA ⨯ B) ⟶ LFA ⨯ LB ⟶ A ⨯ LB
natural in `B`, where the first morphism is the product comparison and the latter uses the counit
of the adjunction.
We will show that if `C` and `D` are cartesian closed, then this morphism is an isomorphism for all
`A` iff `F` is a cartesian closed functor, i.e. it preserves exponentials.
-/
def frobeniusMorphism (h : L ⊣ F) (A : C) :
prod.functor.obj (F.obj A) ⋙ L ⟶ L ⋙ prod.functor.obj A :=
prodComparisonNatTrans L (F.obj A) ≫ whiskerLeft _ (prod.functor.map (h.counit.app _))
#align category_theory.frobenius_morphism CategoryTheory.frobeniusMorphism
/-- If `F` is full and faithful and has a left adjoint `L` which preserves binary products, then the
Frobenius morphism is an isomorphism.
-/
instance frobeniusMorphism_iso_of_preserves_binary_products (h : L ⊣ F) (A : C)
[PreservesLimitsOfShape (Discrete WalkingPair) L] [Full F] [Faithful F] :
IsIso (frobeniusMorphism F h A) :=
by
apply nat_iso.is_iso_of_is_iso_app _
intro B
dsimp [frobenius_morphism]
infer_instance
#align category_theory.frobenius_morphism_iso_of_preserves_binary_products CategoryTheory.frobeniusMorphism_iso_of_preserves_binary_products
variable [CartesianClosed C] [CartesianClosed D]
variable [PreservesLimitsOfShape (Discrete WalkingPair) F]
/-- The exponential comparison map.
`F` is a cartesian closed functor if this is an iso for all `A`.
-/
def expComparison (A : C) : exp A ⋙ F ⟶ F ⋙ exp (F.obj A) :=
transferNatTrans (exp.adjunction A) (exp.adjunction (F.obj A)) (prodComparisonNatIso F A).inv
#align category_theory.exp_comparison CategoryTheory.expComparison
theorem expComparison_ev (A B : C) :
Limits.prod.map (𝟙 (F.obj A)) ((expComparison F A).app B) ≫ (exp.ev (F.obj A)).app (F.obj B) =
inv (prodComparison F _ _) ≫ F.map ((exp.ev _).app _) :=
by
convert transfer_nat_trans_counit _ _ (prod_comparison_nat_iso F A).inv B
ext
simp
#align category_theory.exp_comparison_ev CategoryTheory.expComparison_ev
theorem coev_expComparison (A B : C) :
F.map ((exp.coev A).app B) ≫ (expComparison F A).app (A ⨯ B) =
(exp.coev _).app (F.obj B) ≫ (exp (F.obj A)).map (inv (prodComparison F A B)) :=
by
convert unit_transfer_nat_trans _ _ (prod_comparison_nat_iso F A).inv B
ext
dsimp
simp
#align category_theory.coev_exp_comparison CategoryTheory.coev_expComparison
theorem uncurry_expComparison (A B : C) :
CartesianClosed.uncurry ((expComparison F A).app B) =
inv (prodComparison F _ _) ≫ F.map ((exp.ev _).app _) :=
by rw [uncurry_eq, exp_comparison_ev]
#align category_theory.uncurry_exp_comparison CategoryTheory.uncurry_expComparison
/-- The exponential comparison map is natural in `A`. -/
theorem expComparison_whiskerLeft {A A' : C} (f : A' ⟶ A) :
expComparison F A ≫ whiskerLeft _ (pre (F.map f)) =
whiskerRight (pre f) _ ≫ expComparison F A' :=
by
ext B
dsimp
apply uncurry_injective
rw [uncurry_natural_left, uncurry_natural_left, uncurry_exp_comparison, uncurry_pre,
prod.map_swap_assoc, ← F.map_id, exp_comparison_ev, ← F.map_id, ←
prod_comparison_inv_natural_assoc, ← prod_comparison_inv_natural_assoc, ← F.map_comp, ←
F.map_comp, prod_map_pre_app_comp_ev]
#align category_theory.exp_comparison_whisker_left CategoryTheory.expComparison_whiskerLeft
/-- The functor `F` is cartesian closed (ie preserves exponentials) if each natural transformation
`exp_comparison F A` is an isomorphism
-/
class CartesianClosedFunctor where
comparison_iso : ∀ A, IsIso (expComparison F A)
#align category_theory.cartesian_closed_functor CategoryTheory.CartesianClosedFunctor
attribute [instance] cartesian_closed_functor.comparison_iso
theorem frobeniusMorphism_mate (h : L ⊣ F) (A : C) :
transferNatTransSelf (h.comp (exp.adjunction A)) ((exp.adjunction (F.obj A)).comp h)
(frobeniusMorphism F h A) =
expComparison F A :=
by
rw [← Equiv.eq_symm_apply]
ext B : 2
dsimp [frobenius_morphism, transfer_nat_trans_self, transfer_nat_trans, adjunction.comp]
simp only [id_comp, comp_id]
rw [← L.map_comp_assoc, prod.map_id_comp, assoc, exp_comparison_ev, prod.map_id_comp, assoc, ←
F.map_id, ← prod_comparison_inv_natural_assoc, ← F.map_comp, exp.ev_coev,
F.map_id (A ⨯ L.obj B), comp_id]
apply prod.hom_ext
· rw [assoc, assoc, ← h.counit_naturality, ← L.map_comp_assoc, assoc, inv_prod_comparison_map_fst]
simp
· rw [assoc, assoc, ← h.counit_naturality, ← L.map_comp_assoc, assoc, inv_prod_comparison_map_snd]
simp
#align category_theory.frobenius_morphism_mate CategoryTheory.frobeniusMorphism_mate
/--
If the exponential comparison transformation (at `A`) is an isomorphism, then the Frobenius morphism
at `A` is an isomorphism.
-/
theorem frobeniusMorphism_iso_of_expComparison_iso (h : L ⊣ F) (A : C)
[i : IsIso (expComparison F A)] : IsIso (frobeniusMorphism F h A) :=
by
rw [← frobenius_morphism_mate F h] at i
exact @transfer_nat_trans_self_of_iso _ _ _ _ _ i
#align category_theory.frobenius_morphism_iso_of_exp_comparison_iso CategoryTheory.frobeniusMorphism_iso_of_expComparison_iso
/--
If the Frobenius morphism at `A` is an isomorphism, then the exponential comparison transformation
(at `A`) is an isomorphism.
-/
theorem expComparison_iso_of_frobeniusMorphism_iso (h : L ⊣ F) (A : C)
[i : IsIso (frobeniusMorphism F h A)] : IsIso (expComparison F A) :=
by
rw [← frobenius_morphism_mate F h]
infer_instance
#align category_theory.exp_comparison_iso_of_frobenius_morphism_iso CategoryTheory.expComparison_iso_of_frobeniusMorphism_iso
/-- If `F` is full and faithful, and has a left adjoint which preserves binary products, then it is
cartesian closed.
TODO: Show the converse, that if `F` is cartesian closed and its left adjoint preserves binary
products, then it is full and faithful.
-/
def cartesianClosedFunctorOfLeftAdjointPreservesBinaryProducts (h : L ⊣ F) [Full F] [Faithful F]
[PreservesLimitsOfShape (Discrete WalkingPair) L] : CartesianClosedFunctor F
where comparison_iso A := expComparison_iso_of_frobeniusMorphism_iso F h _
#align category_theory.cartesian_closed_functor_of_left_adjoint_preserves_binary_products CategoryTheory.cartesianClosedFunctorOfLeftAdjointPreservesBinaryProducts
end CategoryTheory
|
Require Import Coq.Strings.Ascii
Coq.Bool.Bool
Coq.Lists.List
Coq.Structures.OrderedType.
Require Import
Fiat.BinEncoders.Env.BinLib.Core
Fiat.BinEncoders.Env.Common.Specs
Fiat.BinEncoders.Env.Common.Compose
Fiat.BinEncoders.Env.Common.ComposeOpt
Fiat.BinEncoders.Env.Automation.Solver
Fiat.BinEncoders.Env.Lib2.WordOpt
Fiat.BinEncoders.Env.Lib2.NatOpt
Fiat.BinEncoders.Env.Lib2.StringOpt
Fiat.BinEncoders.Env.Lib2.EnumOpt
Fiat.BinEncoders.Env.Lib2.FixListOpt
Fiat.BinEncoders.Env.Lib2.SumTypeOpt.
Require Import
Fiat.Common.SumType
Fiat.Examples.Tutorial.Tutorial
Fiat.Examples.DnsServer.DecomposeEnumField
Fiat.QueryStructure.Automation.AutoDB
Fiat.QueryStructure.Implementation.DataStructures.BagADT.BagADT
Fiat.QueryStructure.Automation.IndexSelection
Fiat.QueryStructure.Specification.SearchTerms.ListPrefix
Fiat.QueryStructure.Automation.SearchTerms.FindPrefixSearchTerms
Fiat.Examples.HACMSDemo.DuplicateFree
Fiat.QueryStructure.Automation.MasterPlan.
Require Import
Bedrock.Word
Bedrock.Memory.
Lemma exists_CompletelyUnConstrFreshIdx:
forall (qs_schema : RawQueryStructureSchema)
(BagIndexKeys : ilist3 (qschemaSchemas qs_schema))
(r_o : UnConstrQueryStructure qs_schema)
(r_n : IndexedQueryStructure qs_schema BagIndexKeys),
DelegateToBag_AbsR r_o r_n ->
exists bnd : nat,
forall idx : Fin.t (numRawQSschemaSchemas qs_schema),
UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd.
Proof.
intros.
generalize (exists_UnConstrFreshIdx H); clear H.
remember (GetUnConstrRelation r_o); clear.
destruct qs_schema; simpl in *.
clear qschemaConstraints.
induction numRawQSschemaSchemas; simpl in *; intros.
- exists 0; intros; inversion idx.
- revert i IHnumRawQSschemaSchemas H.
pattern numRawQSschemaSchemas, qschemaSchemas;
apply Vector.caseS; simpl; intros.
destruct (IHnumRawQSschemaSchemas
t
(fun idx => i (Fin.FS idx))
(fun idx => H (Fin.FS idx))
).
destruct (H Fin.F1).
exists (max x x0).
unfold UnConstrFreshIdx in *; simpl in *; intros.
pose proof (Max.le_max_l x x0);
pose proof (Max.le_max_r x x0).
generalize dependent idx; intro; generalize t i x x0 H0 H1 H3 H4;
clear; pattern n, idx; apply Fin.caseS; simpl; intros.
apply H1 in H2; omega.
apply H0 in H2; omega.
Qed.
Lemma refine_Pick_CompletelyUnConstrFreshIdx
: forall (qs_schema : RawQueryStructureSchema)
(BagIndexKeys : ilist3 (qschemaSchemas qs_schema))
(r_o : UnConstrQueryStructure qs_schema)
(r_n : IndexedQueryStructure qs_schema BagIndexKeys),
DelegateToBag_AbsR r_o r_n ->
forall (bnd : nat),
(forall (idx : Fin.t (numRawQSschemaSchemas qs_schema)),
UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd) ->
refine {bnd0 : nat | forall idx, UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd0} (ret bnd).
Proof.
intros; refine pick val _; eauto.
reflexivity.
Qed.
Instance Query_eq_word32 : Query_eq (word 32) :=
{| A_eq_dec := @weq 32 |}.
Global Instance GetAttributeRawTermCounter' {A : Type} {qsSchema}
{Ridx : Fin.t _}
{tup : @RawTuple (Vector.nth _ Ridx)}
{BAidx : _ }
a
: (TermAttributeCounter qsSchema (@GetAttributeRaw {| NumAttr := S _;
AttrList := Vector.cons _ A _ _ |} {|prim_fst := a; prim_snd := tup |} (Fin.FS BAidx)) Ridx BAidx) | 0 := Build_TermAttributeCounter qsSchema _ Ridx BAidx.
Ltac GetAttributeRawTermCounterTac t ::=
lazymatch goal with
_ =>
match goal with
|- TermAttributeCounter
?qs_schema
(GetAttributeRaw {| prim_fst := ?a;
prim_snd := ?tup |} (Fin.FS ?BAidx))
_ _ =>
match type of tup with
| @RawTuple (@GetNRelSchemaHeading _ _ ?Ridx) =>
apply (@GetAttributeRawTermCounter' _ qs_schema Ridx tup _ a)
end
end
end.
Lemma refineEquiv_Query_Where_And
{ResultT}
: forall P P' bod,
(P \/ ~ P)
-> refineEquiv (@Query_Where ResultT (P /\ P') bod)
(Query_Where P (Query_Where P' bod)).
Proof.
split; unfold refine, Query_Where; intros;
computes_to_inv; computes_to_econstructor;
intuition.
- computes_to_inv; intuition.
- computes_to_inv; intuition.
- computes_to_econstructor; intuition.
Qed.
Corollary refineEquiv_For_Query_Where_And
{ResultT}
{qs_schema}
: forall (r : UnConstrQueryStructure qs_schema) idx P P' bod,
(forall tup, P tup \/ ~ P tup)
-> refine (For (UnConstrQuery_In
r idx
(fun tup => @Query_Where ResultT (P tup /\ P' tup) (bod tup))))
(For (UnConstrQuery_In
r idx
(fun tup => Where (P tup) (Where (P' tup) (bod tup))))).
Proof.
intros; apply refine_refine_For_Proper.
apply refine_UnConstrQuery_In_Proper.
intro; apply refineEquiv_Query_Where_And; eauto.
Qed.
Lemma refine_If_IfOpt {A B}
: forall (a_opt : option A) (t e : Comp B),
refine (If_Then_Else (If_Opt_Then_Else a_opt (fun _ => false) true)
t e)
(If_Opt_Then_Else a_opt (fun _ => e) t).
Proof.
destruct a_opt; simpl; intros; reflexivity.
Qed.
Global Arguments icons2 _ _ _ _ _ _ _ / .
Global Arguments GetAttributeRaw {heading} !tup !attr .
Global Arguments ilist2_tl _ _ _ _ !il / .
Global Arguments ilist2_hd _ _ _ _ !il / .
Global Opaque If_Opt_Then_Else.
Ltac implement_DecomposeRawQueryStructure :=
first [ simplify with monad laws; simpl
| rewrite refine_If_IfOpt
| match goal with
|- refine (b <- If_Opt_Then_Else _ _ _; _) _ =>
etransitivity;
[ apply refine_If_Opt_Then_Else_Bind
| simpl; eapply refine_If_Opt_Then_Else_trans;
intros; set_refine_evar ]
end
| match goal with
H0 : DecomposeRawQueryStructureSchema_AbsR' _ _ _ _ ?r_o ?r_n |- refine _ ?H => unfold H;
apply (refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv H0 Fin.F1)
end
| match goal with
H0 : DecomposeRawQueryStructureSchema_AbsR' (qs_schema := ?qs_schema) _ _ _ _ ?r_o ?r_n |- refine (Query_For _ ) _ =>
rewrite (refineEquiv_For_Query_Where_And r_o Fin.F1); eauto
end
|
match goal with
H0 : DecomposeRawQueryStructureSchema_AbsR' (qs_schema := ?qs_schema) _ _ _ _ ?r_o ?r_n |- refine (Query_For _ ) _ =>
rewrite (@refine_QueryIn_Where _ qs_schema Fin.F1 _ _ _ _ _ H0 _ _ _ );
unfold Tuple_DecomposeRawQueryStructure_inj; simpl
end
| match goal with
H0 : DecomposeRawQueryStructureSchema_AbsR' _ _ _ _ ?r_o ?r_n
|- refine { r_n | DecomposeRawQueryStructureSchema_AbsR' _ _ _ _ _ r_n} _ =>
first [refine pick val _; [ | eassumption ]
| refine pick val _;
[ | apply (DecomposeRawQueryStructureSchema_Insert_AbsR_eq H0) ] ]
end
].
Ltac implement_DecomposeRawQueryStructure' H :=
first [
simplify with monad laws; simpl
| rewrite H
| apply refine_pick_eq'
| etransitivity;
[ apply refine_If_Opt_Then_Else_Bind
| simpl; eapply refine_If_Opt_Then_Else_trans;
intros; set_refine_evar ] ].
Lemma GetAttributeRaw_FS
: forall {A} {heading} (a : A) (tup : @RawTuple heading) n,
@GetAttributeRaw {| AttrList := Vector.cons _ A _ (AttrList heading) |}
{| prim_fst := a; prim_snd := tup |} (Fin.FS n)
= GetAttributeRaw tup n.
Proof.
unfold GetAttributeRaw; simpl; reflexivity.
Qed.
Lemma GetAttributeRaw_F1
: forall {A} {heading} (a : A) (tup : @RawTuple heading),
@GetAttributeRaw {| AttrList := Vector.cons _ A _ (AttrList heading) |}
{| prim_fst := a; prim_snd := tup |} Fin.F1
= a.
Proof.
unfold GetAttributeRaw; simpl; reflexivity.
Qed.
Module word_as_OT <: OrderedType.
Definition t := word 32.
Definition eq (c1 c2 : t) := c1 = c2.
Definition lt (c1 c2 : t) := wlt c1 c2.
Definition eq_dec : forall l l', {eq l l'} + {~eq l l'} := @weq 32 .
Lemma eq_refl : forall x, eq x x.
Proof. reflexivity. Qed.
Lemma eq_sym : forall x y, eq x y -> eq y x.
Proof. intros. symmetry. eauto. Qed.
Lemma eq_trans : forall x y z, eq x y -> eq y z -> eq x z.
Proof. intros. unfold eq in *. rewrite H. rewrite H0. eauto. Qed.
Lemma lt_trans : forall x y z, lt x y -> lt y z -> lt x z.
Proof. intros. unfold lt in *. eapply N.lt_trans; eauto. Qed.
Lemma lt_not_eq : forall x y, lt x y -> ~eq x y.
Proof.
intros. unfold eq, lt, wlt in *. intro.
rewrite <- N.compare_lt_iff in H.
subst; rewrite N.compare_refl in H; discriminate.
Qed.
Lemma compare : forall x y, Compare lt eq x y.
Proof.
intros. unfold lt, eq, wlt.
destruct (N.compare (wordToN x) (wordToN y)) eqn: eq.
- eapply EQ. apply N.compare_eq_iff in eq; apply wordToN_inj; eauto.
- eapply LT. abstract (rewrite <- N.compare_lt_iff; eauto).
- eapply GT. abstract (rewrite <- N.compare_gt_iff; eauto).
Defined.
End word_as_OT.
Module wordIndexedMap := FMapAVL.Make word_as_OT.
Module wordTreeBag := TreeBag wordIndexedMap.
Ltac BuildQSIndexedBag heading AttrList BuildEarlyBag BuildLastBag k ::=
lazymatch AttrList with
| (?Attr :: [ ])%list =>
let AttrKind := eval simpl in (KindIndexKind Attr) in
let AttrIndex := eval simpl in (KindIndexIndex Attr) in
let is_equality := eval compute in (string_dec AttrKind "EqualityIndex") in
lazymatch is_equality with
| left _ =>
let AttrType := eval compute in (Domain heading AttrIndex) in
lazymatch AttrType with
| BinNums.N =>
k (@NTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _
(@CountingListAsCorrectBag
(@RawTuple heading)
(IndexedTreeUpdateTermType heading)
(IndexedTreebupdate_transform heading))
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)
)
| word 32 =>
k (@wordTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _
(@CountingListAsCorrectBag
(@RawTuple heading)
(IndexedTreeUpdateTermType heading)
(IndexedTreebupdate_transform heading))
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)
)
| BinNums.Z =>
k (@ZTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _
(@CountingListAsCorrectBag
(@RawTuple heading)
(IndexedTreeUpdateTermType heading)
(IndexedTreebupdate_transform heading))
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)
)
| nat =>
k (@NatTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _
(@CountingListAsCorrectBag
(@RawTuple heading)
(IndexedTreeUpdateTermType heading)
(IndexedTreebupdate_transform heading))
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)
)
| string =>
k (@StringTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _
(@CountingListAsCorrectBag
(@RawTuple heading)
(IndexedTreeUpdateTermType heading)
(IndexedTreebupdate_transform heading))
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)
)
end
| right _ =>
BuildLastBag heading AttrList AttrKind AttrIndex k
end
| (?Attr :: ?AttrList')%list =>
let AttrKind := eval simpl in (KindIndexKind Attr) in
let AttrIndex := eval simpl in (KindIndexIndex Attr) in
let is_equality := eval compute in (string_dec AttrKind "EqualityIndex") in
lazymatch is_equality with
| left _ =>
let AttrType := eval compute in (Domain heading AttrIndex) in
lazymatch AttrType with
| BinNums.N =>
BuildQSIndexedBag
heading AttrList'
BuildEarlyBag BuildLastBag
ltac:(fun subtree =>
k (@NTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _ subtree
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)))
| BinNums.Z =>
BuildQSIndexedBag
heading AttrList'
BuildEarlyBag BuildLastBag
(fun x => GetAttributeRaw x AttrIndex)
ltac:(fun subtree =>
k (@ZTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _ subtree
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)))
| nat =>
BuildQSIndexedBag
heading AttrList'
BuildEarlyBag BuildLastBag
ltac:(fun subtree =>
k (@NatTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _ subtree
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)))
| string =>
BuildQSIndexedBag
heading AttrList'
BuildEarlyBag BuildLastBag
ltac:(fun subtree =>
k (@StringTreeBag.IndexedBagAsCorrectBag
_ _ _ _ _ _ _ subtree
(fun x => GetAttributeRaw (heading := heading) x AttrIndex)))
end
| right _ =>
BuildQSIndexedBag
heading AttrList'
BuildEarlyBag BuildLastBag
ltac:(fun subtree =>
BuildEarlyBag
heading AttrList AttrKind AttrIndex subtree k)
end
| ([ ])%list =>
k (@CountingListAsCorrectBag
(@RawTuple heading)
(IndexedTreeUpdateTermType heading)
(IndexedTreebupdate_transform heading))
end.
Ltac rewrite_drill ::=
subst_refine_evar; (first
[
match goal with
|- refine (b <- If_Opt_Then_Else _ _ _; _) _ =>
etransitivity;
[ apply refine_If_Opt_Then_Else_Bind
| simpl; eapply refine_If_Opt_Then_Else_trans;
intros; set_refine_evar ]
end
| eapply refine_under_bind_both; [ set_refine_evar | intros; set_refine_evar ]
| eapply refine_If_Then_Else; [ set_refine_evar | set_refine_evar ] ] ).
Ltac implement_insert CreateTerm EarlyIndex LastIndex
makeClause_dep EarlyIndex_dep LastIndex_dep ::=
repeat first
[simplify with monad laws; simpl
| match goal with
|- context [(@GetAttributeRaw ?heading {| prim_fst := ?a;
prim_snd := ?tup |} (Fin.FS ?BAidx)) ] =>
setoid_rewrite (@GetAttributeRaw_FS
(Vector.hd (AttrList heading))
{| AttrList := Vector.tl (AttrList heading)|} a _ BAidx)
end
| match goal with
| |- context [(@GetAttributeRaw ?heading {| prim_fst := ?a;
prim_snd := ?tup |} Fin.F1) ] =>
rewrite (@GetAttributeRaw_F1
(Vector.hd (AttrList heading))
{| AttrList := Vector.tl (AttrList heading) |} a)
end
| setoid_rewrite refine_If_Then_Else_Bind
| match goal with
H : DelegateToBag_AbsR ?r_o ?r_n
|- context[Pick (fun idx => forall Ridx, UnConstrFreshIdx (GetUnConstrRelation ?r_o Ridx) idx)] =>
let freshIdx := fresh in
destruct (exists_CompletelyUnConstrFreshIdx _ _ _ _ H) as [? freshIdx];
rewrite (refine_Pick_CompletelyUnConstrFreshIdx _ _ _ _ H _ freshIdx)
end
| implement_Query CreateTerm EarlyIndex LastIndex
makeClause_dep EarlyIndex_dep LastIndex_dep
| progress (rewrite ?refine_BagADT_QSInsert; try setoid_rewrite refine_BagADT_QSInsert); [ | solve [ eauto ] .. ]
| progress (rewrite ?refine_Pick_DelegateToBag_AbsR; try setoid_rewrite refine_Pick_DelegateToBag_AbsR); [ | solve [ eauto ] .. ] ].
Ltac choose_data_structures :=
simpl; pose_string_ids; pose_headings_all;
pose_search_term; pose_SearchUpdateTerms;
match goal with
|- context [ @Build_IndexedQueryStructure_Impl_Sigs _ ?indices ?SearchTerms _ ] => try unfold SearchTerms
end; BuildQSIndexedBags' BuildEarlyBag BuildLastBag.
Ltac insertOne :=
insertion CreateTerm EarlyIndex LastIndex
makeClause_dep EarlyIndex_dep LastIndex_dep.
Global Instance cache : Cache :=
{| CacheEncode := unit;
CacheDecode := unit;
Equiv ce cd := True |}.
Global Instance cacheAddNat : CacheAdd cache nat :=
{| addE ce n := tt;
addD cd n := tt;
add_correct ce cd t m := I |}.
Definition transformer : Transformer bin := btransformer.
Global Instance transformerUnit : TransformerUnitOpt transformer bool :=
{| T_measure t := 1;
transform_push_opt b t := (b :: t)%list;
transform_pop_opt t :=
match t with
| b :: t' => Some (b, t')
| _ => None
end%list
|}.
abstract (simpl; intros; omega).
abstract (simpl; intros; omega).
abstract (destruct b;
[ simpl; discriminate
| intros; injections; simpl; omega ] ).
reflexivity.
reflexivity.
abstract (destruct b; destruct b'; simpl; intros; congruence).
Defined.
Definition Empty : CacheEncode := tt.
Ltac decompose_EnumField Ridx Fidx :=
match goal with
|- appcontext[ @BuildADT (UnConstrQueryStructure (QueryStructureSchemaRaw ?qs_schema)) ]
=>
let n := eval compute in (NumAttr (GetHeading qs_schema Ridx)) in
let AbsR' := constr:(@DecomposeRawQueryStructureSchema_AbsR' n qs_schema ``Ridx ``Fidx id (fun i => ibound (indexb i))
(fun val =>
{| bindex := _;
indexb := {| ibound := val;
boundi := @eq_refl _ _ |} |})) in hone representation using AbsR'
end;
try first [ solve [simplify with monad laws;
apply refine_pick_val;
apply DecomposeRawQueryStructureSchema_empty_AbsR ]
| doAny ltac:(implement_DecomposeRawQueryStructure)
rewrite_drill ltac:(cbv beta; simpl; finish honing) ];
simpl; hone representation using (fun r_o r_n => snd r_o = r_n);
try first [
solve [simplify with monad laws; apply refine_pick_val; reflexivity ]
|
match goal with
H : snd ?r_o = ?r_n |- _
=> doAny ltac:(implement_DecomposeRawQueryStructure' H)
ltac:(rewrite_drill; simpl)
ltac:(finish honing)
end
];
cbv beta; unfold DecomposeRawQueryStructureSchema, DecomposeSchema; simpl.
Ltac makeEvar T k :=
let x := fresh in evar (x : T); let y := eval unfold x in x in clear x; k y.
Ltac shelve_inv :=
let H' := fresh in
let data := fresh in
intros data H';
repeat destruct H';
match goal with
| H : ?P data |- ?P_inv' =>
is_evar P;
let P_inv' := (eval pattern data in P_inv') in
let P_inv := match P_inv' with ?P_inv data => P_inv end in
let new_P_T := type of P in
makeEvar new_P_T
ltac:(fun new_P =>
unify P (fun data => new_P data /\ P_inv data)); apply (Logic.proj2 H)
end.
Ltac solve_data_inv :=
first [ intros; exact I
| solve
[ let data := fresh in
let H' := fresh in
let H'' := fresh in
intros data H' *;
match goal with
proj : BoundedIndex _ |- _ =>
instantiate (1 := ibound (indexb proj));
destruct H' as [? H'']; intuition;
try (rewrite <- H''; reflexivity);
destruct data; simpl; eauto
end ]
| shelve_inv ].
Ltac apply_compose :=
intros;
match goal with
H : cache_inv_Property ?P ?P_inv |- _ =>
first [eapply (compose_encode_correct_no_dep H); clear H
| eapply (compose_encode_correct H); clear H
]
end.
Ltac build_decoder :=
first [ solve [eapply Enum_decode_correct; [ repeat econstructor; simpl; intuition;
repeat match goal with
H : @Vector.In _ _ _ _ |- _ =>
inversion H;
apply_in_hyp Eqdep.EqdepTheory.inj_pair2; subst
end
| .. ]; eauto ]
| solve [eapply Word_decode_correct ]
| solve [eapply Nat_decode_correct ]
| solve [eapply String_decode_correct ]
| eapply (SumType_decode_correct
[ _ ]%vector
(icons _ inil)
(icons _ inil)
(@Iterate_Dep_Type_equiv' 1 _ (icons _ inil))
(@Iterate_Dep_Type_equiv' 1 _ (icons _ inil)));
[let idx' := fresh in
intro idx'; pattern idx';
eapply Iterate_Ensemble_equiv' with (idx := idx'); simpl;
repeat (match goal with |- prim_and _ _ => apply Build_prim_and; try exact I end)
| .. ]
| eapply (SumType_decode_correct
[ _; _]%vector
(icons _ (icons _ inil))
(icons _ (icons _ inil))
(@Iterate_Dep_Type_equiv' 2 _ (icons _ (icons _ inil)))
(@Iterate_Dep_Type_equiv' 2 _ (icons _ (icons _ inil))));
[let idx' := fresh in
intro idx'; pattern idx';
eapply Iterate_Ensemble_equiv' with (idx := idx'); simpl;
repeat (match goal with |- prim_and _ _ => apply Build_prim_and; try exact I end)
| .. ]
| eapply (SumType_decode_correct
[ _; _; _ ]%vector
(icons _ (icons _ (icons _ inil)))
(icons _ (icons _ (icons _ inil)))
(@Iterate_Dep_Type_equiv' 3 _ (icons _ (icons _ (icons _ inil))))
(@Iterate_Dep_Type_equiv' 3 _ (icons (icons _ (icons _ inil)))));
[let idx' := fresh in
intro idx'; pattern idx';
eapply Iterate_Ensemble_equiv' with (idx := idx'); simpl;
repeat (match goal with |- prim_and _ _ => apply Build_prim_and; try exact I end)
| .. ]
| intros;
match goal with
|- encode_decode_correct_f
_ _ _
(encode_list_Spec _) _ _ =>
eapply FixList_decode_correct end
| apply_compose ].
Lemma Fin_inv :
forall n (idx : Fin.t (S n)),
idx = Fin.F1 \/ exists n', idx = Fin.FS n'.
Proof. apply Fin.caseS; eauto. Qed.
Ltac solve_cache_inv :=
repeat instantiate (1 := fun _ => True);
unfold cache_inv_Property; intuition;
repeat match goal with
| idx : Fin.t (S _) |- _ =>
destruct (Fin_inv _ idx) as [? | [? ?] ]; subst; simpl; eauto
| idx : Fin.t 0 |- _ => inversion idx
end.
Ltac finalize_decoder P_inv :=
(unfold encode_decode_correct_f; intuition eauto);
[ computes_to_inv; injections; subst; simpl;
match goal with
H : Equiv _ ?env |- _ =>
eexists env; intuition eauto;
simpl;
match goal with
|- ?f ?a ?b ?c = ?P =>
let P' := (eval pattern a, b, c in P) in
let f' := match P' with ?f a b c => f end in
unify f f'; reflexivity
end
end
| injections; eauto
| eexists _; eexists _;
intuition eauto; injections; eauto using idx_ibound_eq;
try match goal with
|- P_inv ?data => destruct data;
simpl in *; eauto
end
].
Ltac build_decoder_component :=
(build_decoder || solve_data_inv).
|
{-# OPTIONS --without-K #-}
module NTypes.Product where
open import NTypes
open import PathOperations
open import PathStructure.Product
open import Types
×-isSet : ∀ {a b} {A : Set a} {B : Set b} →
isSet A → isSet B → isSet (A × B)
×-isSet A-set B-set x y p q
= split-eq p ⁻¹
· ap (λ y → ap₂ _,_ y (ap π₂ p))
(A-set _ _ (ap π₁ p) (ap π₁ q))
· ap (λ y → ap₂ _,_ (ap π₁ q) y)
(B-set _ _ (ap π₂ p) (ap π₂ q))
· split-eq q
where
split-eq : (p : x ≡ y) → ap₂ _,_ (ap π₁ p) (ap π₂ p) ≡ p
split-eq = π₂ (π₂ (π₂ split-merge-eq))
|
/-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
! This file was ported from Lean 3 source module ring_theory.witt_vector.identities
! leanprover-community/mathlib commit 0798037604b2d91748f9b43925fb7570a5f3256c
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathbin.RingTheory.WittVector.Frobenius
import Mathbin.RingTheory.WittVector.Verschiebung
import Mathbin.RingTheory.WittVector.MulP
/-!
## Identities between operations on the ring of Witt vectors
In this file we derive common identities between the Frobenius and Verschiebung operators.
## Main declarations
* `frobenius_verschiebung`: the composition of Frobenius and Verschiebung is multiplication by `p`
* `verschiebung_mul_frobenius`: the “projection formula”: `V(x * F y) = V x * y`
* `iterate_verschiebung_mul_coeff`: an identity from [Haze09] 6.2
## References
* [Hazewinkel, *Witt Vectors*][Haze09]
* [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21]
-/
namespace WittVector
variable {p : ℕ} {R : Type _} [hp : Fact p.Prime] [CommRing R]
-- mathport name: expr𝕎
local notation "𝕎" => WittVector p
-- type as `\bbW`
include hp
noncomputable section
/-- The composition of Frobenius and Verschiebung is multiplication by `p`. -/
theorem frobenius_verschiebung (x : 𝕎 R) : frobenius (verschiebung x) = x * p :=
by
ghost_calc x
ghost_simp [mul_comm]
#align witt_vector.frobenius_verschiebung WittVector.frobenius_verschiebung
/-- Verschiebung is the same as multiplication by `p` on the ring of Witt vectors of `zmod p`. -/
theorem verschiebung_zMod (x : 𝕎 (ZMod p)) : verschiebung x = x * p := by
rw [← frobenius_verschiebung, frobenius_zmodp]
#align witt_vector.verschiebung_zmod WittVector.verschiebung_zMod
variable (p R)
theorem coeff_p_pow [CharP R p] (i : ℕ) : (p ^ i : 𝕎 R).coeff i = 1 :=
by
induction' i with i h
· simp only [one_coeff_zero, Ne.def, pow_zero]
·
rw [pow_succ', ← frobenius_verschiebung, coeff_frobenius_char_p, verschiebung_coeff_succ, h,
one_pow]
#align witt_vector.coeff_p_pow WittVector.coeff_p_pow
theorem coeff_p_pow_eq_zero [CharP R p] {i j : ℕ} (hj : j ≠ i) : (p ^ i : 𝕎 R).coeff j = 0 :=
by
induction' i with i hi generalizing j
· rw [pow_zero, one_coeff_eq_of_pos]
exact Nat.pos_of_ne_zero hj
· rw [pow_succ', ← frobenius_verschiebung, coeff_frobenius_char_p]
cases j
· rw [verschiebung_coeff_zero, zero_pow]
exact Nat.Prime.pos hp.out
· rw [verschiebung_coeff_succ, hi, zero_pow]
· exact Nat.Prime.pos hp.out
· exact ne_of_apply_ne (fun j : ℕ => j.succ) hj
#align witt_vector.coeff_p_pow_eq_zero WittVector.coeff_p_pow_eq_zero
theorem coeff_p [CharP R p] (i : ℕ) : (p : 𝕎 R).coeff i = if i = 1 then 1 else 0 :=
by
split_ifs with hi
· simpa only [hi, pow_one] using coeff_p_pow p R 1
· simpa only [pow_one] using coeff_p_pow_eq_zero p R hi
#align witt_vector.coeff_p WittVector.coeff_p
@[simp]
theorem coeff_p_zero [CharP R p] : (p : 𝕎 R).coeff 0 = 0 :=
by
rw [coeff_p, if_neg]
exact zero_ne_one
#align witt_vector.coeff_p_zero WittVector.coeff_p_zero
@[simp]
theorem coeff_p_one [CharP R p] : (p : 𝕎 R).coeff 1 = 1 := by rw [coeff_p, if_pos rfl]
#align witt_vector.coeff_p_one WittVector.coeff_p_one
theorem p_nonzero [Nontrivial R] [CharP R p] : (p : 𝕎 R) ≠ 0 :=
by
intro h
simpa only [h, zero_coeff, zero_ne_one] using coeff_p_one p R
#align witt_vector.p_nonzero WittVector.p_nonzero
theorem FractionRing.p_nonzero [Nontrivial R] [CharP R p] : (p : FractionRing (𝕎 R)) ≠ 0 := by
simpa using (IsFractionRing.injective (𝕎 R) (FractionRing (𝕎 R))).Ne (p_nonzero _ _)
#align witt_vector.fraction_ring.p_nonzero WittVector.FractionRing.p_nonzero
variable {p R}
/-- The “projection formula” for Frobenius and Verschiebung. -/
theorem verschiebung_mul_frobenius (x y : 𝕎 R) :
verschiebung (x * frobenius y) = verschiebung x * y :=
by
ghost_calc x y
rintro ⟨⟩ <;> ghost_simp [mul_assoc]
#align witt_vector.verschiebung_mul_frobenius WittVector.verschiebung_mul_frobenius
theorem mul_charP_coeff_zero [CharP R p] (x : 𝕎 R) : (x * p).coeff 0 = 0 :=
by
rw [← frobenius_verschiebung, coeff_frobenius_char_p, verschiebung_coeff_zero, zero_pow]
exact Nat.Prime.pos hp.out
#align witt_vector.mul_char_p_coeff_zero WittVector.mul_charP_coeff_zero
theorem mul_charP_coeff_succ [CharP R p] (x : 𝕎 R) (i : ℕ) :
(x * p).coeff (i + 1) = x.coeff i ^ p := by
rw [← frobenius_verschiebung, coeff_frobenius_char_p, verschiebung_coeff_succ]
#align witt_vector.mul_char_p_coeff_succ WittVector.mul_charP_coeff_succ
theorem verschiebung_frobenius [CharP R p] (x : 𝕎 R) : verschiebung (frobenius x) = x * p :=
by
ext ⟨i⟩
· rw [mul_char_p_coeff_zero, verschiebung_coeff_zero]
· rw [mul_char_p_coeff_succ, verschiebung_coeff_succ, coeff_frobenius_char_p]
#align witt_vector.verschiebung_frobenius WittVector.verschiebung_frobenius
theorem verschiebung_frobenius_comm [CharP R p] :
Function.Commute (verschiebung : 𝕎 R → 𝕎 R) frobenius := fun x => by
rw [verschiebung_frobenius, frobenius_verschiebung]
#align witt_vector.verschiebung_frobenius_comm WittVector.verschiebung_frobenius_comm
/-!
## Iteration lemmas
-/
open Function
theorem iterate_verschiebung_coeff (x : 𝕎 R) (n k : ℕ) :
((verschiebung^[n]) x).coeff (k + n) = x.coeff k :=
by
induction' n with k ih
· simp
· rw [iterate_succ_apply', Nat.add_succ, verschiebung_coeff_succ]
exact ih
#align witt_vector.iterate_verschiebung_coeff WittVector.iterate_verschiebung_coeff
theorem iterate_verschiebung_mul_left (x y : 𝕎 R) (i : ℕ) :
(verschiebung^[i]) x * y = (verschiebung^[i]) (x * (frobenius^[i]) y) :=
by
induction' i with i ih generalizing y
· simp
· rw [iterate_succ_apply', ← verschiebung_mul_frobenius, ih, iterate_succ_apply']
rfl
#align witt_vector.iterate_verschiebung_mul_left WittVector.iterate_verschiebung_mul_left
section CharP
variable [CharP R p]
theorem iterate_verschiebung_mul (x y : 𝕎 R) (i j : ℕ) :
(verschiebung^[i]) x * (verschiebung^[j]) y =
(verschiebung^[i + j]) ((frobenius^[j]) x * (frobenius^[i]) y) :=
by
calc
_ = (verschiebung^[i]) (x * (frobenius^[i]) ((verschiebung^[j]) y)) := _
_ = (verschiebung^[i]) (x * (verschiebung^[j]) ((frobenius^[i]) y)) := _
_ = (verschiebung^[i]) ((verschiebung^[j]) ((frobenius^[i]) y) * x) := _
_ = (verschiebung^[i]) ((verschiebung^[j]) ((frobenius^[i]) y * (frobenius^[j]) x)) := _
_ = (verschiebung^[i + j]) ((frobenius^[i]) y * (frobenius^[j]) x) := _
_ = _ := _
· apply iterate_verschiebung_mul_left
· rw [verschiebung_frobenius_comm.iterate_iterate] <;> infer_instance
· rw [mul_comm]
· rw [iterate_verschiebung_mul_left]
· rw [iterate_add_apply]
· rw [mul_comm]
#align witt_vector.iterate_verschiebung_mul WittVector.iterate_verschiebung_mul
theorem iterate_frobenius_coeff (x : 𝕎 R) (i k : ℕ) :
((frobenius^[i]) x).coeff k = x.coeff k ^ p ^ i :=
by
induction' i with i ih
· simp
· rw [iterate_succ_apply', coeff_frobenius_char_p, ih]
ring
#align witt_vector.iterate_frobenius_coeff WittVector.iterate_frobenius_coeff
/-- This is a slightly specialized form of [Hazewinkel, *Witt Vectors*][Haze09] 6.2 equation 5. -/
theorem iterate_verschiebung_mul_coeff (x y : 𝕎 R) (i j : ℕ) :
((verschiebung^[i]) x * (verschiebung^[j]) y).coeff (i + j) =
x.coeff 0 ^ p ^ j * y.coeff 0 ^ p ^ i :=
by
calc
_ = ((verschiebung^[i + j]) ((frobenius^[j]) x * (frobenius^[i]) y)).coeff (i + j) := _
_ = ((frobenius^[j]) x * (frobenius^[i]) y).coeff 0 := _
_ = ((frobenius^[j]) x).coeff 0 * ((frobenius^[i]) y).coeff 0 := _
_ = _ := _
· rw [iterate_verschiebung_mul]
· convert iterate_verschiebung_coeff _ _ _ using 2
rw [zero_add]
· apply mul_coeff_zero
· simp only [iterate_frobenius_coeff]
#align witt_vector.iterate_verschiebung_mul_coeff WittVector.iterate_verschiebung_mul_coeff
end CharP
end WittVector
|
theory Pls_comm_enat
imports Main "~~/src/HOL/Library/BNF_Corec" "$HIPSTER_HOME/IsaHipster"
begin
setup Tactic_Data.set_coinduct_sledgehammer
codatatype (sset: 'a) Stream =
SCons (shd: 'a) (stl: "'a Stream")
codatatype ENat = is_zero: EZ | ESuc (epred: ENat)
primcorec eplus :: "ENat \<Rightarrow> ENat \<Rightarrow> ENat" where
"eplus m n = (if is_zero m then n else ESuc (eplus (epred m) n))"
primcorec pls :: "ENat Stream \<Rightarrow> ENat Stream \<Rightarrow> ENat Stream" where
"pls s t = SCons (eplus (shd s) (shd t)) (pls (stl s) (stl t))"
datatype 'a Lst =
Emp
| Cons "'a" "'a Lst"
fun obsStream :: "int \<Rightarrow> 'a Stream \<Rightarrow> 'a Lst" where
"obsStream n s = (if (n \<le> 0) then Emp else Cons (shd s) (obsStream (n - 1) (stl s)))"
hipster_obs Stream Lst obsStream pls
lemma lemma_a [thy_expl]: "eplus x EZ = x"
apply (coinduction arbitrary: x rule: Pls_comm_enat.ENat.coinduct_strong)
by simp
lemma lemma_aa [thy_expl]: "eplus EZ x = x"
apply (coinduction arbitrary: x rule: Pls_comm_enat.ENat.coinduct_strong)
by simp
lemma lemma_ab [thy_expl]: "eplus (ESuc x) y = eplus x (ESuc y)"
apply (coinduction arbitrary: x y rule: Pls_comm_enat.ENat.coinduct_strong)
apply simp
by (metis ENat.collapse(2) eplus.code)
lemma lemma_ac [thy_expl]: "ESuc (eplus x y) = eplus x (ESuc y)"
apply (coinduction arbitrary: x y rule: Pls_comm_enat.ENat.coinduct_strong)
apply simp
by (metis eplus.code)
lemma lemma_ad [thy_expl]: "eplus (eplus x y) z = eplus x (eplus y z)"
apply (coinduction arbitrary: x y z rule: Pls_comm_enat.ENat.coinduct_strong)
apply simp
by auto
lemma lemma_ae [thy_expl]: "eplus y x = eplus x y"
apply (coinduction arbitrary: x y rule: Pls_comm_enat.ENat.coinduct_strong)
apply simp
by (metis ENat.collapse(1) ENat.collapse(2) lemma_a lemma_ab)
theorem pls_comm: "pls s t = pls t s"
by hipster_coinduct_sledgehammer
(*by hipster_coinduct_sledgehammer
Failed to apply initial proof method*) |
module UniverseCollapse
(down : Set₁ -> Set)
(up : Set → Set₁)
(iso : ∀ {A} → down (up A) → A)
(osi : ∀ {A} → up (down A) → A) where
anything : (A : Set) → A
anything = {!!}
|
Überall & Nirgendwo: Gespenster Geburtstag Spiele With Partyspiele Kindergeburtstag Uploaded by robert carlson on Tuesday, January 22nd, 2019 in category Blog.
See also Kindergeburtstag Im Freien Ideen Für Partyspiele Check More At Http Intended For Partyspiele Kindergeburtstag from Blog Topic.
Here we have another image Legoparty Kindergeburtstag Lego Spiele Ideen | Legos | Birthday For Partyspiele Kindergeburtstag featured under Überall & Nirgendwo: Gespenster Geburtstag Spiele With Partyspiele Kindergeburtstag. We hope you enjoyed it and if you want to download the pictures in high quality, simply right click the image and choose "Save As". Thanks for reading Überall & Nirgendwo: Gespenster Geburtstag Spiele With Partyspiele Kindergeburtstag. |
(* ll_fragments library for yalla *)
(* output in Type *)
(** * Definitions of various Linear Logic fragments *)
Require Import Bool_more.
Require Import List_more.
Require Import List_Type_more.
Require Import Permutation_Type_more.
Require Import Permutation_Type_solve.
Require Import genperm_Type.
Require Export ll_prop.
Require Import subs.
(** ** Standard linear logic: [ll_ll] (no mix, no axiom, commutative) *)
(** cut / axioms / mix0 / mix2 / permutation *)
Definition pfrag_ll := mk_pfrag false NoAxioms false false true.
(* cut axioms mix0 mix2 perm *)
Definition ll_ll := ll pfrag_ll.
Lemma cut_ll_r : forall A l1 l2,
ll_ll (dual A :: l1) -> ll_ll (A :: l2) -> ll_ll (l2 ++ l1).
Proof with myeeasy.
intros A l1 l2 pi1 pi2.
eapply cut_r_axfree...
intros a ; destruct a.
Qed.
Lemma cut_ll_admissible :
forall l, ll (cutupd_pfrag pfrag_ll true) l -> ll_ll l.
Proof with myeeasy.
intros l pi.
induction pi ; try (now econstructor).
- eapply ex_r...
- eapply ex_wn_r...
- eapply cut_ll_r...
Qed.
(** ** Linear logic with mix0: [ll_mix0] (no mix2, no axiom, commutative) *)
(** cut / axioms / mix0 / mix2 / permutation *)
Definition pfrag_mix0 := mk_pfrag false NoAxioms true false true.
(* cut axioms mix0 mix2 perm *)
Definition ll_mix0 := ll pfrag_mix0.
Definition mix0add_pfrag P :=
mk_pfrag (pcut P) (pgax P) true (pmix2 P) (pperm P).
Lemma cut_mix0_r : forall A l1 l2,
ll_mix0 (dual A :: l1) -> ll_mix0 (A :: l2) -> ll_mix0 (l2 ++ l1).
Proof with myeeasy.
intros A l1 l2 pi1 pi2.
eapply cut_r_axfree...
intros a ; destruct a.
Qed.
Lemma cut_mix0_admissible :
forall l, ll (cutupd_pfrag pfrag_mix0 true) l -> ll_mix0 l.
Proof with myeeasy.
intros l pi.
induction pi ; try (now econstructor).
- eapply ex_r...
- eapply ex_wn_r...
- eapply cut_mix0_r...
Qed.
(** Provability in [ll_mix0] is equivalent to adding [wn one] in [ll] *)
Lemma mix0_to_ll {P} : pperm P = true -> forall b0 bp l,
ll (mk_pfrag P.(pcut) P.(pgax) b0 P.(pmix2) bp) l -> ll P (wn one :: l).
Proof with myeeasy ; try PCperm_Type_solve.
intros fp b0 bp l pi.
eapply (ext_wn_param _ P fp _ (one :: nil)) in pi.
- eapply ex_r...
- intros Hcut...
- simpl ; intros a.
eapply ex_r ; [ | apply PCperm_Type_last ].
apply wk_r.
apply gax_r.
- intros.
eapply de_r.
eapply one_r.
- intros Hpmix2 Hpmix2'.
exfalso.
simpl in Hpmix2.
rewrite Hpmix2 in Hpmix2'.
inversion Hpmix2'.
Qed.
Lemma ll_to_mix0_axat {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->
pperm P = true -> forall l,
ll P (wn one :: l) -> ll (mix0add_pfrag P) l.
Proof with myeeasy ; try PCperm_Type_solve.
intros Hgax Hperm.
enough (forall l, ll P l -> forall l' (l0 l1 : list unit),
Permutation_Type l (l' ++ map (fun _ => one) l1
++ map (fun _ => wn one) l0) ->
ll (mix0add_pfrag P) l').
{ intros l pi.
eapply (X _ pi l (tt :: nil) nil)... }
intros l pi.
induction pi ; intros l' l0' l1' HP.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
apply Permutation_Type_length_1_inv in HP.
apply app_eq_unit_Type in HP.
destruct HP as [[Heq1 Heq2] | [Heq1 Heq2]] ; subst ; destruct l' ; inversion Heq ; subst.
+ destruct l1' ; inversion H0.
destruct l0' ; inversion H1.
+ destruct l' ; inversion H1.
* destruct l1' ; inversion H0.
destruct l0' ; inversion H2.
* destruct l' ; inversion H2.
rewrite H3.
apply ax_r.
+ destruct l1' ; inversion H0.
destruct l0' ; inversion H1.
+ destruct l' ; inversion H1.
* destruct l1' ; inversion H0.
destruct l0' ; inversion H2.
* destruct l' ; inversion H2.
rewrite H3.
eapply ex_r ; [ apply ax_r | ]...
- rewrite Hperm in p ; simpl in p.
eapply IHpi.
etransitivity...
- apply (Permutation_Type_map wn) in p.
eapply IHpi.
etransitivity...
- apply Permutation_Type_nil in HP.
destruct l' ; inversion HP.
rewrite H0.
apply mix0_r...
- apply Permutation_Type_app_app_inv in HP.
destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;
simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.
apply Permutation_Type_app_app_inv in HP4.
destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;
simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.
symmetry in HP1b.
apply Permutation_Type_map_inv in HP1b.
destruct HP1b as [la Heqa _].
decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.
symmetry in HP2b.
apply Permutation_Type_map_inv in HP2b.
destruct HP2b as [lb Heqb _].
decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.
apply (Permutation_Type_app_head l2a) in HP4b.
assert (IHP1 := Permutation_Type_trans HP2 HP4b).
apply (Permutation_Type_app_head l1a) in HP3b.
assert (IHP2 := Permutation_Type_trans HP1 HP3b).
apply IHpi1 in IHP1.
apply IHpi2 in IHP2.
symmetry in HP3.
eapply ex_r ; [ apply mix2_r | simpl ; rewrite Hperm ; apply HP3 ]...
- apply Permutation_Type_length_1_inv in HP.
destruct l' ; inversion HP.
+ apply mix0_r...
+ apply app_eq_nil in H1 ; destruct H1 ; subst.
apply one_r.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply IHpi in HP.
eapply ex_r ; [ apply bot_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
remember (l'l ++ l) as l'.
apply Permutation_Type_app_app_inv in HP.
destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;
simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.
apply Permutation_Type_app_app_inv in HP4.
destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;
simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.
symmetry in HP1b.
apply Permutation_Type_map_inv in HP1b.
destruct HP1b as [la Heqa _].
decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.
symmetry in HP2b.
apply Permutation_Type_map_inv in HP2b.
destruct HP2b as [lb Heqb _].
decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.
apply (Permutation_Type_app_head l2a) in HP4b.
assert (IHP1 := Permutation_Type_trans HP2 HP4b).
apply (@Permutation_Type_cons _ A _ eq_refl) in IHP1.
rewrite app_comm_cons in IHP1.
apply (Permutation_Type_app_head l1a) in HP3b.
assert (IHP2 := Permutation_Type_trans HP1 HP3b).
apply (@Permutation_Type_cons _ B _ eq_refl) in IHP2.
rewrite app_comm_cons in IHP2.
apply IHpi1 in IHP1.
apply IHpi2 in IHP2.
symmetry in HP3.
apply (Permutation_Type_cons_app _ _ (tens A B)) in HP3.
eapply ex_r ; [ apply tens_r | simpl ; rewrite Hperm ; apply HP3 ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* exfalso.
decomp_map_Type Heq0 ; inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ B _ eq_refl) in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite 2 app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply parr_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ eapply ex_r ; [ apply top_r
| simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply plus_r1 | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply plus_r2 | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
assert (HP2 := HP).
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi1 in HP.
apply (@Permutation_Type_cons _ B _ eq_refl) in HP2.
rewrite app_comm_cons in HP2.
apply IHpi2 in HP2.
eapply ex_r ; [ apply with_r
| simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ symmetry in HP.
apply Permutation_Type_map_inv in HP.
destruct HP as [l' Heq HP].
decomp_map_Type Heq ;
simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; simpl in Heq5 ; subst ;
simpl in HP.
apply (Permutation_Type_map wn) in HP.
list_simpl in HP.
rewrite app_assoc in HP.
rewrite <- map_app in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
rewrite <- Heq2 in HP.
rewrite <- Heq5 in HP.
apply IHpi in HP.
eapply ex_r ; [ apply oc_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply de_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.
inversion Heq2 ; subst.
list_simpl in HP ; rewrite <- map_app in HP.
apply (@Permutation_Type_cons _ one _ eq_refl) in HP.
assert (Permutation_Type (one :: l)
(l' ++ map (fun _ : unit => one) (tt :: l1')
++ map (fun _ : unit => wn one) (l1 ++ l4)))
as HP' by (etransitivity ; [ apply HP | ] ; perm_Type_solve).
apply IHpi in HP'...
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply IHpi in HP.
eapply ex_r ; [ apply wk_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.
inversion Heq2 ; subst.
list_simpl in HP ; rewrite <- map_app in HP.
apply IHpi in HP...
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.
apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.
rewrite 2 app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply co_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.
inversion Heq2 ; subst.
list_simpl in HP ; rewrite <- map_app in HP.
apply (@Permutation_Type_cons _ (wn one) _ eq_refl) in HP.
apply (@Permutation_Type_cons _ (wn one) _ eq_refl) in HP.
assert (Permutation_Type (wn one :: wn one :: l)
(l' ++ map (fun _ : unit => one) l1' ++
map (fun _ : unit => wn one) (tt :: tt :: l1 ++ l4)))
as HP' by (etransitivity ; [ apply HP | perm_Type_solve ]).
apply IHpi in HP'...
- apply Permutation_Type_app_app_inv in HP.
destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;
simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.
apply Permutation_Type_app_app_inv in HP4.
destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;
simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.
symmetry in HP1b.
apply Permutation_Type_map_inv in HP1b.
destruct HP1b as [la Heqa _].
decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.
symmetry in HP2b.
apply Permutation_Type_map_inv in HP2b.
destruct HP2b as [lb Heqb _].
decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.
apply (Permutation_Type_app_head l2a) in HP4b.
assert (IHP1 := Permutation_Type_trans HP2 HP4b).
apply (@Permutation_Type_cons _ (dual A) _ eq_refl) in IHP1.
rewrite app_comm_cons in IHP1.
apply (Permutation_Type_app_head l1a) in HP3b.
assert (IHP2 := Permutation_Type_trans HP1 HP3b).
apply (@Permutation_Type_cons _ A _ eq_refl) in IHP2.
rewrite app_comm_cons in IHP2.
apply IHpi1 in IHP1.
apply IHpi2 in IHP2.
symmetry in HP3.
eapply ex_r ; [ eapply cut_r | simpl ; rewrite Hperm ; apply HP3 ]...
- destruct l1' ; destruct l0' ; simpl in HP.
+ eapply ex_r ; [ apply gax_r | simpl ; rewrite Hperm ]...
+ exfalso.
apply Permutation_Type_vs_elt_inv in HP.
specialize (Hgax a).
destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.
apply Forall_elt in Hgax.
inversion Hgax.
+ exfalso.
apply Permutation_Type_vs_elt_inv in HP.
specialize (Hgax a).
destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.
apply Forall_elt in Hgax.
inversion Hgax.
+ exfalso.
apply Permutation_Type_vs_elt_inv in HP.
specialize (Hgax a).
destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.
apply Forall_elt in Hgax.
inversion Hgax.
Qed.
Lemma ll_to_mix0_cut {P} : forall l,
ll P (wn one :: l) -> ll (mk_pfrag true P.(pgax) true P.(pmix2) P.(pperm)) l.
Proof with myeasy.
intros l pi.
eapply stronger_pfrag in pi.
- rewrite <- (app_nil_r l).
eapply cut_r ; [ | | apply pi]...
change nil with (map wn nil).
apply oc_r.
apply bot_r.
eapply mix0_r...
- nsplit 5...
+ destruct pcut...
+ intros a.
exists a...
+ destruct pmix0...
Qed.
Lemma mix0_wn_one : forall l, ll_mix0 (wn one :: l) -> ll_mix0 l.
Proof with myeeasy.
intros l pi.
(* an alternative proof is by introducing a cut with (oc bot) *)
assert (pfrag_mix0 = mk_pfrag pfrag_mix0.(pcut) pfrag_mix0.(pgax)
true pfrag_mix0.(pmix2) true)
as Heqfrag by reflexivity.
apply cut_mix0_admissible.
apply ll_to_mix0_cut.
apply co_r.
eapply mix0_to_ll...
Qed.
(** Provability in [ll_mix0] is equivalent to provability of [ll]
extended with the provability of [bot :: bot :: nil] *)
Lemma mix0_to_ll_bot {P} : pcut P = true -> pperm P = true -> forall bc b0 bp l,
ll (mk_pfrag bc P.(pgax) b0 P.(pmix2) bp) l ->
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => bot :: bot :: nil
end))) l.
Proof with myeeasy ; try (unfold PCperm_Type ; PCperm_Type_solve).
remember (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => bot :: bot :: nil
end))) as P'.
intros fc fp bc b0 bp l pi.
eapply stronger_pfrag in pi.
- eapply mix0_to_ll in pi...
assert (pcut P' = true) as fc' by (rewrite HeqP' ; simpl ; assumption).
apply (stronger_pfrag _ P') in pi.
+ assert (ll P' (bot :: map wn nil)) as pi'.
{ change (bot :: map wn nil) with ((bot :: nil) ++ nil).
eapply (@cut_r _ fc' bot).
- apply one_r.
- assert ({ b | bot :: bot :: nil = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now (exists (inr tt))).
rewrite Hgax.
apply gax_r. }
apply oc_r in pi'.
rewrite <- (app_nil_l l).
eapply (@cut_r _ fc' (oc bot)) ; [ simpl ; apply pi | apply pi' ].
+ nsplit 5 ; rewrite HeqP'...
simpl ; intros a ; exists (inl a)...
- nsplit 5 ; intros ; simpl...
+ rewrite fc.
destruct bc...
+ exists a...
Qed.
Lemma ll_bot_to_mix0 {P} : forall l,
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => bot :: bot :: nil
end))) l
-> ll (mk_pfrag P.(pcut) P.(pgax) true P.(pmix2) P.(pperm)) l.
Proof with myeeasy.
intros l pi.
remember (mk_pfrag P.(pcut) P.(pgax) true P.(pmix2) P.(pperm)) as P'.
apply (stronger_pfrag _
(axupd_pfrag P' (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => bot :: bot :: nil
end)))) in pi.
- eapply ax_gen...
clear - HeqP' ; simpl ; intros a.
destruct a.
+ assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now exists p).
rewrite Hgax.
apply gax_r.
+ destruct u.
apply bot_r.
apply bot_r.
apply mix0_r.
rewrite HeqP'...
- rewrite HeqP' ; nsplit 5 ; simpl ; intros...
+ exists a...
+ destruct (pmix0 P)...
Qed.
(** [mix2] is not valid in [ll_mix0] *)
Lemma mix0_not_mix2 : ll_mix0 (one :: one :: nil) -> False.
Proof.
intros pi.
remember (one :: one :: nil) as l.
revert Heql ; induction pi ; intros Heql ; subst ; try inversion Heql.
- apply IHpi.
simpl in p ; apply Permutation_Type_sym in p.
apply Permutation_Type_length_2_inv in p.
destruct p ; assumption.
- destruct l1 ; destruct lw' ; inversion Heql ; subst.
+ now symmetry in p ; apply Permutation_Type_nil in p ; subst.
+ now symmetry in p ; apply Permutation_Type_nil in p ; subst.
+ destruct l1 ; inversion H2.
destruct l1 ; inversion H3.
- inversion f.
- inversion f.
- destruct a.
Qed.
(** ** Linear logic with mix2: [ll_mix2] (no mix0, no axiom, commutative) *)
(** cut / axioms / mix0 / mix2 / permutation *)
Definition pfrag_mix2 := mk_pfrag false NoAxioms false true true.
(* cut axioms mix0 mix2 perm *)
Definition ll_mix2 := ll pfrag_mix2.
Definition mix2add_pfrag P :=
mk_pfrag (pcut P) (pgax P) (pmix0 P) true (pperm P).
Lemma cut_mix2_r : forall A l1 l2,
ll_mix2 (dual A :: l1) -> ll_mix2 (A :: l2) -> ll_mix2 (l2 ++ l1).
Proof with myeeasy.
intros A l1 l2 pi1 pi2.
eapply cut_r_axfree...
intros a ; destruct a.
Qed.
Lemma cut_mix2_admissible :
forall l, ll (cutupd_pfrag pfrag_mix2 true) l -> ll_mix2 l.
Proof with myeeasy.
intros l pi.
induction pi ; try (now econstructor).
- eapply ex_r...
- eapply ex_wn_r...
- eapply cut_mix2_r...
Qed.
(** Provability in [ll_mix2] is equivalent to adding [wn (tens bot bot)] in [ll] *)
Lemma mix2_to_ll {P} : pperm P = true -> forall b2 bp l,
ll (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) b2 bp) l -> ll P (wn (tens bot bot) :: l).
Proof with myeeasy ; try PCperm_Type_solve.
intros fp b2 bp l pi.
eapply (ext_wn_param _ P fp _ (tens bot bot :: nil)) in pi.
- eapply ex_r...
- intros Hcut...
- simpl ; intros a.
eapply ex_r ; [ | apply PCperm_Type_last ].
apply wk_r.
apply gax_r.
- intros Hpmix0 Hpmix0'.
exfalso.
simpl in Hpmix0.
rewrite Hpmix0 in Hpmix0'.
inversion Hpmix0'.
- intros _ _ l1 l2 pi1 pi2.
apply (ex_r _ (wn (tens bot bot) :: l2 ++ l1))...
apply co_r.
apply co_r.
apply de_r.
eapply ex_r.
+ apply tens_r ; apply bot_r ; [ apply pi1 | apply pi2 ].
+ rewrite fp...
Qed.
Lemma ll_to_mix2_axat {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->
pperm P = true -> forall l,
ll P (wn (tens bot bot) :: l) -> ll (mix2add_pfrag P) l.
Proof with myeeasy ; try PCperm_Type_solve.
intros Hgax Hperm.
assert (forall a, In bot (projT2 (pgax P) a) -> False) as Hgaxbot.
{ intros a Hbot.
apply (Forall_In _ _ _ (Hgax a)) in Hbot.
inversion Hbot. }
enough (forall l, ll P l -> forall l' (l0 l1 : list unit),
Permutation_Type l (l' ++ map (fun _ => tens bot bot) l1
++ map (fun _ => wn (tens bot bot)) l0) ->
ll (mix2add_pfrag P) l').
{ intros l pi.
eapply (X _ pi l (tt :: nil) nil)... }
intros l pi.
induction pi ; intros l' l0' l1' HP.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
apply Permutation_Type_length_1_inv in HP.
apply app_eq_unit_Type in HP.
destruct HP as [[Heq1 Heq2] | [Heq1 Heq2]] ; subst ; destruct l' ; inversion Heq ; subst.
+ destruct l1' ; inversion H0.
destruct l0' ; inversion H1.
+ destruct l' ; inversion H1.
* destruct l1' ; inversion H0.
destruct l0' ; inversion H2.
* destruct l' ; inversion H2.
rewrite H3.
apply ax_r.
+ destruct l1' ; inversion H0.
destruct l0' ; inversion H1.
+ destruct l' ; inversion H1.
* destruct l1' ; inversion H0.
destruct l0' ; inversion H2.
* destruct l' ; inversion H2.
rewrite H3.
eapply ex_r ; [ apply ax_r | ]...
- rewrite Hperm in p ; simpl in p.
eapply IHpi.
etransitivity...
- apply (Permutation_Type_map wn) in p.
eapply IHpi.
etransitivity...
- apply Permutation_Type_nil in HP.
destruct l' ; inversion HP.
rewrite H0.
apply mix0_r...
- apply Permutation_Type_app_app_inv in HP.
destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;
simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.
apply Permutation_Type_app_app_inv in HP4.
destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;
simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.
symmetry in HP1b.
apply Permutation_Type_map_inv in HP1b.
destruct HP1b as [la Heqa _].
decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.
symmetry in HP2b.
apply Permutation_Type_map_inv in HP2b.
destruct HP2b as [lb Heqb _].
decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.
apply (Permutation_Type_app_head l2a) in HP4b.
assert (IHP1 := Permutation_Type_trans HP2 HP4b).
apply (Permutation_Type_app_head l1a) in HP3b.
assert (IHP2 := Permutation_Type_trans HP1 HP3b).
apply IHpi1 in IHP1.
apply IHpi2 in IHP2.
symmetry in HP3.
eapply ex_r ; [ apply mix2_r | simpl ; rewrite Hperm ; apply HP3 ]...
- apply Permutation_Type_length_1_inv in HP.
destruct l' ; inversion HP.
+ destruct l1' ; inversion H0.
destruct l0' ; inversion H1.
+ apply app_eq_nil in H1 ; destruct H1 ; subst.
apply one_r.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply IHpi in HP.
eapply ex_r ; [ apply bot_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
remember (l'l ++ l) as l'.
apply Permutation_Type_app_app_inv in HP.
destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;
simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.
apply Permutation_Type_app_app_inv in HP4.
destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;
simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.
symmetry in HP1b.
apply Permutation_Type_map_inv in HP1b.
destruct HP1b as [la Heqa _].
decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.
symmetry in HP2b.
apply Permutation_Type_map_inv in HP2b.
destruct HP2b as [lb Heqb _].
decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.
apply (Permutation_Type_app_head l2a) in HP4b.
assert (IHP1 := Permutation_Type_trans HP2 HP4b).
apply (@Permutation_Type_cons _ A _ eq_refl) in IHP1.
rewrite app_comm_cons in IHP1.
apply (Permutation_Type_app_head l1a) in HP3b.
assert (IHP2 := Permutation_Type_trans HP1 HP3b).
apply (@Permutation_Type_cons _ B _ eq_refl) in IHP2.
rewrite app_comm_cons in IHP2.
apply IHpi1 in IHP1.
apply IHpi2 in IHP2.
symmetry in HP3.
apply (Permutation_Type_cons_app _ _ (tens A B)) in HP3.
eapply ex_r ; [ apply tens_r | simpl ; rewrite Hperm ; apply HP3 ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0 ; subst ; list_simpl in HP.
rewrite (app_assoc (map _ l4)) in HP.
rewrite <- map_app in HP.
remember (l4 ++ l6) as l0 ; clear Heql0.
apply Permutation_Type_app_app_inv in HP.
destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;
simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.
apply Permutation_Type_app_app_inv in HP4.
destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;
simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.
symmetry in HP1b.
apply Permutation_Type_map_inv in HP1b.
destruct HP1b as [la Heqa _].
decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.
symmetry in HP2b.
apply Permutation_Type_map_inv in HP2b.
destruct HP2b as [lb Heqb _].
decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.
apply (Permutation_Type_app_head l2a) in HP4b.
assert (IHP1 := Permutation_Type_trans HP2 HP4b).
apply (@Permutation_Type_cons _ bot _ eq_refl) in IHP1.
rewrite app_comm_cons in IHP1.
apply IHpi1 in IHP1.
rewrite <- app_nil_l in IHP1.
eapply bot_rev in IHP1 ; [ | apply Hgaxbot ].
list_simpl in IHP1.
apply (Permutation_Type_app_head l1a) in HP3b.
assert (IHP2 := Permutation_Type_trans HP1 HP3b).
apply (@Permutation_Type_cons _ bot _ eq_refl) in IHP2.
rewrite app_comm_cons in IHP2.
apply IHpi2 in IHP2.
rewrite <- app_nil_l in IHP2.
eapply bot_rev in IHP2 ; [ | apply Hgaxbot ].
list_simpl in IHP2.
assert (Permutation_Type (l2a ++ l1a) l') as HP' by perm_Type_solve.
eapply ex_r ; [ apply mix2_r | simpl ; rewrite Hperm ; apply HP' ]...
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ B _ eq_refl) in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite 2 app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply parr_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ eapply ex_r ; [ apply top_r
| simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply plus_r1 | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply plus_r2 | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
assert (HP2 := HP).
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi1 in HP.
apply (@Permutation_Type_cons _ B _ eq_refl) in HP2.
rewrite app_comm_cons in HP2.
apply IHpi2 in HP2.
eapply ex_r ; [ apply with_r
| simpl ; rewrite Hperm ; apply Permutation_Type_middle ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ symmetry in HP.
apply Permutation_Type_map_inv in HP.
destruct HP as [l' Heq HP].
decomp_map_Type Heq ;
simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; simpl in Heq5 ; subst ;
simpl in HP.
apply (Permutation_Type_map wn) in HP.
list_simpl in HP.
rewrite app_assoc in HP.
rewrite <- map_app in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
rewrite <- Heq2 in HP.
rewrite <- Heq5 in HP.
apply IHpi in HP.
eapply ex_r ; [ apply oc_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2.
inversion Heq2.
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ A _ eq_refl) in HP.
rewrite app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply de_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.
inversion Heq2 ; subst.
list_simpl in HP ; rewrite <- map_app in HP.
apply (@Permutation_Type_cons _ (tens bot bot) _ eq_refl) in HP.
assert (Permutation_Type (tens bot bot :: l)
(l' ++ map (fun _ : unit => tens bot bot) (tt :: l1')
++ map (fun _ : unit => wn (tens bot bot)) (l1 ++ l4)))
as HP' by (etransitivity ; [ apply HP | ] ; perm_Type_solve).
apply IHpi in HP'...
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply IHpi in HP.
eapply ex_r ; [ apply wk_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.
inversion Heq2 ; subst.
list_simpl in HP ; rewrite <- map_app in HP.
apply IHpi in HP...
- assert (HP' := HP).
symmetry in HP'.
apply Permutation_Type_vs_cons_inv in HP'.
destruct HP' as [[l'l l'r] Heq] ; simpl in Heq.
rewrite Heq in HP.
apply Permutation_Type_cons_app_inv in HP.
dichot_Type_elt_app_exec Heq ; subst.
+ rewrite app_assoc in HP.
apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.
apply (@Permutation_Type_cons _ (wn A) _ eq_refl) in HP.
rewrite 3 app_comm_cons in HP.
apply IHpi in HP.
eapply ex_r ; [ apply co_r | simpl ; rewrite Hperm ]...
+ dichot_Type_elt_app_exec Heq1 ; subst.
* decomp_map_Type Heq0.
inversion Heq0.
* decomp_map_Type Heq2 ; simpl in Heq1 ; simpl in Heq2 ; simpl in Heq3 ; subst ; simpl in HP.
inversion Heq2 ; subst.
list_simpl in HP ; rewrite <- map_app in HP.
apply (@Permutation_Type_cons _ (wn (tens bot bot)) _ eq_refl) in HP.
apply (@Permutation_Type_cons _ (wn (tens bot bot)) _ eq_refl) in HP.
assert (Permutation_Type (wn (tens bot bot) :: wn (tens bot bot) :: l)
(l' ++ map (fun _ : unit => tens bot bot) l1' ++
map (fun _ : unit => wn (tens bot bot)) (tt :: tt :: l1 ++ l4)))
as HP' by (etransitivity ; [ apply HP | perm_Type_solve ]).
apply IHpi in HP'...
- apply Permutation_Type_app_app_inv in HP.
destruct HP as [[[l1a l2a] [l3a l4a]] [[HP1 HP2] [HP3 HP4]]] ;
simpl in HP1 ; simpl in HP2 ; simpl in HP3 ; simpl in HP4.
apply Permutation_Type_app_app_inv in HP4.
destruct HP4 as [[[l1b l2b] [l3b l4b]] [[HP1b HP2b] [HP3b HP4b]]] ;
simpl in HP1b ; simpl in HP2b ; simpl in HP3b ; simpl in HP4b.
symmetry in HP1b.
apply Permutation_Type_map_inv in HP1b.
destruct HP1b as [la Heqa _].
decomp_map_Type Heqa ; simpl in Heqa1 ; simpl in Heqa2 ; subst.
symmetry in HP2b.
apply Permutation_Type_map_inv in HP2b.
destruct HP2b as [lb Heqb _].
decomp_map_Type Heqb ; simpl in Heqb1 ; simpl in Heqb2 ; subst.
apply (Permutation_Type_app_head l2a) in HP4b.
assert (IHP1 := Permutation_Type_trans HP2 HP4b).
apply (@Permutation_Type_cons _ (dual A) _ eq_refl) in IHP1.
rewrite app_comm_cons in IHP1.
apply (Permutation_Type_app_head l1a) in HP3b.
assert (IHP2 := Permutation_Type_trans HP1 HP3b).
apply (@Permutation_Type_cons _ A _ eq_refl) in IHP2.
rewrite app_comm_cons in IHP2.
apply IHpi1 in IHP1.
apply IHpi2 in IHP2.
symmetry in HP3.
eapply ex_r ; [ eapply cut_r | simpl ; rewrite Hperm ; apply HP3 ]...
- destruct l1' ; destruct l0' ; simpl in HP.
+ eapply ex_r ; [ apply gax_r | simpl ; rewrite Hperm ]...
+ exfalso.
apply Permutation_Type_vs_elt_inv in HP.
specialize (Hgax a).
destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.
apply Forall_elt in Hgax.
inversion Hgax.
+ exfalso.
apply Permutation_Type_vs_elt_inv in HP.
specialize (Hgax a).
destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.
apply Forall_elt in Hgax.
inversion Hgax.
+ exfalso.
apply Permutation_Type_vs_elt_inv in HP.
specialize (Hgax a).
destruct HP as [[l1 l2] Heq] ; rewrite Heq in Hgax.
apply Forall_elt in Hgax.
inversion Hgax.
Qed.
Lemma ll_to_mix2_cut {P} : forall l,
ll P (wn (tens bot bot) :: l) -> ll (mk_pfrag true P.(pgax) P.(pmix0) true P.(pperm)) l.
Proof with myeasy.
intros l pi.
eapply stronger_pfrag in pi.
- rewrite <- (app_nil_r l).
eapply cut_r ; [ | | apply pi]...
change nil with (map wn nil).
apply oc_r.
apply parr_r.
change (one :: one :: map wn nil) with ((one :: nil) ++ one :: nil).
eapply mix2_r...
+ apply one_r.
+ apply one_r.
- nsplit 5...
+ destruct pcut...
+ intros a.
exists a...
+ destruct pmix2...
Qed.
(** Provability in [ll_mix2] is equivalent to
provability of [ll] extended with the provability of [one :: one :: nil]
and to provability of [ll] extended with the provability of [parr (dual B) (dual A) :: tens A B :: nil]
for all [A] and [B] *)
Lemma mix2_to_ll_one_one {P} : pcut P = true -> pperm P = true -> forall bc b2 bp l,
ll (mk_pfrag bc P.(pgax) P.(pmix0) b2 bp) l ->
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => one :: one :: nil
end))) l.
Proof with myeeasy ; try (unfold PCperm_Type ; PCperm_Type_solve).
remember (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => one :: one :: nil
end))) as P'.
intros fc fp bc b2 bp l pi.
eapply stronger_pfrag in pi.
- eapply mix2_to_ll in pi...
assert (pcut P' = true) as fc' by (rewrite HeqP' ; simpl ; assumption).
apply (stronger_pfrag _ P') in pi.
+ assert (ll P' (parr one one :: map wn nil)) as pi'.
{ change (parr one one :: map wn nil) with ((parr one one :: nil) ++ nil).
eapply (@cut_r _ fc' bot).
- apply one_r.
- apply bot_r.
apply parr_r.
assert ({ b | one :: one :: nil = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now (exists (inr tt))).
rewrite Hgax.
apply gax_r. }
apply oc_r in pi'.
rewrite <- (app_nil_l l).
eapply (@cut_r _ fc' (oc (parr one one))) ; [ simpl ; apply pi | apply pi' ].
+ nsplit 5 ; rewrite HeqP'...
simpl ; intros a ; exists (inl a)...
- nsplit 5 ; intros ; simpl...
+ rewrite fc.
destruct bc...
+ exists a...
Qed.
Lemma ll_one_one_to_ll_tens_parr_one_one_cut {P} : (pcut P = true) ->
ll P (parr one one :: parr bot bot :: nil) -> ll P (one :: one :: nil).
Proof.
intros Hcut pi.
assert (ll P (dual (parr (parr one one) (parr bot bot)) :: one :: one :: nil)) as pi'.
{ simpl.
rewrite <- (app_nil_r _) ; rewrite <- app_comm_cons.
apply tens_r.
- rewrite <- (app_nil_r _) ; rewrite <- app_comm_cons.
apply tens_r ; apply one_r.
- rewrite <- (app_nil_l (one :: nil)).
rewrite (app_comm_cons _ _ one).
apply tens_r ; apply ax_exp. }
rewrite <- (app_nil_l _).
eapply cut_r ; [ assumption | apply pi' | ].
apply parr_r ; apply pi.
Qed.
Lemma ll_tens_parr_one_one_to_ll_tens_parr {P} : forall l,
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => parr one one :: parr bot bot :: nil
end))) l
-> ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil
end))) l.
Proof with myeeasy.
intros l pi.
remember (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => parr one one :: parr bot bot :: nil
end))) as P'.
apply (ax_gen P') ; (try now (rewrite HeqP' ; simpl ; reflexivity))...
clear - HeqP' ; simpl ; intros a.
revert a ; rewrite HeqP' ; intros a ; destruct a ; simpl.
- assert ({ b | projT2 (pgax P) p =
projT2 (pgax (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil
end)))) b })
as [b Hgax] by (now exists (inl p)).
rewrite Hgax.
apply gax_r.
- destruct u.
assert ({ b | parr one one :: parr bot bot :: nil =
projT2 (pgax (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil
end)))) b })
as [b Hgax] by (exists (inr (bot,bot)) ; reflexivity).
rewrite Hgax.
apply gax_r.
Qed.
Lemma ll_tens_parr_to_mix2 {P} : forall l,
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil
end))) l
-> ll (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) l.
Proof with myeeasy.
intros l pi.
remember (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) as P'.
apply (stronger_pfrag _
(axupd_pfrag P' (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr (A,B) => parr (dual B) (dual A) :: parr A B :: nil
end)))) in pi.
- eapply ax_gen...
clear - HeqP' ; simpl ; intros a.
destruct a.
+ assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now exists p).
rewrite Hgax.
apply gax_r.
+ destruct p as [A B].
apply parr_r.
apply (ex_r _ (parr A B :: (dual B :: nil) ++ (dual A) :: nil)) ;
[ |etransitivity ; [ apply PCperm_Type_last | reflexivity ] ].
apply parr_r.
eapply ex_r ;
[ | symmetry ; apply PCperm_Type_last ].
list_simpl.
rewrite <- (app_nil_l (dual A :: _)).
rewrite 2 app_comm_cons.
apply mix2_r.
* rewrite HeqP'...
* eapply ex_r ; [ | apply PCperm_Type_swap ].
apply ax_exp.
* apply ax_exp.
- rewrite HeqP' ; nsplit 5 ; simpl ; intros...
+ exists a...
+ destruct (pmix2 P)...
Qed.
Lemma ll_one_one_to_mix2 {P} : forall l,
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => one :: one :: nil
end))) l
-> ll (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) l.
Proof with myeeasy.
intros l pi.
remember (mk_pfrag P.(pcut) P.(pgax) P.(pmix0) true P.(pperm)) as P'.
apply (stronger_pfrag _
(axupd_pfrag P' (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr tt => one :: one :: nil
end)))) in pi.
- eapply ax_gen...
clear - HeqP' ; simpl ; intros a.
destruct a.
+ assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now exists p).
rewrite Hgax.
apply gax_r.
+ destruct u.
change (one :: one :: nil) with ((one :: nil) ++ one :: nil).
rewrite HeqP'.
apply mix2_r...
* apply one_r.
* apply one_r.
- rewrite HeqP' ; nsplit 5 ; simpl ; intros...
+ exists a...
+ destruct (pmix2 P)...
Qed.
(** [mix0] is not valid in [ll_mix2] *)
Lemma mix2_not_mix0 : ll_mix2 nil -> False.
Proof.
intros pi.
remember nil as l.
revert Heql ; induction pi ; intros Heql ; subst ; try inversion Heql.
- apply IHpi.
simpl in p ; apply Permutation_Type_sym in p.
apply Permutation_Type_nil in p.
assumption.
- apply app_eq_nil in Heql ; destruct Heql as [Heql Heql2].
apply app_eq_nil in Heql2 ; destruct Heql2 as [Heql2 _] ; subst.
destruct lw' ; inversion Heql2.
symmetry in p ; apply Permutation_Type_nil in p ; subst.
intuition.
- inversion f.
- apply IHpi2.
apply app_eq_nil in Heql.
apply Heql.
- inversion f.
- destruct a.
Qed.
(** ** Linear logic with both mix0 and mix2: [ll_mix02] (no axiom, commutative) *)
(** cut / axioms / mix0 / mix2 / permutation *)
Definition pfrag_mix02 := mk_pfrag false NoAxioms true true true.
(* cut axioms mix0 mix2 perm *)
Definition ll_mix02 := ll pfrag_mix02.
Lemma cut_mix02_r : forall A l1 l2,
ll_mix02 (dual A :: l1) -> ll_mix02 (A :: l2) -> ll_mix02 (l2 ++ l1).
Proof with myeeasy.
intros A l1 l2 pi1 pi2.
eapply cut_r_axfree...
intros a ; destruct a.
Qed.
Lemma cut_mix02_admissible :
forall l, ll (cutupd_pfrag pfrag_mix02 true) l -> ll_mix02 l.
Proof with myeeasy.
intros l pi.
induction pi ; try (now econstructor).
- eapply ex_r...
- eapply ex_wn_r...
- eapply cut_mix02_r...
Qed.
(** Provability in [ll_mix02] is equivalent to adding [wn (tens (wn one) (wn one))] in [ll] *)
Lemma mix02_to_ll {P} : pperm P = true -> forall b1 b2 bp l,
ll (mk_pfrag P.(pcut) P.(pgax) b1 b2 bp) l -> ll P (wn (tens (wn one) (wn one)) :: l).
Proof with myeeasy ; try PCperm_Type_solve.
intros fp b1 b2 bp l pi.
eapply (ext_wn_param _ P fp _ (tens (wn one) (wn one) :: nil)) in pi.
- eapply ex_r...
- intros Hcut...
- simpl ; intros a.
eapply ex_r ; [ | apply PCperm_Type_last ].
apply wk_r.
apply gax_r.
- intros Hpmix0 Hpmix0'.
apply de_r...
rewrite <- (app_nil_l nil).
apply tens_r ; apply de_r ; apply one_r.
- intros _ _ l1 l2 pi1 pi2.
apply (ex_r _ (wn (tens (wn one) (wn one)) :: l2 ++ l1))...
apply co_r.
apply co_r.
apply de_r.
eapply ex_r.
+ apply tens_r ; apply wk_r ; [ apply pi1 | apply pi2 ].
+ rewrite fp...
Qed.
Lemma ll_to_mix02_cut {P} : forall l,
ll P (wn (tens (wn one) (wn one)) :: l) -> ll (mk_pfrag true P.(pgax) true true P.(pperm)) l.
Proof with myeasy.
intros l pi.
eapply stronger_pfrag in pi.
- rewrite <- (app_nil_r l).
eapply cut_r ; [ | | apply pi]...
change nil with (map wn nil).
apply oc_r.
apply parr_r.
change (oc bot :: oc bot :: map wn nil) with ((oc bot :: map wn nil) ++ oc bot :: map wn nil).
eapply mix2_r...
+ apply oc_r.
apply bot_r.
apply mix0_r...
+ apply oc_r.
apply bot_r.
apply mix0_r...
- nsplit 5...
+ destruct pcut...
+ intros a.
exists a...
+ destruct pmix0...
+ destruct pmix2...
Qed.
(** Provability in [ll_mix02] is equivalent to adding other stuff in [ll] *)
Lemma mix02_to_ll' {P} : pperm P = true -> forall b0 b2 bp l,
ll (mk_pfrag P.(pcut) P.(pgax) b0 b2 bp) l -> ll P (wn one :: wn (tens bot bot) :: l).
Proof with myeasy.
intros Hperm b0 b2 bp l pi.
eapply mix0_to_ll...
eapply mix2_to_ll...
apply pi.
Qed.
Lemma ll_to_mix02'_axat {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->
pperm P = true -> forall l,
ll P (wn one :: wn (tens bot bot) :: l) -> ll (mix2add_pfrag (mix0add_pfrag P)) l.
Proof with myeasy.
intros Hgax Hperm l pi.
apply ll_to_mix2_axat...
apply ll_to_mix0_axat...
Qed.
Lemma mix02_to_ll'' {P} : pperm P = true -> forall b0 b2 bp l,
ll (mk_pfrag P.(pcut) P.(pgax) b0 b2 bp) l -> ll P (wn one :: wn (tens (wn one) bot) :: l).
Proof with myeeasy ; try PCperm_Type_solve.
intros Hperm b0 b2 bp l pi.
eapply (ext_wn_param _ _ _ _ (one :: tens (wn one) bot :: nil)) in pi.
- eapply ex_r...
- intros Hcut...
- simpl ; intros a.
eapply ex_r ; [ | apply PCperm_Type_app_comm ] ; list_simpl.
apply wk_r.
apply wk_r.
apply gax_r.
- intros Hpmix0 Hpmix0'.
apply de_r...
eapply ex_r ; [ | apply PCperm_Type_swap ].
apply wk_r.
apply one_r.
- intros _ _ l1 l2 pi1 pi2.
apply (ex_r _ (wn (tens (wn one) bot) :: (wn one :: l2) ++ l1)) ; [ | rewrite Hperm ]...
apply co_r.
apply co_r.
apply de_r.
apply (ex_r _ (tens (wn one) bot :: (wn (tens (wn one) bot) :: wn one :: l2)
++ (wn (tens (wn one) bot) :: l1))) ;
[ | rewrite Hperm ]...
apply tens_r.
+ eapply ex_r ; [ apply pi1 | ]...
+ apply bot_r ; eapply ex_r ; [ apply pi2 | rewrite Hperm ]...
Unshelve. assumption.
Qed.
(* Hgax_cut is here only to allow the use of cut_admissible
the more general result without Hgax_cut should be provable by induction as for [ll_to_mix2] *)
Lemma ll_to_mix02''_axcut {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->
(forall a b x l1 l2 l3 l4,
projT2 (pgax P) a = (l1 ++ dual x :: l2) -> projT2 (pgax P) b = (l3 ++ x :: l4) ->
{ c | projT2 (pgax P) c = l3 ++ l2 ++ l1 ++ l4 }) ->
pperm P = true -> forall l,
ll P (wn one :: wn (tens (wn one) bot) :: l) -> ll (mix2add_pfrag (mix0add_pfrag P)) l.
Proof with myeasy.
intros Hgax_at Hgax_cut Hperm l pi.
apply (stronger_pfrag (cutrm_pfrag (cutupd_pfrag (mix2add_pfrag (mix0add_pfrag P)) true))).
{ nsplit 5...
intros a ; exists a... }
eapply cut_admissible...
eapply stronger_pfrag in pi.
- rewrite <- (app_nil_r l).
eapply (cut_r _ (wn (tens (wn one) bot))) ; simpl.
+ change nil with (map wn nil).
apply oc_r.
apply parr_r.
change (one :: oc bot :: map wn nil) with ((one :: nil) ++ oc bot :: map wn nil).
eapply mix2_r...
* apply oc_r.
apply bot_r.
apply mix0_r...
* apply one_r.
+ rewrite <- app_nil_r.
eapply cut_r ; [ | | apply pi ] ; simpl...
change nil with (map wn nil).
apply oc_r.
apply bot_r.
apply mix0_r...
- etransitivity ; [ apply cutupd_pfrag_true| ].
nsplit 5...
+ intros a ; exists a...
+ apply leb_true.
+ apply leb_true.
Unshelve. reflexivity.
Qed.
(* Hgax_cut is here only to allow the use of cut_admissible
the more general result without Hgax_cut should be provable by induction as for [ll_to_mix2] *)
Lemma ll_to_mix02'''_axcut {P} : (forall a, Forall atomic (projT2 (pgax P) a)) ->
(forall a b x l1 l2 l3 l4,
projT2 (pgax P) a = (l1 ++ dual x :: l2) -> projT2 (pgax P) b = (l3 ++ x :: l4) ->
{ c | projT2 (pgax P) c = l3 ++ l2 ++ l1 ++ l4 }) ->
pperm P = true -> forall l (l0 : list unit),
ll P (wn one :: map (fun _ => wn (tens (wn one) bot)) l0 ++ l) ->
ll (mix2add_pfrag (mix0add_pfrag P)) l.
Proof with try assumption.
intros Hgax_at Hgax_cut Hperm l l0 pi.
apply ll_to_mix02''_axcut...
revert l pi ; induction l0 ; intros l pi.
- cons2app.
eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ].
simpl ; apply wk_r.
eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ]...
- cons2app.
eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ].
simpl ; apply co_r.
rewrite 2 app_comm_cons.
eapply ex_r ; [ | rewrite Hperm ; apply Permutation_Type_app_comm ].
list_simpl ; apply IHl0.
list_simpl in pi.
eapply ex_r ; [ apply pi | rewrite Hperm ; PCperm_Type_solve ].
Qed.
(** Provability in [ll_mix02] is equivalent to provability of [ll]
extended with the provability of both [bot :: bot :: nil] and [one :: one :: nil] *)
Lemma mix02_to_ll_one_eq_bot {P} : pcut P = true -> pperm P = true -> forall bc b0 b2 bp l,
ll (mk_pfrag bc P.(pgax) b0 b2 bp) l ->
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr true => one :: one :: nil
| inr false => bot :: bot :: nil
end))) l.
Proof with myeeasy ; try (unfold PCperm_Type ; PCperm_Type_solve).
remember (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr true => one :: one :: nil
| inr false => bot :: bot :: nil
end))) as P'.
intros fc fp bc b0 b2 bp l pi.
eapply stronger_pfrag in pi.
- eapply mix02_to_ll in pi...
assert (pcut P' = true) as fc' by (rewrite HeqP' ; simpl ; assumption).
apply (stronger_pfrag _ P') in pi.
+ assert (ll P' (parr (oc bot) (oc bot) :: map wn nil)) as pi'.
{ apply parr_r.
change (oc bot :: oc bot :: map wn nil)
with ((oc bot :: nil) ++ oc bot :: map wn nil).
eapply (@cut_r _ fc' one).
- apply bot_r.
apply oc_r.
change (bot :: map wn nil) with ((bot :: nil) ++ nil).
eapply (@cut_r _ fc' bot).
+ apply one_r.
+ assert ({ b | bot :: bot :: nil = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now (exists (inr false))).
rewrite Hgax.
apply gax_r.
- change (one :: oc bot :: nil)
with ((one :: nil) ++ oc bot :: map wn nil).
eapply (@cut_r _ fc' one).
+ apply bot_r.
apply oc_r.
change (bot :: map wn nil) with ((bot :: nil) ++ nil).
eapply (@cut_r _ fc' bot).
* apply one_r.
* assert ({ b | bot :: bot :: nil = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now (exists (inr false))).
rewrite Hgax.
apply gax_r.
+ assert ({ b | one :: one :: nil = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now (exists (inr true))).
rewrite Hgax.
apply gax_r. }
apply oc_r in pi'.
rewrite <- (app_nil_l l).
eapply (@cut_r _ fc' (oc (parr (oc bot) (oc bot)))) ; [ simpl ; apply pi | apply pi' ].
+ nsplit 5 ; rewrite HeqP'...
simpl ; intros a ; exists (inl a)...
- nsplit 5 ; intros ; simpl...
+ rewrite fc.
destruct bc...
+ exists a...
Qed.
Lemma ll_one_eq_bot_to_mix02 {P} : forall l,
ll (axupd_pfrag P (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr true => one :: one :: nil
| inr false => bot :: bot :: nil
end))) l
-> ll (mk_pfrag P.(pcut) P.(pgax) true true P.(pperm)) l.
Proof with myeeasy.
intros l pi.
remember (mk_pfrag P.(pcut) P.(pgax) true true P.(pperm)) as P'.
apply (stronger_pfrag _
(axupd_pfrag P' (existT (fun x => x -> list formula) _
(fun a => match a with
| inl x => projT2 (pgax P) x
| inr true => one :: one :: nil
| inr false => bot :: bot :: nil
end)))) in pi.
- eapply ax_gen...
clear - HeqP' ; simpl ; intros a.
destruct a.
+ assert ({ b | projT2 (pgax P) p = projT2 (pgax P') b })
as [b Hgax] by (rewrite HeqP' ; now exists p).
rewrite Hgax.
apply gax_r.
+ destruct b.
* change (one :: one :: nil) with ((one :: nil) ++ one :: nil).
rewrite HeqP'.
apply mix2_r...
-- apply one_r.
-- apply one_r.
* apply bot_r.
apply bot_r.
rewrite HeqP'.
apply mix0_r...
- rewrite HeqP' ; nsplit 5 ; simpl ; intros...
+ exists a...
+ destruct (pmix0 P)...
+ destruct (pmix2 P)...
Qed.
(* llR *)
(** ** Linear logic extended with [R] = [bot]: [llR] *)
(** cut / axioms / mix0 / mix2 / permutation *)
Definition pfrag_llR R :=
mk_pfrag true (existT (fun x => x -> list formula) _
(fun a => match a with
| true => dual R :: nil
| false => R :: one :: nil
end))
false false true.
(* cut axioms
mix0 mix2 perm *)
Definition llR R := ll (pfrag_llR R).
Lemma llR1_R2 : forall R1 R2,
llR R2 (dual R1 :: R2 :: nil) -> llR R2 (dual R2 :: R1 :: nil) ->
forall l, llR R1 l-> llR R2 l.
Proof with myeeasy.
intros R1 R2 HR1 HR2 l Hll.
induction Hll ; try (now constructor).
- eapply ex_r...
- eapply ex_wn_r...
- eapply cut_r...
- destruct a.
+ rewrite <- (app_nil_l _).
apply (@cut_r (pfrag_llR R2) eq_refl (dual R2)).
* rewrite bidual.
eapply ex_r.
apply HR1.
apply PCperm_Type_swap.
* assert ({ b | dual R2 :: nil = projT2 (pgax (pfrag_llR R2)) b })
as [b Hgax] by (now exists true).
rewrite Hgax.
apply gax_r.
+ eapply (@cut_r (pfrag_llR R2) eq_refl R2) in HR2.
* eapply ex_r ; [ apply HR2 | ].
unfold PCperm_Type.
simpl.
apply Permutation_Type_sym.
apply Permutation_Type_cons_app.
rewrite app_nil_r.
apply Permutation_Type_refl.
* assert ({ b | R2 :: one :: nil = projT2 (pgax (pfrag_llR R2)) b })
as [b Hgax] by (now exists false).
rewrite Hgax.
apply gax_r.
Qed.
Lemma ll_to_llR : forall R l, ll_ll l -> llR R l.
Proof with myeeasy.
intros R l pi.
induction pi ; try (now econstructor).
- eapply ex_r...
- eapply ex_wn_r...
Qed.
Lemma subs_llR : forall R C x l, llR R l -> llR (subs C x R) (map (subs C x) l).
Proof with myeeasy.
intros R C x l pi.
apply (subs_ll C x) in pi.
eapply stronger_pfrag in pi...
nsplit 5...
simpl ; intros a.
destruct a ; simpl.
- exists true.
rewrite subs_dual...
- exists false...
Qed.
Lemma llR_to_ll : forall R l, llR R l-> ll_ll (l ++ wn R :: wn (tens (dual R) bot) :: nil).
Proof with myeasy.
intros R l pi.
apply cut_ll_admissible.
replace (wn R :: wn (tens (dual R) bot) :: nil) with (map wn (map dual (dual R :: parr one R :: nil)))
by (simpl ; rewrite bidual ; reflexivity).
apply deduction_list...
eapply ax_gen ; [ | | | | | apply pi ]...
simpl ; intros a.
destruct a ; simpl.
- assert ({ b | dual R :: nil = projT2 (pgax (axupd_pfrag (cutupd_pfrag pfrag_ll true)
(existT (fun x => x -> list formula) (sum _ {k : nat | k < 2})
(fun a => match a with
| inl x => Empty_fun x
| inr x => match proj1_sig x with
| 0 => dual R
| 1 => parr one R
| 2 => one
| S (S (S _)) => one
end :: nil
end)))) b })
as [b Hgax] by (now exists (inr (exist _ 0 (le_n_S _ _ (le_S _ _ (le_n 0)))))).
rewrite Hgax.
apply gax_r.
- rewrite <- (app_nil_r nil).
rewrite_all app_comm_cons.
eapply (cut_r _ (dual (parr one R))).
+ rewrite bidual.
assert ({ b | parr one R :: nil = projT2 (pgax (axupd_pfrag (cutupd_pfrag pfrag_ll true)
(existT (fun x => x -> list formula) (sum _ {k : nat | k < 2})
(fun a => match a with
| inl x => Empty_fun x
| inr x => match proj1_sig x with
| 0 => dual R
| 1 => parr one R
| 2 => one
| S (S (S _)) => one
end :: nil
end)))) b })
as [b Hgax] by (now exists (inr (exist _ 1 (le_n 2)))).
erewrite Hgax.
apply gax_r.
+ apply (ex_r _ (tens (dual R) bot :: (one :: nil) ++ R :: nil)) ; [ | PCperm_Type_solve ].
apply tens_r.
* eapply ex_r ; [ | apply PCperm_Type_swap ].
eapply stronger_pfrag ; [ | apply ax_exp ].
nsplit 5...
simpl ; intros a.
destruct a as [a | a].
-- destruct a.
-- destruct a as [n Hlt].
destruct n ; simpl.
++ exists (inr (exist _ 0 Hlt))...
++ destruct n ; simpl.
** exists (inr (exist _ 1 Hlt))...
** exfalso.
inversion Hlt ; subst.
inversion H0 ; subst.
inversion H1.
* apply bot_r.
apply one_r.
Unshelve. reflexivity.
Qed.
Lemma llwnR_to_ll : forall R l, llR (wn R) l -> ll_ll (l ++ wn R :: nil).
Proof with myeeasy.
intros R l pi.
apply llR_to_ll in pi.
eapply (ex_r _ _ (wn (tens (dual (wn R)) bot) :: l ++ wn (wn R) :: nil)) in pi ;
[ | PCperm_Type_solve ].
eapply (cut_ll_r _ nil) in pi.
- eapply (cut_ll_r (wn (wn R))).
+ simpl.
change (wn R :: nil) with (map wn (R :: nil)).
apply oc_r ; simpl.
replace (wn R) with (dual (oc (dual R))) by (simpl ; rewrite bidual ; reflexivity).
apply ax_exp.
+ eapply ex_r ; [ apply pi | PCperm_Type_solve ].
- simpl ; rewrite bidual.
change nil with (map wn nil).
apply oc_r.
apply parr_r.
eapply ex_r ; [ apply wk_r ; apply one_r | PCperm_Type_solve ].
Qed.
Lemma ll_wn_wn_to_llR : forall R l, ll_ll (l ++ wn R :: wn (tens (dual R) bot) :: nil) -> llR R l.
Proof with myeasy.
intros R l pi.
apply (ll_to_llR R) in pi.
rewrite <- (app_nil_l l).
eapply (cut_r _ (oc (dual R))).
- rewrite <- (app_nil_l (dual _ :: l)).
eapply (cut_r _ (oc (parr one R))).
+ simpl ; rewrite bidual ; eapply ex_r ; [apply pi | PCperm_Type_solve ].
+ change nil with (map wn nil).
apply oc_r.
apply parr_r.
apply (ex_r _ (R :: one :: nil)).
* assert ({ b | R :: one :: nil = projT2 (pgax (pfrag_llR R)) b })
as [b Hgax] by (now exists false).
rewrite Hgax.
apply gax_r.
* PCperm_Type_solve.
- change nil with (map wn nil).
apply oc_r.
assert ({ b | dual R :: map wn nil = projT2 (pgax (pfrag_llR R)) b })
as [b Hgax] by (now exists true).
rewrite Hgax.
apply gax_r.
Unshelve. all : reflexivity.
Qed.
Lemma ll_wn_to_llwnR : forall R l, ll_ll (l ++ wn R :: nil) -> llR (wn R) l.
Proof with myeasy.
intros R l pi.
eapply ll_wn_wn_to_llR.
eapply (ex_r _ (wn (tens (dual (wn R)) bot) :: wn (wn R) :: l)) ;
[ | PCperm_Type_solve ].
apply wk_r.
apply de_r.
eapply ex_r ; [ apply pi | PCperm_Type_solve ].
Qed.
|
# ATW relaxation notebook
```python
import numpy as np
import matplotlib.pyplot as plt
import warnings
from copy import deepcopy
# Global constants
f = 1e-4 # [s-1]
g = 9.81 # [m s-2]
%matplotlib inline
plt.rcParams['font.size'] = 14
warnings.simplefilter('ignore')
```
### Analytical solution
Start with the linearized, steady state shallow water equations with linear friction and longshore windstress. Assume cross-shore geostrophic balance.
\begin{align}
f\mathbf{k}\times\mathbf{u} & = -g\nabla\eta + \frac{1}{h}\left(\tau_y - \mu v\right)\hat{\jmath} \tag{1a} \\
0 & = \nabla\cdot h\mathbf{u} \tag{1b}
\end{align}
Taking the curl of (1a) and solving for $\eta$ gives the the Arrested Topography Wave (ATW) of Csanady (1978 *JPO*). I have oriented the problem to $x\to-\infty$ offshore such that $\frac{\partial h}{\partial x} = -s$.
$$\frac{\partial^2\eta}{\partial x^2} - \frac{1}{\kappa}\frac{\partial\eta}{\partial y} = 0, \hspace{0.5cm} \frac{1}{\kappa} = \frac{fs}{\mu}\tag{2}$$
The coastal boundary condition (obtained from 1a) requires $u \to 0$ and $h \to 0$
$$\frac{\partial\eta}{\partial x}(0, y) = \frac{\tau_yf}{\mu g} = q_0 \tag{3}$$
Equation (2) is analogous to a constant heat flux boundary condition. The solution is given by Carslaw and Jaeger 1959 (p. 112)
$$\eta(x, y) = \frac{\kappa q_0y}{L} + q_0L\left\{\frac{3(x + L)^2 - L^2}{6L^2} - \frac{2}{\pi^2}\sum_{n=1}^\infty\frac{(-1)^n}{n^2}\exp\left(\frac{-\kappa n^2\pi^2y}{L^2}\right)\cos\left(\frac{n\pi(x + L)}{L}\right)\right\} \tag{4}$$
which, as $y\to\infty$, reduces to
$$\eta(x, y) = \frac{\kappa q_0y}{L} + q_0L\frac{3(x + L)^2 - L^2}{6L^2} \tag{5}$$
Calculate $\eta$ according to equation (5)
```python
def calc_eta(x, y, L, kappa, q_0):
"""Calculate eta according to equation 5
"""
return kappa * q_0 * y / L + q_0 * L * (3 * (x + L)**2 - L**2) / (6 * L**2)
```
Find $\eta$ given problem parameters
```python
# Constants
L = 1e3 # Slope width [m]
tau_y = -1e-4 # Kinematic wind stress [m2 s-2]
mu = 1e-2 # Linear friction coefficient [s-1]
s = 1 # Shelf slope [dimensionless]
# Terms (heat equation analogues)
kappa = mu / (f * s) # 'Diffusivity' of eta
q_0 = tau_y * f / (mu * g) # 'Flux' of eta through boundary
# Coordinates
dL = L * 1e-2
xi = np.arange(-L, 0, dL)
yi = np.arange(0, L, dL)
x, y = np.meshgrid(xi, yi)
# Solution
eta = calc_eta(x, y, L, kappa, q_0)
```
Plot $\eta$ solution
```python
# Plot eta
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.contour(xi/L, yi/L, eta, colors='k')
for tick in np.arange(0, 1, 0.015):
ax.plot([0, 0.005], [tick, tick+0.005], 'k-', clip_on=False)
ax.set_xlabel('$\longleftarrow$ $X/L$')
ax.set_ylabel('$\longleftarrow$ $Y/L$')
ax.xaxis.set_ticks([-1, 0])
ax.yaxis.set_ticks([0, 1])
ax.xaxis.set_ticklabels(['$-L$', 0])
ax.yaxis.set_ticklabels([0, '$L$'])
ax.tick_params(direction='out', pad=8)
ax.set_xlim([0, -1])
ax.set_ylim([1, 0])
ax.text(0.02, 0.05, 'Low $\eta$', transform=ax.transAxes)
ax.text(0.85, 0.9, 'High $\eta$', transform=ax.transAxes)
ax.text(0.03, 0.46, '$\\tau_y$', transform=ax.transAxes)
ax.arrow(0.04, 0.5, 0, 0.1, transform=ax.transAxes, head_width=0.01, facecolor='k')
ax.set_title('Cross-shelf bottom slope (ATW) solution')
plt.show()
```
### Relaxation solution
Three schemes:
Centered difference
$$r_{i, j}^{(n)} = \frac{\eta_{i, j+1}^{(n)} - \eta_{i, j-1}^{(n)}}{2\Delta y} - \kappa\frac{\eta_{i+1, j}^{(n)} - 2\eta_{i, j}^{(n)} + \eta_{i-1, j}^{(n)}}{\Delta x^2}$$
$$\eta_{i, j}^{(n+1)} = \eta_{i, j}^{(n)} - \frac{\mu\Delta x^2}{2\kappa}r_{i, j}^{(n)}$$
Upstream Euler
$$r_{i, j}^{(n)} = \frac{\eta_{i, j+1}^{(n)} - \eta_{i, j}^{(n)}}{\Delta y} - \kappa\frac{\eta_{i+1, j}^{(n)} - 2\eta_{i, j}^{(n)} + \eta_{i-1, j}^{(n)}}{\Delta x^2}$$
$$\eta_{i, j}^{(n+1)} = \eta_{i, j}^{(n)} - \frac{\mu}{\left(\frac{2\kappa}{\Delta x} - 1\right)}r_{i, j}^{(n)}$$
Downstream Euler
$$r_{i, j}^{(n)} = \frac{\eta_{i, j}^{(n)} - \eta_{i, j-1}^{(n)}}{\Delta y} - \kappa\frac{\eta_{i+1, j}^{(n)} - 2\eta_{i, j}^{(n)} + \eta_{i-1, j}^{(n)}}{\Delta x^2}$$
$$\eta_{i, j}^{(n+1)} = \eta_{i, j}^{(n)} - \frac{\mu}{\left(\frac{2\kappa}{\Delta x} + 1\right)}r_{i, j}^{(n)}$$
Only the downstream Euler is stable.
Find $\eta$ by relaxation
```python
# Find phi by relaxation
# Parameters
M = eta.shape[0] # matrix size
mu = 1 # SOR convergence parameter
TOL = 1e-4 # Convergence tolerance
N = 100000 # Max iterations
Ci = int(M / 2) # Cape i position
Cj = int(2 * M / 3) # Cape j position
# Allocate arrays
eta_next = deepcopy(eta)
res = np.zeros(eta.shape)
# Reset eta (equation 37)
eta = kappa * q_0 * y / L + q_0 * L * (3 * (x + L)**2 - L**2) / (6 * L**2)
# Relaxation loop
for n in range(N):
for i in range(1, M-1): # Longshore step
for j in range(2, M-1): # Cross-shore step
#Downstream Euler
res[i, j] = (eta[i, j] - eta[i-1, j]) / dL - kappa * (eta[i, j+1] - 2 * eta[i, j] + eta[i, j-1]) / dL**2
eta_next[i, j] = eta[i, j] - mu / (2 * kappa / dL + 1) * res[i, j]
eta = eta_next
eta[Ci, Cj:] = eta[Ci, -1] # Reset eta along cape equal to eta at coast
#if dL**2 * np.max(abs(res)) / np.max(abs(eta)) < TOL:
# break
```
```python
# Plot results
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.contour(xi/L, yi/L, eta, colors='k')
ax.set_xlim([0, -1])
ax.set_ylim([1, 0])
```
```python
```
|
{- Copyright © 1992–2002 The University of Glasgow
Copyright © 2015 Benjamin Barenblat
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. -}
module B.Prelude.Monad where
import Category.Monad
import Data.List
import Data.Maybe
open import Function using (const)
open Category.Monad
using (RawMonad)
public
open Category.Monad.RawMonad ⦃...⦄
using (_>>=_; _>>_; return)
public
instance
Monad-List : ∀ {ℓ} → RawMonad (Data.List.List {ℓ})
Monad-List = Data.List.monad
Monad-Maybe : ∀ {ℓ} → RawMonad (Data.Maybe.Maybe {ℓ})
Monad-Maybe = Data.Maybe.monad
Monad-Function : ∀ {ℓ} {r : Set ℓ} → RawMonad (λ s → (r → s))
Monad-Function {r} = record { return = const {r}
; _>>=_ = λ f k → λ r → k (f r) r }
|
lemma (in function_ring_on) one: assumes U: "open U" and t0: "t0 \<in> S" "t0 \<in> U" and t1: "t1 \<in> S-U" shows "\<exists>V. open V \<and> t0 \<in> V \<and> S \<inter> V \<subseteq> U \<and> (\<forall>e>0. \<exists>f \<in> R. f ` S \<subseteq> {0..1} \<and> (\<forall>t \<in> S \<inter> V. f t < e) \<and> (\<forall>t \<in> S - U. f t > 1 - e))" |
import sli.sli model_checking.mc_bridge
namespace rmd_bridge
universe u
/-!
**S** the type of a specification (the model that is interpreted by the STR)
- if it is a string, then we have an inject function String → STR C A that will parse the string and instantiate the STR
- if it is an program AST, the we have an inject function AST → STR C A that will instantiate the STR with the program AST
- more generaly it can be any object type S for which we have an inject function S → STR C A
-/
variables (S C A E R V α : Type)
open sli
open sli.toTR
open model_checking
/-!
# Debug semantics
-/
mutual inductive TraceEntry , DebugAction
with TraceEntry: Type
| root (c: C) (a: DebugAction)
| child (c: C) (a: DebugAction) (parent : TraceEntry)
with DebugAction : Type
| init
| step : A → DebugAction
| select : C → DebugAction
| jump : TraceEntry → DebugAction
| run_to_breakpoint : DebugAction
structure DebugConfig :=
(current : option (TraceEntry C A))
(history : set (TraceEntry C A))
(options : option(DebugAction C A × set C))
/-!
**BE** breakpoint expression type, which can be mapped to the semantics and the emptiness checking algorithm needed
**Cp** configuration product, a configuration type, which in general is different from C.
In practice it is the tuple (C, C₂), where C₂ is the configuration type needed by the breakpoint semantics
-/
def Finder (BE: Type)
:=
STR C A → set C → BE → R → list C
def ote2c {C A : Type} : option (TraceEntry C A) → option C
| none := none
| (some (TraceEntry.root c _)) := c
| (some (TraceEntry.child c _ _)) := c
def rmdInitial
(o : STR C A) : set (DebugConfig C A) :=
{ { current := none, history := ∅, options := some (DebugAction.init, o.initial) } }
open DebugAction
def rmdActions
(o : STR C A) : DebugConfig C A → set (DebugAction C A)
| ⟨ current, history, options ⟩ :=
let
oa := { x : DebugAction C A | ∀ c, (options = none) → (ote2c current) = some c → ∀ a ∈ (o.actions c), x = step a },
sa := { x : DebugAction C A | match options with | some (_, configs) := ∀ c ∈ configs, x = select c | none := false end },
ja := { x : DebugAction C A | ∀ te ∈ history, x = jump te },
rtb := { x : DebugAction C A | match current with | some te := x = run_to_breakpoint | none := false end }
in oa ∪ sa ∪ ja ∪ rtb
def same_configuration [decidable_eq C]: TraceEntry C A → C → bool
| (TraceEntry.root c₁ _ ) c₂ := c₁ = c₂
| (TraceEntry.child c₁ _ _) c₂ := c₁ = c₂
/-!
Attention:
- to the order of configurations in the counter example (start .. end) vs (end .. start).
Here we suppose **(start .. end)**
- does the counter exemple contain the start configuration ?
The same_configuration check removes the consecutive duplicates
-/
def trace2history {C A : Type} [decidable_eq C] : TraceEntry C A → DebugAction C A → list C → set (TraceEntry C A) → TraceEntry C A × set (TraceEntry C A)
| te da [] history := (te, history)
| te da (head::tail) history :=
let
te' := if (same_configuration C A te head) then te else (TraceEntry.child head da te),
h := history ∪ { te' }
in
trace2history te' da tail h
def te2c {C A : Type} : TraceEntry C A → C
| (TraceEntry.root c _) := c
| (TraceEntry.child c _ _):= c
def rmdExecute {BE: Type}
[decidable_eq C]
(o : STR C A)
(finder : Finder C A R BE) (breakpoint : BE) (reduction : R)
:
DebugAction C A → DebugConfig C A → set (DebugConfig C A)
| (init) _ := ∅ -- cannot get here
| (step a) ⟨ (some (TraceEntry.root c da)), history, _ ⟩ := { ⟨ (TraceEntry.root c da), history, some (step a, o.execute a c) ⟩ }
| (step a) ⟨ (some (TraceEntry.child c da p)), history, _⟩ := { ⟨ (TraceEntry.child c da p), history, some (step a, o.execute a c) ⟩ }
| (step a) ⟨ _, _, _ ⟩ := ∅ -- cannot get here due to debugActions which produce steps only of current=some c
| (select c) ⟨ none, history, some (da, _)⟩ := (let te := (TraceEntry.root c da) in { ⟨ te , { te } ∪ history, none ⟩ })
| (select c) ⟨ some te, history, some(da, _)⟩ := (let te₁ := (TraceEntry.child c da te) in { ⟨ te₁, { te₁ } ∪ history, none ⟩ })
| (select c) ⟨ _, _, _ ⟩ := ∅ --cannot get here
| (jump te) ⟨ _, history, _⟩ := { ⟨ some te, history, none ⟩ }
| (run_to_breakpoint) ⟨ some te, history, opts ⟩ :=
let
trace := finder o { (te2c te) } breakpoint reduction,
patch := trace2history te run_to_breakpoint trace ∅
in
match patch with
| (te, ch) := { ⟨ some te, history ∪ ch, none ⟩ }
end
| (run_to_breakpoint) ⟨ _, _, _ ⟩ := ∅ --cannot get here
def ReducedMultiverseDebuggerBridge {BE: Type}
[decidable_eq C]
(o : STR C A)
(finder : Finder C A R BE)
(breakpoint : BE)
(reduction : R)
: STR (DebugConfig C A) (DebugAction C A) :=
{
initial := rmdInitial C A o,
actions := λ dc, rmdActions C A o dc,
execute := λ da dc, rmdExecute C A R o finder breakpoint reduction da dc
}
/-!
# Replace the initial states of a STR, to make it start somewhere else
-/
def ReplaceInitial (o : STR C A) (initial : set C) : STR C A :=
{
initial := initial,
actions := o.actions,
execute := o.execute,
}
def ReducedMultiverseDebugger {BE: Type}
[decidable_eq C]
(finder : Finder C A R BE)
(inject: S → STR C A)
(specification: S)
(breakpoint : BE)
(reduction : R)
: STR (DebugConfig C A) (DebugAction C A) :=
ReducedMultiverseDebuggerBridge C A R (inject specification)
finder breakpoint reduction
end rmd_bridge |
[GOAL]
A : Type u_1
B : Type u_2
i : SetLike A B
p q : A
⊢ p < q ↔ p ≤ q ∧ ∃ x, x ∈ q ∧ ¬x ∈ p
[PROOFSTEP]
rw [lt_iff_le_not_le, not_le_iff_exists]
|
module LibVulkan
import Libdl
paths = String[]
const libvulkan = Libdl.find_library(["libvulkan", "vulkan", "vulkan-1", "libvulkan.so.1"], paths)
@assert libvulkan != ""
using CEnum
const Ctm = Base.Libc.TmStruct
const Ctime_t = UInt
const Cclock_t = UInt
export Ctm, Ctime_t, Cclock_t
include(joinpath(@__DIR__, "..", "gen", "vk_common.jl"))
include(joinpath(@__DIR__, "..", "gen", "vk_api.jl"))
# export everything
foreach(names(@__MODULE__, all=true)) do s
if startswith(string(s), "VK_") || startswith(string(s), "vk") || startswith(string(s), "VULKAN")
@eval export $s
end
end
end # module
|
[STATEMENT]
lemma compact_space:
"compact_space X \<longleftrightarrow>
(\<forall>\<U>. (\<forall>U \<in> \<U>. openin X U) \<and> \<Union>\<U> = topspace X
\<longrightarrow> (\<exists>\<F>. finite \<F> \<and> \<F> \<subseteq> \<U> \<and> \<Union>\<F> = topspace X))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. compact_space X = (\<forall>\<U>. (\<forall>U\<in>\<U>. openin X U) \<and> \<Union> \<U> = topspace X \<longrightarrow> (\<exists>\<F>. finite \<F> \<and> \<F> \<subseteq> \<U> \<and> \<Union> \<F> = topspace X))
[PROOF STEP]
unfolding compact_space_alt
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<forall>\<U>. Ball \<U> (openin X) \<and> topspace X \<subseteq> \<Union> \<U> \<longrightarrow> (\<exists>\<F>. finite \<F> \<and> \<F> \<subseteq> \<U> \<and> topspace X \<subseteq> \<Union> \<F>)) = (\<forall>\<U>. (\<forall>U\<in>\<U>. openin X U) \<and> \<Union> \<U> = topspace X \<longrightarrow> (\<exists>\<F>. finite \<F> \<and> \<F> \<subseteq> \<U> \<and> \<Union> \<F> = topspace X))
[PROOF STEP]
using openin_subset
[PROOF STATE]
proof (prove)
using this:
openin ?U ?S \<Longrightarrow> ?S \<subseteq> topspace ?U
goal (1 subgoal):
1. (\<forall>\<U>. Ball \<U> (openin X) \<and> topspace X \<subseteq> \<Union> \<U> \<longrightarrow> (\<exists>\<F>. finite \<F> \<and> \<F> \<subseteq> \<U> \<and> topspace X \<subseteq> \<Union> \<F>)) = (\<forall>\<U>. (\<forall>U\<in>\<U>. openin X U) \<and> \<Union> \<U> = topspace X \<longrightarrow> (\<exists>\<F>. finite \<F> \<and> \<F> \<subseteq> \<U> \<and> \<Union> \<F> = topspace X))
[PROOF STEP]
by fastforce |
From Categories Require Import Essentials.Notations.
From Categories Require Import Essentials.Types.
From Categories Require Import Essentials.Facts_Tactics.
From Categories Require Import Category.Main.
From Categories Require Import Functor.Main.
From Categories Require Import Cat.Cat.
From Categories Require Import Ext_Cons.Prod_Cat.Prod_Cat Ext_Cons.Prod_Cat.Operations.
From Categories Require Import Basic_Cons.Product.
From Categories Require Import Basic_Cons.Exponential.
From Categories Require Import NatTrans.NatTrans NatTrans.Func_Cat NatTrans.NatIso.
From Categories Require Import Cat.Product Cat.Exponential.
(** Facts about exponentials in Cat. *)
Local Open Scope functor_scope.
Section Exp_Cat_morph_ex_compose.
Context {C C' C'' : Category}
(F : (C'' × C) –≻ C')
{B : Category}
(G : B –≻ C'')
.
(** This is the more specific case of curry_compose. Proven separately for cat
because of universe polymorphism issues that prevent cat to both have
expoenentials and type_cat in it. *)
Theorem Exp_Cat_morph_ex_compose :
Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C)))
= (Exp_Cat_morph_ex F) ∘ G.
Proof.
Func_eq_simpl.
{
FunExt.
apply NatTrans_eq_simplify.
apply JMeq_eq.
ElimEq; trivial.
}
{
FunExt; cbn.
Func_eq_simpl.
FunExt.
cbn; auto.
}
Qed.
End Exp_Cat_morph_ex_compose.
Section Exp_Cat_morph_ex_compose_Iso.
Context {C C' C'' : Category}
(F : (C'' × C) –≻ C')
{B : Category}
(G : B –≻ C'').
Local Hint Extern 1 => apply NatTrans_eq_simplify; cbn.
Program Definition Exp_Cat_morph_ex_compose_Iso_RL :
((Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C))))
–≻ ((Exp_Cat_morph_ex F) ∘ G))%nattrans :=
{|
Trans :=
fun c =>
{|
Trans := fun d => id
|}
|}.
Program Definition Exp_Cat_morph_ex_compose_Iso_LR :
(((Exp_Cat_morph_ex F) ∘ G)
–≻ (Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C)))))%nattrans
:=
{|
Trans :=
fun c =>
{|
Trans := fun d => id
|}
|}.
(** This is the isomorphic form of the theorem above. *)
Program Definition Exp_Cat_morph_ex_compose_Iso :
(((Exp_Cat_morph_ex (F ∘ (Prod_Functor G (Functor_id C))))%functor)
≃ ((Exp_Cat_morph_ex F) ∘ G)%functor)%natiso :=
{|
iso_morphism := Exp_Cat_morph_ex_compose_Iso_RL;
inverse_morphism := Exp_Cat_morph_ex_compose_Iso_LR
|}.
End Exp_Cat_morph_ex_compose_Iso.
Section Exp_Cat_morph_ex_NT.
Context {C C' C'' : Category}
{F F' : (C'' × C) –≻ C'}
(N : (F –≻ F')%nattrans).
(** If we have a natural transformation from F to F' then we have a natural
transformation from (curry F) to (curry F'). *)
Program Definition Exp_Cat_morph_ex_NT :
((Exp_Cat_morph_ex F) –≻ (Exp_Cat_morph_ex F'))%nattrans :=
{|
Trans := fun d =>
{|
Trans := fun c => Trans N (d, c);
Trans_com :=
fun c c' h => @Trans_com _ _ _ _ N (d, c) (d ,c') (id, h);
Trans_com_sym :=
fun c c' h => @Trans_com_sym _ _ _ _ N (d, c) (d ,c') (id, h)
|}
|}.
Next Obligation.
Proof.
apply NatTrans_eq_simplify; FunExt; cbn.
apply Trans_com.
Qed.
Next Obligation.
Proof.
symmetry.
apply Exp_Cat_morph_ex_NT_obligation_1.
Qed.
End Exp_Cat_morph_ex_NT.
Section Exp_Cat_morph_ex_Iso.
Context {C C' C'' : Category}
{F F' : (C'' × C) –≻ C'}
(N : (F ≃ F')%natiso)
.
(** If F is naturally isomorphic to F' then (curry F) is naturally
isomorphic to (curry F'). *)
Program Definition Exp_Cat_morph_ex_Iso :
(Exp_Cat_morph_ex F ≃ Exp_Cat_morph_ex F')%natiso :=
{|
iso_morphism := Exp_Cat_morph_ex_NT (iso_morphism N);
inverse_morphism := Exp_Cat_morph_ex_NT (inverse_morphism N)
|}.
Next Obligation.
Proof.
apply NatTrans_eq_simplify; extensionality x; cbn.
apply NatTrans_eq_simplify; extensionality y; cbn.
change (Trans (N⁻¹) (x, y) ∘ Trans (iso_morphism N) (x, y))%morphism
with (Trans (N⁻¹ ∘ N)%morphism (x, y)).
rewrite left_inverse; trivial.
Qed.
Next Obligation.
Proof.
apply NatTrans_eq_simplify; extensionality x; cbn.
apply NatTrans_eq_simplify; extensionality y; cbn.
change (Trans (iso_morphism N) (x, y) ∘ Trans (N⁻¹) (x, y))%morphism
with (Trans (N ∘ (N⁻¹))%morphism (x, y)).
rewrite right_inverse; trivial.
Qed.
End Exp_Cat_morph_ex_Iso.
Section Exp_Cat_morph_ex_inverse_NT.
Context {C C' C'' : Category}
{F F' : (C'' × C) –≻ C'}
(N : ((Exp_Cat_morph_ex F) –≻ (Exp_Cat_morph_ex F'))%nattrans).
(** If we have a natural transformation from (curry F) to (curry F') then
we have a natural transformation from F to F'. *)
Program Definition Exp_Cat_morph_ex_inverse_NT : (F –≻ F')%nattrans :=
{|
Trans := fun d => Trans (Trans N (fst d)) (snd d)
|}.
Local Obligation Tactic := idtac.
Next Obligation.
Proof.
intros [d1 d2] [d1' d2'] [h1 h2]; cbn in *.
replace (F @_a (_, _) (_, _) (h1, h2))%morphism
with ((F @_a (_, _) (_, _) (id d1', h2))
∘ (F @_a (_, _) (_, _) (h1, id d2)))%morphism by auto.
rewrite assoc_sym.
cbn_rewrite (Trans_com (Trans N d1') h2).
rewrite assoc.
cbn_rewrite (f_equal (fun w => Trans w d2) (Trans_com N h1)).
rewrite assoc_sym.
rewrite <- F_compose.
cbn; auto.
Qed.
Next Obligation.
Proof.
symmetry.
apply Exp_Cat_morph_ex_inverse_NT_obligation_1.
Qed.
End Exp_Cat_morph_ex_inverse_NT.
Section Exp_Cat_morph_ex_inverse_Iso.
Context {C C' C'' : Category}
{F F' : (C'' × C) –≻ C'}
(N : (Exp_Cat_morph_ex F ≃ Exp_Cat_morph_ex F')%natiso)
.
(** If (curry F) is naturally isomorphic to (curry F') then we have that F is
naturally isomorphic to F'. *)
Program Definition Exp_Cat_morph_ex_inverse_Iso : (F ≃ F')%natiso :=
{|
iso_morphism := Exp_Cat_morph_ex_inverse_NT (iso_morphism N);
inverse_morphism := Exp_Cat_morph_ex_inverse_NT (inverse_morphism N)
|}.
Next Obligation.
Proof.
apply NatTrans_eq_simplify; extensionality x; cbn.
match goal with
[|- ?U = _] =>
match U with
(Trans (Trans ?A ?X) ?Y ∘ Trans (Trans ?B ?X) ?Y)%morphism =>
change U with (Trans (Trans (A ∘ B) X) Y)
end
end.
cbn_rewrite (left_inverse N); trivial.
Qed.
Next Obligation.
Proof.
apply NatTrans_eq_simplify; extensionality x; cbn.
match goal with
[|- ?U = _] =>
match U with
(Trans (Trans ?A ?X) ?Y ∘ Trans (Trans ?B ?X) ?Y)%morphism =>
change U with (Trans (Trans (NatTrans_compose B A) X) Y)
end
end.
cbn_rewrite (right_inverse N); trivial.
Qed.
End Exp_Cat_morph_ex_inverse_Iso.
|
[STATEMENT]
lemma nonzero_bl2wc[simp]: "\<forall>m. b \<noteq> Bk\<up>(m) \<Longrightarrow> 0 < bl2wc b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> 0 < bl2wc b
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> 0 < bl2wc b
[PROOF STEP]
have "\<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> bl2wc b = 0 \<Longrightarrow> False"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
proof(induct b)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>\<forall>m. [] \<noteq> Bk \<up> m; bl2wc [] = 0\<rbrakk> \<Longrightarrow> False
2. \<And>a b. \<lbrakk>\<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False; \<forall>m. a # b \<noteq> Bk \<up> m; bl2wc (a # b) = 0\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
case (Cons a b)
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False
\<forall>m. a # b \<noteq> Bk \<up> m
bl2wc (a # b) = 0
goal (2 subgoals):
1. \<lbrakk>\<forall>m. [] \<noteq> Bk \<up> m; bl2wc [] = 0\<rbrakk> \<Longrightarrow> False
2. \<And>a b. \<lbrakk>\<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False; \<forall>m. a # b \<noteq> Bk \<up> m; bl2wc (a # b) = 0\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
\<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False
\<forall>m. a # b \<noteq> Bk \<up> m
bl2wc (a # b) = 0
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False
\<forall>m. a # b \<noteq> Bk \<up> m
bl2wc (a # b) = 0
goal (1 subgoal):
1. False
[PROOF STEP]
apply(simp add: bl2wc.simps, case_tac a, simp_all
add: bl2nat.simps bl2nat_double)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; \<forall>m. Bk # b \<noteq> Bk \<up> m; bl2nat b 0 = 0; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; bl2wc b = 0; a = Bk; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
apply(case_tac "\<exists> m. b = Bk\<up>(m)", erule exE)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>m. \<lbrakk>\<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; \<forall>m. Bk # b \<noteq> Bk \<up> m; bl2nat b 0 = 0; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; bl2wc b = 0; a = Bk; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; b = Bk \<up> m\<rbrakk> \<Longrightarrow> False
2. \<lbrakk>\<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; \<forall>m. Bk # b \<noteq> Bk \<up> m; bl2nat b 0 = 0; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; bl2wc b = 0; a = Bk; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; \<nexists>m. b = Bk \<up> m\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
apply(metis append_Nil2 replicate_Suc_iff_anywhere)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>\<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; \<forall>m. Bk # b \<noteq> Bk \<up> m; bl2nat b 0 = 0; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; bl2wc b = 0; a = Bk; \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> False; \<nexists>m. b = Bk \<up> m\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
False
goal (1 subgoal):
1. \<lbrakk>\<forall>m. [] \<noteq> Bk \<up> m; bl2wc [] = 0\<rbrakk> \<Longrightarrow> False
[PROOF STEP]
qed auto
[PROOF STATE]
proof (state)
this:
\<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False
goal (1 subgoal):
1. \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> 0 < bl2wc b
[PROOF STEP]
thus "\<forall>m. b \<noteq> Bk\<up>(m) \<Longrightarrow> 0 < bl2wc b"
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>\<forall>m. b \<noteq> Bk \<up> m; bl2wc b = 0\<rbrakk> \<Longrightarrow> False
goal (1 subgoal):
1. \<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> 0 < bl2wc b
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
\<forall>m. b \<noteq> Bk \<up> m \<Longrightarrow> 0 < bl2wc b
goal:
No subgoals!
[PROOF STEP]
qed |
From iris.algebra Require Import auth gmap excl.
From aneris.algebra Require Import monotone.
From aneris.aneris_lang Require Import network resources proofmode.
From aneris.aneris_lang.lib Require Import list_proof lock_proof.
From aneris.examples.ccddb.spec Require Import base time events resources.
(** Specifications for read and write operations. *)
Section Specification.
Context `{!anerisG Mdl Σ, !DB_params, !DB_time, !Maximals_Computing,
!DB_events, !DB_resources Mdl Σ}.
(** General specifications for read & write *)
Definition read_spec
(rd : val) (i: nat) (z : socket_address) : iProp Σ :=
Eval simpl in
□ (∀ (k : Key) (s : lhst),
⌜DB_addresses !! i = Some z⌝ -∗
{{{ Seen i s }}}
rd #k @[ip_of_address z]
{{{ vo, RET vo;
∃ (s': lhst), ⌜s ⊆ s'⌝ ∗ Seen i s' ∗
((⌜vo = NONEV⌝ ∗ ⌜restrict_key k s' = ∅⌝) ∨
(∃ (v: val) (e : ae),
⌜vo = SOMEV v⌝ ∗ ⌜AE_val e = v⌝ ∗
⌜e ∈ Maximals (restrict_key k s')⌝ ∗
OwnMemSnapshot k {[erasure e]} ∗
⌜e = Observe (restrict_key k s')⌝))
}}})%I.
Definition write_spec
(wr : val) (i: nat) (z : socket_address) : iProp Σ :=
Eval simpl in
□ (∀ (E : coPset) (k : Key) (v : SerializableVal) (s: lhst)
(P : iProp Σ) (Q : ae → gmem → lhst → iProp Σ),
⌜DB_addresses !! i = Some z⌝ -∗
⌜↑DB_InvName ⊆ E⌝ -∗
□ (∀ (s1: lhst) (e: ae),
let s' := s1 ∪ {[ e ]} in
⌜s ⊆ s1⌝ → ⌜e ∉ s1⌝ →
⌜AE_key e = k⌝ → ⌜AE_val e = v⌝ →
P ={⊤, E}=∗
∀ (h : gmem),
let a := erasure e in
let h' := h ∪ {[ a ]} in
⌜a ∉ h⌝ →
⌜a ∈ Maximals h'⌝ →
⌜Maximum s' = Some e⌝ →
Seen i s' -∗
k ↦ₛ h
={E∖↑DB_InvName}=∗ k ↦ₛ h' ∗ |={E, ⊤}=> Q e h s1) -∗
{{{ ⌜k ∈ DB_keys⌝ ∗ P ∗ Seen i s }}}
wr #k v @[ip_of_address z]
{{{ RET #();
∃ (h: gmem) (s1: lhst) (e: ae), ⌜s ⊆ s1⌝ ∗ Q e h s1 }}})%I.
Definition init_spec (init : val) : iProp Σ :=
□ ∀ (i : nat) (z : socket_address)
(v : val),
⌜is_list DB_addresses v⌝ →
⌜DB_addresses !! i = Some z⌝ →
{{{ ([∗ list] i ↦ z ∈ DB_addresses, z ⤇ DB_socket_proto) ∗
z ⤳ (∅, ∅) ∗
free_ports (ip_of_address z) {[port_of_address z]} ∗
init_token i}}}
init v #i @[ip_of_address z]
{{{ rd wr, RET (rd, wr);
Seen i ∅ ∗ read_spec rd i z ∗ write_spec wr i z}}}.
Definition simplified_write_spec
(wr : val) (i: nat) (z : socket_address)
(k : Key) (v : SerializableVal) (h : gmem) (s : lhst) : iProp Σ :=
(⌜DB_addresses !! i = Some z⌝ -∗
⌜k ∈ DB_keys⌝ -∗
{{{ k ↦ᵤ h ∗ Seen i s }}}
wr #k v @[ip_of_address z]
{{{ RET #();
∃ (s1: lhst) (e: ae),
⌜s ⊆ s1⌝ ∗ ⌜e ∉ s1⌝ ∗ ⌜AE_key e = k⌝ ∗ ⌜AE_val e = v⌝ ∗
⌜erasure e ∉ h⌝ ∗ ⌜Maximum (s1 ∪ {[ e ]}) = Some e⌝ ∗
⌜erasure e ∈ Maximals (h ∪ {[ erasure e ]})⌝ ∗ Seen i (s1 ∪ {[ e ]}) ∗
k ↦ᵤ (h ∪ {[ erasure e ]}) }}})%I.
Lemma write_spec_implies_simplified_write_spec wr i z :
write_spec wr i z ⊢ ∀ k v h s, simplified_write_spec wr i z k v h s.
Proof.
iIntros "#Hwr" (k v h s).
iIntros (Hi Hk) "!#".
iIntros (Φ) "[Hk Hseen] HΦ".
set (P := k ↦ᵤ h).
set (Q e1 h1 s1 :=
(⌜h1 = h⌝ ∗ ⌜s ⊆ s1⌝ ∗ ⌜e1 ∉ s1⌝ ∗ ⌜AE_key e1 = k⌝ ∗
⌜AE_val e1 = v⌝ ∗ ⌜erasure e1 ∉ h1⌝ ∗ ⌜Maximum (s1 ∪ {[e1]}) = Some e1⌝ ∗
⌜erasure e1 ∈ Maximals (h1 ∪ {[erasure e1]})⌝ ∗
Seen i (s1 ∪ {[e1]}) ∗ k ↦ᵤ (h1 ∪ {[erasure e1]}))%I).
iSpecialize ("Hwr" $! ⊤ k v s P Q with "[] []"); [done|done|].
iApply ("Hwr" with "[] [$Hk $Hseen]"); [|done|].
- iModIntro.
iIntros (s1 e Hs1 Hes1 Hek Hev) "Hkh".
unfold P, Q.
iModIntro.
iIntros (h' Hh' He'h' Hmax) "Hseen Hsys".
iDestruct (User_Sys_agree with "Hkh Hsys") as %<-.
iMod (OwnMem_update _ _ (h ∪ {[erasure e]}) with "Hkh Hsys")
as "[Hkh Hsys]"; first set_solver.
iModIntro; eauto with iFrame.
- iNext.
unfold Q.
iDestruct 1 as (h1 s1 e2 Hse) "(->&%&%&%&%&%&%&%&?&?)".
iApply "HΦ"; iExists _, _; eauto with iFrame.
Qed.
End Specification.
(** Modular specification for causal memory
vector-clock based implementation. *)
Class DBG `{!DB_time, !DB_events} Σ := {
DBG_Global_mem_excl :> inG Σ (authUR (gmapUR Key (exclR (gsetO we))));
DBG_Global_mem_mono :> inG Σ (authUR (gmapUR Key (gsetUR we)));
DBG_local_history_mono :> inG Σ (authUR (monotoneUR seen_relation));
DBG_local_history_gset :> inG Σ (authUR (gsetUR ae));
DBG_lockG :> lockG Σ;
}.
Definition DBΣ `{!DB_time, !DB_events} : gFunctors :=
#[GFunctor (authUR (gmapUR Key (exclR (gsetO we))));
GFunctor (authUR (gmapUR Key (gsetUR we)));
GFunctor (authUR (monotoneUR seen_relation));
GFunctor (authUR (gsetUR ae));
lockΣ].
Instance subG_DBΣ `{!DB_time, !DB_events} {Σ} : subG DBΣ Σ → DBG Σ.
Proof. econstructor; solve_inG. Qed.
Class DB_init_function := { init : val }.
Section Init.
Context `{!anerisG Mdl Σ, !DB_params, !DB_time, !Maximals_Computing,
!DB_events, !DBG Σ, !DB_init_function}.
Class DB_init := {
DB_init_time :> DB_time;
DB_init_events :> DB_events;
DB_init_setup E :
True ⊢ |={E}=> ∃ (DBRS : DB_resources Mdl Σ),
GlobalInv ∗
([∗ list] i ↦ _ ∈ DB_addresses, init_token i) ∗
([∗ set] k ∈ DB_keys, OwnMemUser k ∅) ∗
init_spec init;
}.
End Init.
|
> module PNat.Operations
> import PNat.PNat
> import Nat.Positive
> import Nat.Operations
> import Nat.OperationsProperties
> import Pairs.Operations
> %default total
> %access public export
> ||| The predecessor of a PNat
> pred : PNat -> Nat
> pred (Element _ (MkPositive {n})) = n
> |||
> fromNat : (m : Nat) -> Z `LT` m -> PNat
> {-
> fromNat Z zLTz = absurd zLTz
> fromNat (S m) _ = Element (S m) (MkPositive {n = m})
> ----}
> --{-
> fromNat m prf = Element m pm where
> pm : Positive m
> pm = fromSucc (pred m prf) m (predLemma m prf)
> ---}
> |||
> toNat : PNat -> Nat
> toNat = getWitness
> |||
> plus : PNat -> PNat -> PNat
> plus (Element m pm) (Element n pn) = Element (m + n) (plusPreservesPositivity pm pn)
> |||
> (+) : PNat -> PNat -> PNat
> (+) = plus
> |||
> mult : PNat -> PNat -> PNat
> mult (Element m pm) (Element n pn) = Element (m * n) (multPreservesPositivity pm pn)
> |||
> (*) : PNat -> PNat -> PNat
> (*) = mult
> {-
> ---}
|
# includet("D:\\projects\\vsCode\\MedPipe\\MedPipe\\src\\structs\\distinctColorsSaved.jl")
# includet("D:\\projects\\vsCode\\MedPipe\\MedPipe\\src\\visualizationUtils\\visualizationFromHdf5.jl")
# includet("D:\\projects\\vsCode\\MedPipe\\MedPipe\\src\\HDF5Utils\\HDF5saveUtils.jl")
# includet("D:\\projects\\vsCode\\MedPipe\\MedPipe\\src\\fromMonai\\LoadFromMonai.jl")
|
\section{Research Goal}
This research will show how generating comment is important to identify fake news on social media.
Fake news constitutes a grave menace to the safety of our world.
Therefore, it is important to detect news credibility before spreading on social media.
We aim to detect fake news more precisely by generating comments from articles that are only available after they have spread.
In computer science, computer security is the protection of computer systems.
Likewise, countering to fake news prevent people from exposing to malicious information on social media.
This is similar to computer security for the purpose of protecting the safety of society. |
# Kinematik-Berechnung 3. Arm KAS5
# Beschreibung
#
# Modell ohne Zwangsbedingungen. Diese Definitionsdatei erzeugt Dummy-Variablen, damit die Code-Generierung funktioniert.
#
# Die Gelenkvariablen der Schnittgelenke sollen nicht berechnet werden und sind als konstante Ausdrücke in kintmp_s vorgegeben und werden später mit Null ersetzt.
#
# Autor
# Moritz Schappler, [email protected], 2018-02
# Institut fuer mechatronische Systeme, Leibniz Universitaet Hannover
# Initialisierung
restart:
kin_constraints_exist := true: # Für Speicherung
;
with(LinearAlgebra):
with(StringTools): # Für Zeitausgabe
;
read "../helper/proc_convert_s_t":
read "../helper/proc_convert_t_s":
read "../helper/proc_MatlabExport":
codegen_act := true:
read "../robot_codegen_constraints/proc_subs_kintmp_exp":
read "../robot_codegen_definitions/robot_env":
read sprintf("../codeexport/%s/tmp/tree_floatb_definitions", robot_name):
kintmp_subsexp := Matrix(2*RowDimension(kintmp_s),2):
kin_constraints_exist := true:
# Dummy-Einträge für Schnitt-Gelenke
# Die Winkel der Schnittgelenke sind egal, daher keine Berechnung.
# Ersetze alle mit Null
kintmp_qs := kintmp_s*0:
kintmp_qt := kintmp_t*0:
# Speichern der Ergebnisse
save kin_constraints_exist, kintmp_qs, kintmp_qt, kintmp_subsexp, sprintf("../codeexport/%s/tmp/kinematic_constraints_maple_inert", robot_name):
save kin_constraints_exist, kintmp_qs, kintmp_qt, kintmp_subsexp, sprintf("../codeexport/%s/tmp/kinematic_constraints_maple_inert.m", robot_name):
# Liste der Parameter speichern
# Liste mit abhängigen konstanten Kinematikparametern erstellen (wichtig für Matlab-Funktionsgenerierung)
read "../helper/proc_list_constant_expressions";
kc_symbols := Matrix(list_constant_expressions( kintmp_subsexp(..,2) )):
save kc_symbols, sprintf("../codeexport/%s/tmp/kinematic_constraints_symbols_list_maple", robot_name):
kintmp_s:
|
function varargout = arg_guidialog(func,varargin)
% Create an input dialog that displays input fields for a Function and Parameters.
% Parameters = arg_guidialog(Function, Options...)
%
% The Parameters that are passed to the function can be used to override some of its defaults. The
% function must declare its arguments via arg_define. In addition, only a Subset of the function's
% specified arguments can be displayed.
%
% If this function is called with no arguments from within a function that uses arg_define it brings
% up a dialog for the function's defined arguments, with values assigned based on the function's
% inputs (contents of in varargin) and returns an argument struct if the dialog was confirmed with a
% click on OK, and an empty value otherwise. The calling function can exit on empty, or otherwise
% resume with entered parameters.
%
% In:
% Function : the function for which to display arguments
%
% Options... : optional name-value pairs; possible names are:
% 'Parameters' : cell array of parameters to the Function to override some of its
% defaults.
%
% 'Subset' : Cell array of argument names to which the dialog shall be restricted;
% these arguments may contain . notation to index into arg_sub and the
% selected branch(es) of arg_subswitch/arg_subtoggle specifiers. Empty
% cells show up in the dialog as empty rows.
%
% 'Title' : title of the dialog (by default: functionname())
%
% 'Invoke' : whether to invoke the function directly; in this case, the output
% arguments are those of the function (default: true, unless called in
% the form g = arg_guidialog; from within some function)
%
% 'ShowGuru' : whether to show parameters marked as guru-level. (default: according
% to env_startup setting)
%
% Out:
% Parameters : If Invoke was set to true, this is either the results of the function call or empty
% (if the dialog was cancelled). If Invoke was set to false, this is either a struct
% that is a valid input to the Function, or an empty value if cancel was clicked.
%
% Examples:
% % bring up a configuration dialog for the given function
% settings = arg_guidialog(@myfunction)
%
% % bring up a config dialog with some pre-specified defaults
% settings = arg_guidialog(@myfunction,'Parameters',{4,20,'test'})
%
% % bring up a config dialog which displays only a subset of the function's arguments (in a particular order)
% settings = arg_guidialog(@myfunction,'Subset',{'blah','xyz',[],'flag'})
%
% % bring up a dialog, and invoke the function with the selected settings after the user clicks OK
% settings = arg_guidialog(@myfunction,'Invoke',true)
%
% % from within a function
% args = arg_define(varargin, ...);
% if nargin < 1
% % optionally allow the user to enter arguments via a GUI
% args = arg_guidialog;
% % user clicked cancel?
% if isempty(args), return; end
% end
%
% See also:
% arg_guidialog_ex, arg_guipanel, arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-24
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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 2 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
% USA
global tracking;
if ~exist('func','var')
% called with no arguments, from inside a function: open function dialog
func = hlp_getcaller;
varargin = {'Parameters',evalin('caller','varargin'),'Invoke',nargout==0};
end
if ischar(func)
func = str2func(func); end
% parse arguments...
hlp_varargin2struct(varargin, ...
{'params','Parameters','parameters'},{}, ...
{'subset','Subset'},{}, ...
{'dialogtitle','title','Title'}, [char(func) '()'], ...
{'buttons','Buttons'},[], ...
{'invoke','Invoke'},true, ...
{'show_guru','ShowGuru'},tracking.gui.show_guru);
oldparams = params;
% obtain the argument specification for the function
rawspec = arg_report('rich', func, params); %#ok<*NODEF>
% extract a list of sub arguments...
if ~isempty(subset) && subset{1}==-1
% user specified a set of items to *exclude*
% convert subset to setdiff(all-arguments,subset)
allnames = fieldnames(arg_tovals(rawspec));
subset(1) = [];
subset = allnames(~ismember(allnames,[subset 'arg_direct']));
end
[spec,subset] = obtain_items(rawspec,subset,'',show_guru);
% trim unnecessary blank margins at the beginning and end
while isempty(spec{1}) && isempty(subset{1})
spec = spec(2:end);
subset = subset(2:end);
end
while isempty(spec{end}) && isempty(subset{end})
spec = spec(1:end-1);
subset = subset(1:end-1);
end
% create an inputgui() dialog...
geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2);
geomvert = ones(1,length(spec)+length(buttons)/2);
% turn the spec into a UI list...
uilist = {};
for k = 1:length(spec)
s = spec{k};
if isempty(s)
uilist(end+1:end+2) = {{} {}};
else
if isempty(s.help)
error(['Cannot display the argument ' subset{k} ' because it contains no description.']);
else
tag = subset{k};
uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'};
% depending on the type, we introduce different types of input widgets here...
if iscell(s.range) && strcmp(s.type,'char')
% string popup menu
uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag};
elseif strcmp(s.type,'logical')
if iscell(s.range) % length(s.range)>1
% multiselect
uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(ismember(s.range,s.value)),'tag',tag,'min',1,'max',100000};
geomvert(k) = min(3.5,length(s.range));
else
% checkbox
uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag};
end
elseif strcmp(s.type,'char')
% string edit
uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag};
else
% expression edit
if isinteger(s.value)
s.value = double(s.value); end
uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag};
end
% append the tooltip string
if length(s.help) > 1
uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end
end
end
if ~isempty(buttons) && k==buttons{1}
% render a command button
uilist(end+1:end+2) = {{} buttons{2}};
buttons(1:2) = [];
end
end
% invoke the GUI, obtaining a list of output values...
helptopic = char(func);
try
if helptopic(1) == '@'
fn = functions(func);
tmp = struct2cell(fn.workspace{1});
helptopic = class(tmp{1});
end
catch
disp('Cannot deduce help topic.');
end
[outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom',['env_doc ' helptopic], 'title',dialogtitle,'geomvert',geomvert); %#ok<ASGLU>
if ~isempty(okpressed)
% remove blanks from the spec
spec = spec(~cellfun('isempty',spec));
subset = subset(~cellfun('isempty',subset));
% turn the raw specification into a parameter struct (a non-direct one, since we will mess with
% it)
params = arg_tovals(rawspec);
% for each parameter produced by the GUI...
for k = 1:length(outs)
s = spec{k}; % current specifier
v = outs{k}; % current raw value
% do type conversion according to spec
if iscell(s.range) && strcmp(s.type,'char')
v = s.range{v};
elseif strcmp(s.type,'expression')
v = eval(v);
elseif strcmp(s.type,'logical')
if length(s.range)>1
v = s.range(v);
else
v = logical(v);
end
elseif strcmp(s.type,'char')
% noting to do
elseif ~isempty(v) && ischar(v)
v = eval(v);
end
% assign the converted value to params struct...
params = assign(params,subset{k},v);
end
% now send the result through the function to check for errors and obtain a values structure...
params = arg_report('rich',func,{params});
params = arg_tovals(params);
% invoke the function, if so desired
if ischar(func)
func = str2func(func); end
if invoke
[varargout{1:nargout(func)}] = func(oldparams{:},params);
else
varargout = {params};
end
else
varargout = {[]};
end
% obtain a cell array of spec entries by name from the given specification
function [items,ids] = obtain_items(rawspec,requested,prefix,show_guru)
if ~exist('prefix','var')
prefix = ''; end
items = {};
ids = {};
% determine what subset of (possibly nested) items is requested
if isempty(requested)
% look for a special argument/property arg_dialogsel, which defines the standard dialog
% representation for the given specification
dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names}));
if ~isempty(dialog_sel)
requested = rawspec(dialog_sel).value; end
end
if isempty(requested)
% empty means that all items are requested
for k=1:length(rawspec)
items{k} = rawspec(k);
ids{k} = [prefix rawspec(k).names{1}];
end
else
% otherwise we need to obtain those items
for k=1:length(requested)
if ~isempty(requested{k})
try
[items{k},subid] = obtain(rawspec,requested{k});
catch
error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']);
end
ids{k} = [prefix subid];
end
end
end
% splice items that have children (recursively) into this list
for k = length(items):-1:1
% special case: switch arguments are not spliced, but instead the argument that defines the
% option popupmenu will be retained
if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested))
[subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.'],show_guru);
if ~isempty(subitems)
% and introduce blank rows around them
items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)];
ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)];
end
end
end
% remove items that cannot be displayed
retain = cellfun(@(x)isempty(x)||x.displayable&&(show_guru||~x.guru),items);
items = items(retain);
ids = ids(retain);
% remove double blank rows
empties = cellfun('isempty',ids);
items(empties(1:end-1) & empties(2:end)) = [];
ids(empties(1:end-1) & empties(2:end)) = [];
% obtain a spec entry by name from the given specification
function [item,id] = obtain(rawspec,identifier,prefix)
if ~exist('prefix','var')
prefix = ''; end
% parse the . notation
dot = find(identifier=='.',1);
if ~isempty(dot)
[head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end));
else
head = identifier;
rest = [];
end
% search for the identifier at this level
names = {rawspec.names};
for k=1:length(names)
if any(strcmp(names{k},head))
% found a match!
if isempty(rest)
% return it
item = rawspec(k);
id = [prefix names{k}{1}];
else
% obtain the rest of the identifier
[item,id] = obtain(rawspec(k).children,rest,[prefix names{k}{1} '.']);
end
return;
end
end
error(['The given identifier (' head ') was not found among the function''s declared arguments.']);
% assign a field with dot notation in a struct
function s = assign(s,id,v)
% parse the . notation
dot = find(id=='.',1);
if ~isempty(dot)
[head,rest] = deal(id(1:dot-1), id(dot+1:end));
if ~isfield(s,head)
s.(head) = struct(); end
s.(head) = assign(s.(head),rest,v);
else
s.(id) = v;
end
|
section \<open>Sepref-Definition Command\<close>
theory Sepref_Definition
imports Sepref_Rules "Lib/Pf_Mono_Prover" "Lib/Term_Synth"
keywords "sepref_definition" :: thy_goal
and "sepref_thm" :: thy_goal
begin
subsection \<open>Setup of Extraction-Tools\<close>
declare [[cd_patterns "hn_refine _ ?f _ _ _"]]
lemma heap_fixp_codegen:
assumes DEF: "f \<equiv> heap.fixp_fun cB"
assumes M: "(\<And>x. mono_Heap (\<lambda>f. cB f x))"
shows "f x = cB f x"
unfolding DEF
apply (rule fun_cong[of _ _ x])
apply (rule heap.mono_body_fixp)
apply fact
done
ML \<open>
structure Sepref_Extraction = struct
val heap_extraction: Refine_Automation.extraction = {
pattern = Logic.varify_global @{term "heap.fixp_fun x"},
gen_thm = @{thm heap_fixp_codegen},
gen_tac = (fn ctxt =>
Pf_Mono_Prover.mono_tac ctxt
)
}
val setup = I
(*#> Refine_Automation.add_extraction "trivial" triv_extraction*)
#> Refine_Automation.add_extraction "heap" heap_extraction
end
\<close>
setup Sepref_Extraction.setup
subsection \<open>Synthesis setup for sepref-definition goals\<close>
(* TODO: The UNSPEC are an ad-hoc hack to specify the synthesis goal *)
consts UNSPEC::'a
abbreviation hfunspec
:: "('a \<Rightarrow> 'b \<Rightarrow> assn) \<Rightarrow> ('a \<Rightarrow> 'b \<Rightarrow> assn)\<times>('a \<Rightarrow> 'b \<Rightarrow> assn)"
("(_\<^sup>?)" [1000] 999)
where "R\<^sup>? \<equiv> hf_pres R UNSPEC"
definition SYNTH :: "('a \<Rightarrow> 'r nres) \<Rightarrow> (('ai \<Rightarrow>'ri Heap) \<times> ('a \<Rightarrow> 'r nres)) set \<Rightarrow> bool"
where "SYNTH f R \<equiv> True"
definition [simp]: "CP_UNCURRY _ _ \<equiv> True"
definition [simp]: "INTRO_KD _ _ \<equiv> True"
definition [simp]: "SPEC_RES_ASSN _ _ \<equiv> True"
lemma [synth_rules]: "\<lbrakk>INTRO_KD R1 R1'; INTRO_KD R2 R2'\<rbrakk> \<Longrightarrow> INTRO_KD (R1*\<^sub>aR2) (R1'*\<^sub>aR2')" by simp
lemma [synth_rules]: "INTRO_KD (R\<^sup>?) (hf_pres R k)" by simp
lemma [synth_rules]: "INTRO_KD (R\<^sup>k) (R\<^sup>k)" by simp
lemma [synth_rules]: "INTRO_KD (R\<^sup>d) (R\<^sup>d)" by simp
lemma [synth_rules]: "SPEC_RES_ASSN R R" by simp
lemma [synth_rules]: "SPEC_RES_ASSN UNSPEC R" by simp
lemma synth_hnrI:
"\<lbrakk>CP_UNCURRY fi f; INTRO_KD R R'; SPEC_RES_ASSN S S'\<rbrakk> \<Longrightarrow> SYNTH_TERM (SYNTH f ([P]\<^sub>a R\<rightarrow>S)) ((fi,SDUMMY)\<in>SDUMMY,(fi,f)\<in>([P]\<^sub>a R'\<rightarrow>S'))"
by (simp add: SYNTH_def)
term starts_with
ML \<open>
structure Sepref_Definition = struct
fun make_hnr_goal t ctxt = let
val ctxt = Variable.declare_term t ctxt
val (pat,goal) = case Term_Synth.synth_term @{thms synth_hnrI} ctxt t of
@{mpat "(?pat,?goal)"} => (pat,goal) | t => raise TERM("Synthesized term does not match",[t])
val pat = Thm.cterm_of ctxt pat |> Refine_Automation.prepare_cd_pattern ctxt
val goal = HOLogic.mk_Trueprop goal
in
((pat,goal),ctxt)
end
val cfg_prep_code = Attrib.setup_config_bool @{binding sepref_definition_prep_code} (K true)
local
open Refine_Util
val flags = parse_bool_config' "prep_code" cfg_prep_code
val parse_flags = parse_paren_list' flags
in
val sd_parser = parse_flags -- Parse.binding -- Parse.opt_attribs --| @{keyword "is"}
-- Parse.term --| @{keyword "::"} -- Parse.term
end
fun mk_synth_term ctxt t_raw r_raw = let
val t = Syntax.parse_term ctxt t_raw
val r = Syntax.parse_term ctxt r_raw
val t = Const (@{const_name SYNTH},dummyT)$t$r
in
Syntax.check_term ctxt t
end
fun sd_cmd ((((flags,name),attribs),t_raw),r_raw) lthy = let
local
val ctxt = Refine_Util.apply_configs flags lthy
in
val flag_prep_code = Config.get ctxt cfg_prep_code
end
val t = mk_synth_term lthy t_raw r_raw
val ((pat,goal),ctxt) = make_hnr_goal t lthy
fun
after_qed [[thm]] ctxt = let
val thm = singleton (Variable.export ctxt lthy) thm
val (_,lthy)
= Local_Theory.note
((Refine_Automation.mk_qualified (Binding.name_of name) "refine_raw",[]),[thm])
lthy;
val ((dthm,rthm),lthy) = Refine_Automation.define_concrete_fun NONE name attribs [] thm [pat] lthy
val lthy = lthy
|> flag_prep_code ? Refine_Automation.extract_recursion_eqs
[Sepref_Extraction.heap_extraction] (Binding.name_of name) dthm
val _ = Thm.pretty_thm lthy dthm |> Pretty.string_of |> writeln
val _ = Thm.pretty_thm lthy rthm |> Pretty.string_of |> writeln
in
lthy
end
| after_qed thmss _ = raise THM ("After-qed: Wrong thmss structure",~1,flat thmss)
in
Proof.theorem NONE after_qed [[ (goal,[]) ]] ctxt
end
val _ = Outer_Syntax.local_theory_to_proof @{command_keyword "sepref_definition"}
"Synthesis of imperative program"
(sd_parser >> sd_cmd)
val st_parser = Parse.binding --| @{keyword "is"} -- Parse.term --| @{keyword "::"} -- Parse.term
fun st_cmd ((name,t_raw),r_raw) lthy = let
val t = mk_synth_term lthy t_raw r_raw
val ((_,goal),ctxt) = make_hnr_goal t lthy
fun
after_qed [[thm]] ctxt = let
val thm = singleton (Variable.export ctxt lthy) thm
val _ = Thm.pretty_thm lthy thm |> Pretty.string_of |> tracing
val (_,lthy)
= Local_Theory.note
((Refine_Automation.mk_qualified (Binding.name_of name) "refine_raw",[]),[thm])
lthy;
in
lthy
end
| after_qed thmss _ = raise THM ("After-qed: Wrong thmss structure",~1,flat thmss)
in
Proof.theorem NONE after_qed [[ (goal,[]) ]] ctxt
end
val _ = Outer_Syntax.local_theory_to_proof @{command_keyword "sepref_thm"}
"Synthesis of imperative program: Only generate raw refinement theorem"
(st_parser >> st_cmd)
end
\<close>
end
|
Require Import OrderedType.
Require Import ProjectedOrderedType.
Inductive accessRight :=
| wk : accessRight
| rd : accessRight
| wr : accessRight
| tx : accessRight.
Module ProjectedAccessRight <: ProjectedToNat.
Definition t := accessRight.
Definition project_to_nat r:=
match r with
| wk => 0
| rd => 1
| wr => 2
| tx => 3
end.
Theorem project_to_nat_unique: forall x y:t,
(project_to_nat x) = (project_to_nat y) <-> x = y.
Proof.
intros x y; split; intros H;
unfold project_to_nat in *;
destruct x; destruct y; auto; discriminate.
Qed.
End ProjectedAccessRight.
Module AccessRight := POT_to_OT ProjectedAccessRight.
(* Module AccessRightOT : OrderedType := AccessRight. *)
|
open import Agda.Primitive
open import Semigroup
module Monoid where
record Σ {a b} (A : Set a) (B : A → Set b) : Set (a ⊔ b) where
constructor _,_
field
proj₁ : A
proj₂ : B proj₁
Σ-syntax : ∀ {a b} (A : Set a) → (A → Set b) → Set (a ⊔ b)
Σ-syntax = Σ
syntax Σ-syntax A (λ x → B) = Σ[ x ∈ A ] B
_×_ : ∀ {a b} (A : Set a) (B : Set b) → Set (a ⊔ b)
A × B = Σ[ x ∈ A ] B
record Monoid {A : Set} (_∙_ : A → A → A) (ε : A) : Set where
field
semigroup : Semigroup _∙_
identity : (∀ x → ε ∙ x ≡ x) × (∀ x → x ∙ ε ≡ x)
|
gap>List(SymmetricGroup(4), p -> Permuted([1 .. 4], p));
perms(4);
[ [ 1, 2, 3, 4 ], [ 4, 2, 3, 1 ], [ 2, 4, 3, 1 ], [ 3, 2, 4, 1 ], [ 1, 4, 3, 2 ], [ 4, 1, 3, 2 ], [ 2, 1, 3, 4 ],
[ 3, 1, 4, 2 ], [ 1, 3, 4, 2 ], [ 4, 3, 1, 2 ], [ 2, 3, 1, 4 ], [ 3, 4, 1, 2 ], [ 1, 2, 4, 3 ], [ 4, 2, 1, 3 ],
[ 2, 4, 1, 3 ], [ 3, 2, 1, 4 ], [ 1, 4, 2, 3 ], [ 4, 1, 2, 3 ], [ 2, 1, 4, 3 ], [ 3, 1, 2, 4 ], [ 1, 3, 2, 4 ],
[ 4, 3, 2, 1 ], [ 2, 3, 4, 1 ], [ 3, 4, 2, 1 ] ]
|
#pragma once
#include <errno.h> // errno
#include <fcntl.h> // open, write
#include <unistd.h> // getpid
#include <sstream>
#include <boost/filesystem.hpp>
#include <gsl/gsl_util>
#include "do_persistence.h"
#include "error_macros.h"
// RAII wrapper for creating, writing and deleting the file that will
// contain the port number for the REST interface.
class RestPortAdvertiser
{
public:
RestPortAdvertiser(uint16_t port)
{
// We cannot remove the port file on shutdown because we have already dropped permissions.
// Clean it up now when we are still running as root.
_DeleteOlderPortFiles();
std::stringstream ss;
ss << docli::GetRuntimeDirectory() << '/' << _restPortFileNamePrefix << '.' << getpid();
_outFilePath = ss.str();
// If file already exists, it is truncated. Probably from an old instance that terminated abnormally.
// Allow file to only be read by others.
int fd = open(_outFilePath.data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH);
if (fd == -1)
{
THROW_HR_MSG(E_FAIL, "Failed to open file %s, errno: %d", _outFilePath.data(), errno);
}
try
{
const auto writeStr = std::to_string(port) + '\n';
const auto cbWrite = gsl::narrow_cast<ssize_t>(writeStr.size() * sizeof(char));
const ssize_t written = write(fd, writeStr.data(), cbWrite);
if (written != cbWrite)
{
THROW_HR_MSG(E_FAIL, "Failed to write port, written: %zd, errno: %d", written, errno);
}
}
catch (...)
{
(void)close(fd);
throw;
}
(void)close(fd);
}
const std::string& OutFilePath() const { return _outFilePath; }
private:
void _DeleteOlderPortFiles() try
{
auto& runtimeDirectory = docli::GetRuntimeDirectory();
for (boost::filesystem::directory_iterator itr(runtimeDirectory); itr != boost::filesystem::directory_iterator(); ++itr)
{
auto& dirEntry = itr->path();
if (dirEntry.filename().string().find(_restPortFileNamePrefix) != std::string::npos)
{
boost::system::error_code ec;
boost::filesystem::remove(dirEntry, ec);
if (ec)
{
DoLogWarning("Failed to delete old port file (%d, %s) %s", ec.value(), ec.message().data(), dirEntry.string().data());
}
}
}
} CATCH_LOG()
std::string _outFilePath;
static constexpr const char* const _restPortFileNamePrefix = "restport";
};
|
open list
-- Exercise: 1 star (snd_fst_is_swap)
def swap : ℕ × ℕ → ℕ × ℕ
| (a, b) := (b, a)
lemma snd_fst_is_swap : ∀ p : ℕ × ℕ, (p.snd, p.fst) = swap p
| (a, b) := rfl
-- Exercise: 1 star, optional (fst_swap_is_snd)
theorem fst_swap_is_snd : ∀ p : ℕ × ℕ, (swap p).fst = p.snd
| (a, b) := rfl
-- Exercise: 2 stars, recommended (list_funs)
def nonzeros : list ℕ → list ℕ
| nil := nil
| (cons x xs) := if x ≠ 0 then [x] ++ nonzeros xs else nonzeros xs
lemma test_nonzeros : nonzeros [0, 1, 0, 2, 3, 0, 0] = [1, 2, 3] := rfl
def oddmembers : list ℕ → list ℕ
| nil := nil
| (cons x xs) := if nat.bodd x then [x] ++ oddmembers xs else oddmembers xs
lemma test_oddmembers : oddmembers [0, 1, 0, 2, 3, 0, 0] = [1, 3] := rfl
def countoddmembers (l : list ℕ) : ℕ := length (oddmembers l)
lemma test_countoddmembers1 : countoddmembers [1, 0, 3, 1, 4, 5] = 4 := rfl
lemma test_countoddmembers2 : countoddmembers [0, 2, 4] = 0 := rfl
lemma test_countoddmembers3 : countoddmembers nil = 0 := rfl
-- Exercise: 3 stars, advanced (alternate)
def alternate : list ℕ → list ℕ → list ℕ
| [] [] := []
| [] (y :: ys) := [y] ++ alternate [] ys
| (x :: xs) [] := [x] ++ alternate xs []
| (x :: xs) (y :: ys) := [x, y] ++ alternate xs ys
lemma test_alternate1 : alternate [1,2,3] [4,5,6] = [1,4,2,5,3,6] := rfl
lemma test_alternate2 : alternate [1] [4, 5, 6] = [1,4,5,6] := rfl
lemma test_alternate3 : alternate [1,2,3] [4] = [1,4,2,3] := rfl
lemma test_alternate4 : alternate [] [20,30] = [20, 30] := rfl
-- Exercise: 3 stars, recommended (bag_functions)
def bag : Type := list ℕ
def count : ℕ → bag → ℕ
| n [] := 0
| n (x::xs) := if x = n then 1 + count n xs else count n xs
lemma test_count1 : count 1 [1,2,3,1,4,1] = 3 := rfl
lemma test_count2 : count 6 [1,2,3,1,4,1] = 0 := rfl
def bag.sum : bag → bag → bag := λ a b, @list.append ℕ a b
lemma test_sum1 : count 1 (bag.sum [1,2,3] [1,4,1]) = 3 := rfl
def bag.add : ℕ → bag → bag := λ a b, list.append b [a]
lemma test_add1 : count 1 (bag.add 1 [1,4,1]) = 3 := rfl
lemma test_add2 : count 5 (bag.add 1 [1,4,1]) = 0 := rfl
def bag.mem : ℕ → bag → bool
| n [] := ff
| n (x::xs) := if n = x then tt else bag.mem n xs
lemma test_mem1 : bag.mem 1 [1,4,1] = tt := rfl
lemma test_mem2 : bag.mem 2 [1,4,1] = ff := rfl
-- Exercise: 3 stars, optional (bag_more_functions)
def remove_one : ℕ → bag → bag
| n [] := []
| n (x::xs) := if n = x then xs else x :: (remove_one n xs)
lemma test_remove_one1 : count 5 (remove_one 5 [2,1,5,4,1]) = 0 := rfl
lemma test_remove_one2 : count 5 (remove_one 5 [2,1,4,1]) = 0 := rfl
lemma test_remove_one3 : count 4 (remove_one 5 [2,1,4,5,1,4]) = 2 := rfl
lemma test_remove_one4 : count 5 (remove_one 5 [2,1,5,4,5,1,4]) = 1 := rfl
def remove_all : ℕ → bag → bag
| n [] := []
| n (x::xs) := if n = x then remove_all n xs else x :: remove_all n xs
lemma test_remove_all1 : count 5 (remove_all 5 [2,1,5,4,1]) = 0 := rfl
lemma test_remove_all2 : count 5 (remove_all 5 [2,1,4,1]) = 0 := rfl
lemma test_remove_all3 : count 4 (remove_all 5 [2,1,4,5,1,4]) = 2 := rfl
lemma test_remove_all4 :
count 5 (remove_all 5 [2,1,5,4,5,1,4,5,1,4]) = 0 := rfl
def bag.subset : bag → bag → bool
| [] [] := tt
| [] (y::ys) := tt
| (x::xs) [] := ff
| (x::xs) y := if bag.mem x y then bag.subset xs (remove_one x y) else ff
lemma test_subset1 : bag.subset [1,2] [2,1,4,1] = tt := rfl
lemma test_subset2 : bag.subset [1,2,2] [2,1,4,1] = ff := rfl
-- Exercise: 4 stars, advanced (rev_injective)
def rev : list ℕ → list ℕ
| nil := nil
| (x::xs) := (rev xs) ++ [x]
lemma test_rev1 : rev [3,2,1] = [1,2,3] := rfl
lemma test_rev2 : rev [] = [] := rfl
lemma rev_step : ∀ (hd : ℕ) (tl : list ℕ), rev (hd :: tl) = rev tl ++ [hd] :=
by intros; refl
lemma rev_distrib : ∀ l1 l2 : list ℕ, rev (l1 ++ l2) = rev l2 ++ rev l1 :=
begin
intros,
induction l1 with x xs ihl1,
induction l2 with y ys ihl2,
refl,
simp [rev],
induction l2 with y ys ihl2,
simp [rev],
{ simp [rev],
rw [ihl1, rev_step, ←cons_append],
simp * }
end
lemma rev_involutive : ∀ l : list ℕ, rev (rev l) = l
| nil := rfl
| (x::xs) := by simp [*, rev, rev_step, rev_distrib]
lemma rev_nil : rev nil = nil := rfl
lemma rev_singleton : ∀ n : ℕ, rev [n] = [n] := λ n, rfl
lemma ceqa (hd : ℕ) (tl : list ℕ) : hd :: tl = [hd] ++ tl := rfl
theorem rev_injective : function.injective rev :=
λ a b h, by rw [←rev_involutive a, ←rev_involutive b, h] |
// Copyright (c) 2014, Alexey Ivanov
#include "stdafx.h"
#include "rpc/request_handler.h"
#include "http_server/request_handler.h"
#include "rpc/value.h"
#include "rpc/method.h"
#include "rpc/exception.h"
#include "rpc/frontend.h"
#include "rpc/request_parser.h"
#include "rpc/response_serializer.h"
#include "utils/util.h"
#include <boost/foreach.hpp>
#include "plugin/logger.h"
namespace Rpc
{
namespace {
using namespace ControlPlugin::PluginLogger;
ModuleLoggerType& logger()
{ return getLogManager().getModuleLogger<Rpc::RequestHandler>(); }
}
const int kGENERAL_ERROR_CODE = -1;
void RequestHandler::addFrontend(std::auto_ptr<Frontend> frontend)
{
frontends_.push_back( frontend.release() );
}
Frontend* RequestHandler::getFrontEnd(const std::string& uri)
{
BOOST_FOREACH(Frontend& frontend, frontends_) {
if ( frontend.canHandleRequest(uri) ) {
return &frontend;
}
}
return nullptr;
}
Method* RequestHandler::getMethodByName(const std::string& name)
{
auto method_iterator = rpc_methods_.find(name);
if ( method_iterator != rpc_methods_.end() ) {
return method_iterator->second;
}
return nullptr;
}
void RequestHandler::addMethod(std::auto_ptr<Method> method)
{
std::string key( method->name() ); // boost::ptr_map::insert() needs reference to non-constant.
rpc_methods_.insert( key, method.release() );
}
boost::tribool RequestHandler::handleRequest(const std::string& request_uri,
const std::string& request_content,
Http::DelayedResponseSender_ptr delayed_response_sender,
Frontend& frontend,
std::string* response,
std::string* response_content_type
)
{
assert(response);
assert(response_content_type);
*response_content_type = frontend.responseSerializer().mimeType();
Value root_request;
if ( frontend.requestParser().parse(request_uri, request_content, &root_request) ) {
if ( !root_request.isMember("id") ) { // for example xmlrpc does not use request id, so add null value since Rpc methods rely on it.
root_request["id"] = Value::Null();
}
return callMethod(root_request,
delayed_response_sender,
frontend.responseSerializer(),
response
);
} else {
frontend.responseSerializer().serializeFault(root_request, "Request parsing error", Rpc::REQUEST_PARSING_ERROR, response);
return false;
}
}
boost::tribool RequestHandler::callMethod(const Value& root_request,
Http::DelayedResponseSender_ptr delayed_response_sender,
ResponseSerializer& response_serializer,
std::string* response
)
{
assert(response);
try {
const std::string& method_name = root_request["method"];
Method* method = getMethodByName(method_name);
if (method == nullptr) {
response_serializer.serializeFault(root_request, method_name + ": method not found", METHOD_NOT_FOUND_ERROR, response);
return false;
}
{ // execute method
//PROFILE_EXECUTION_TIME( method_name.c_str() );
active_delayed_response_sender_ = delayed_response_sender; // save current http request handler ref in weak ptr to use in delayed response.
active_response_serializer_ = &response_serializer;
Value root_response;
root_response["id"] = root_request["id"]; // currently all methods set id of response, so set it here. Method can set it to null if needed.
ResponseType response_type = method->execute(root_request, root_response);
if (RESPONSE_DELAYED == response_type) {
return boost::indeterminate; // method execution is delayed, say to http response handler not to send answer immediately.
} else {
assert( root_response.valid() ); ///??? Return empty string if execute() method did not set result.
if ( !root_response.valid() ) {
root_response = "";
}
response_serializer.serializeSuccess(root_response, response);
return true;
}
}
} catch (const Exception& e) {
response_serializer.serializeFault(root_request, e.message(), e.code(), response);
return false;
} catch (const std::exception& e) {
const char* method_name = root_request.isMember("method")
&& root_request["method"].type() == Rpc::Value::TYPE_STRING ? static_cast<const std::string&>(root_request["method"]).c_str()
: "unknown";
BOOST_LOG_SEV(logger(), error) << "RequestHandler::callMethod: call " << method_name << " method error. Reason: " << e.what();
response_serializer.serializeFault(root_request, "internal error", Rpc::INTERNAL_ERROR, response);
return false;
}
}
boost::shared_ptr<DelayedResponseSender> RequestHandler::getDelayedResponseSender() const
{
boost::shared_ptr<Http::DelayedResponseSender> ptr = active_delayed_response_sender_.lock();
if (ptr) {
return boost::make_shared<DelayedResponseSender>(ptr, *active_response_serializer_);
} else {
return boost::shared_ptr<DelayedResponseSender>();
}
}
void DelayedResponseSender::sendResponseSuccess(const Value& root_response)
{
std::string response;
response_serializer_.serializeSuccess(root_response, &response);
comet_http_response_sender_->send(response,
response_serializer_.mimeType()
);
}
void DelayedResponseSender::sendResponseFault(const Value& root_request, const std::string& error_msg, int error_code)
{
std::string response_string;
response_serializer_.serializeFault(root_request, error_msg, error_code, &response_string);
comet_http_response_sender_->send(response_string,
response_serializer_.mimeType()
);
}
} // namespace XmlRpc
|
import Data.Array.CArray
import Data.Complex
import Data.List (tails)
import Math.FFT (dft, idft)
convolution :: (Num a) => [a] -> [a] -> [a]
convolution x = map (sum . zipWith (*) (reverse x)) . spread
where
spread = init . tails . (replicate (length x - 1) 0 ++)
convolutionFFT :: [Complex Double] -> [Complex Double] -> [Complex Double]
convolutionFFT x y = elems $ idft $ liftArray2 (*) (fft x) (fft y)
where
fft a = dft $ listArray (1, length a) a
main :: IO ()
main = do
let x = [1, 2, 1, 2, 1]
y = [2, 1, 2, 1, 2]
print $ convolution x y
print $ convolutionFFT x y
|
-- Andreas, 2018-06-09, issue #2513, parsing attributes
postulate
fail : ∀ @0 A → A → A
-- Should fail.
|
module PCA.GPExample where
import Universum hiding (transpose, Vector)
import Data.Vector.Unboxed as V (fromList)
import Data.Array.Repa
import Numeric.LinearAlgebra.Repa hiding (Matrix, Vector)
import PCA.GaussianProcess
import PCA.Types
import PCA.Util
testList :: [Double]
testList = [ -5.0
, -4.79591837
, -4.59183673
, -4.3877551
, -4.18367347
, -3.97959184
, -3.7755102
, -3.57142857
, -3.36734694
, -3.16326531
, -2.95918367
, -2.75510204
, -2.55102041
, -2.34693878
, -2.14285714
, -1.93877551
, -1.73469388
, -1.53061224
, -1.32653061
, -1.12244898
, -0.91836735
, -0.71428571
, -0.51020408
, -0.30612245
, -0.10204082
, 0.10204082
, 0.30612245
, 0.51020408
, 0.71428571
, 0.91836735
, 1.12244898
, 1.32653061
, 1.53061224
, 1.73469388
, 1.93877551
, 2.14285714
, 2.34693878
, 2.55102041
, 2.75510204
, 2.95918367
, 3.16326531
, 3.36734694
, 3.57142857
, 3.7755102
, 3.97959184
, 4.18367347
, 4.3877551
, 4.59183673
, 4.79591837
, 5.0
]
xTest :: Vector D Double
xTest = delay $ fromUnboxed (Z :. 50) (V.fromList testList)
inputObserve :: InputObservations Double
inputObserve = InputObservations xTest
computeSD
:: Shape sh
=> Array D sh Double
-> Array U sh Double
computeSD = computeS @D @_ @_ @U
sqDist
:: Vector D Double
-> Vector D Double
-> Matrix D Double
sqDist vec1 vec2 = matrixSquare vec1 ++^ (transposeMatrix matrix2')
where
matrix2' = matrixSquare vec2 --^
((delay . smap ((*) 2)) $
matrix1 `mulS` matrix2)
matrixSquare matrix = smap flipExp matrix
flipExp = (flip (^)) 2
matrix1 = toMatrix' $ vec1
matrix2 = transposeMatrix . toMatrix' $ vec2
kernelFunction
:: Vector D Double
-> Vector D Double
-> Matrix D Double
kernelFunction matrix1 matrix2 =
smap fun $ sqDist matrix1 matrix2
where
fun = exp . ((*) (-0.5)) . ((*) (1/0.1))
xTrainList :: [Double]
xTrainList =
[ -4
, -3
, -2
, -1
, 1
]
xTrain :: Vector D Double
xTrain = delay $ fromUnboxed (Z :. 5) (V.fromList xTrainList)
yTrain :: Vector D Double
yTrain = smap sin xTrain
testTrainingData :: GPTrainingData Double
testTrainingData = GPTrainingData xTrain yTrain
k, kS, l, lK :: Matrix D Double
k = kernelFunction xTrain xTrain
kS = kernelFunction xTrain xTest
l = cholSH (k +^ (delay . smap (* 0.0005) $ identD 50))
lK = fromMaybe (error "izviniti") (delay <$> linearSolveS l kS)
testGaussianProcess :: GaussianProcess Double
testGaussianProcess = GaussianProcess kernelFunction
|
** Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
** See https://llvm.org/LICENSE.txt for license information.
** SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
* PARAMETER statements for LOGICAL constants. Also,
* constant folding of logical expressions.
implicit logical (a, o)
logical t1, t2, f1, f2
parameter (t1 = .true.)
parameter (f1 = .false., t2 = .not..false., f2 = .not.t1)
parameter (a1 = f1 .and. .false.,
+ a2 = a1 .and. .true. ,
+ a3 = .true..and..false.,
+ a4 = .true..and..true. )
parameter (o1 = f1 .or. f1,
+ o2 = f1 .or. t1,
+ o3 = t1 .or. f1,
+ o4 = t1 .or. t1 )
logical e1, e2, e3, e4, n1, n2, n3, n4
parameter (e1 = f1 .eqv. f1,
+ e2 = f1 .eqv. t1,
+ e3 = t1 .eqv. f1,
+ e4 = t1 .eqv. t1 )
parameter (n1 = f1 .neqv. f1,
+ n2 = f1 .neqv. t1,
+ n3 = t1 .neqv. f1,
+ n4 = t1 .neqv. t1 )
logical x1, x2, x3, x4
parameter(N = 24)
logical rslts(N), expect(N)
parameter( x1 = (.true. .and. .false.) .or. (.false. .eqv. f1) )
parameter(x2 = 3 .gt. 4 .or. 6 .eq. 1)
parameter(x3 = .not.f1.and.t1 .neqv. f1.or..false..or..false.)
parameter(x4 = .not. (2 .le. 3 .eqv. 78 .eq. 78) )
data expect / .true., .false., .true., .false.,
c tests 5 - 8: AND operation
+ .false., .false., .false., .true.,
c tests 9 - 12: OR operation
+ .false., .true., .true., .true.,
c tests 13 - 16: EQV operation
+ .true., .false., .false., .true.,
c tests 17 - 20: NEQV operation
+ .false., .true., .true., .false.,
c tests 21 - 24: miscellaneous combinations
+ .true., .false., .true., .false. /
data (rslts(i), i = 1, 16) / t1, f1, t2, f2,
+ a1, a2, a3, a4,
+ o1, o2, o3, o4,
+ e1, e2, e3, e4 /
data (rslts(i), i = 17, 20)/ n1, n2, n3, n4 /
rslts(21) = x1
rslts(22) = x2
rslts(23) = x3
rslts(24) = x4
if (x4) rslts(24) = .true.
call check(rslts, expect, N)
end
|
Formal statement is: lemma monom_eq_1 [simp]: "monom 1 0 = 1" Informal statement is: The monomial $x^0$ is equal to $1$. |
function [perimeterEdges,eulerCondition] = findLegalPerimeters2(mesh,perimDist)
% Calculate edges that on distinct perimeters perimDist mm from startVertex
%
% [perimeterEdges,eulerCondition] = findLegalPerimeters2(mesh,perimDist)
%
% Given a mesh structure (nodes, edges, distances from start point) and a
% threshold distance return a list of edges that constitute separate
% perimeters at a distance of perimDist from the start point.
%
% Note that because of intrinsic curvature, there can be more than one
% perimeter at the required distance. This routine makes sure that it
% returns separate perimeters (ones with no common nodes).
%
% Find perims with simple threshold
insideNodes = find(mesh.dist<=perimDist);
insideNodes = insideNodes(:);
% Some triangles have one or two vertices outside the perimeter. These
% triangles will not be included; any nodes that are within the perimeter
% but only part of these excluded triangles are removed here.
insideNodes = removeHangingNodes2(mesh,insideNodes);
% We could write a short piece of code that verifies these new nodes have
% no hanging nodes ...
numBadNodes = 1;
while (numBadNodes>0)
[perimeterEdges,eulerCondition] = findGroupPerimeter2(mesh,insideNodes);
length(perimeterEdges);
length(unique(perimeterEdges,'rows'));
fprintf('Euler number=%d\n',eulerCondition);
badPerimNodes = findBadPerimNodes2(mesh,perimeterEdges);
numBadNodes = length(badPerimNodes);
fprintf('There are %d bad perim nodes.\n',numBadNodes);
if(numBadNodes)
% Splits up joined perimeters
[insideNodes] = correctBadNodes2(mesh,insideNodes,badPerimNodes);
% Cleans up mesh again
insideNodes = removeHangingNodes2(mesh,insideNodes);
end
end
return;
|
import json
import numpy as np
#import cv2
cats = ['Car','DontCare']
cat_ids = {'DontCare':0,'Car':2}
DATASET_PATH = '/home/ubuntu/xwp/datasets/multi_view_dataset/new/fuse_test/cam9+cam21/'
DEBUG = False
# VAL_PATH = DATA_PATH + 'training/label_val/'
import os
ann_dir = DATASET_PATH + 'global_filtered/'
output_dir = DATASET_PATH + 'label_global_tracking/'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
ann_list = os.listdir(ann_dir)
ann_list.sort(key=lambda x:int(x[:-4]))
#calib_dir = DATASET_PATH + 'calib/'
# splits = ['trainval', 'test']
#calib_path = calib_dir + '000000.txt'
#calib = read_clib(calib_path)
out_path = output_dir + '{}'.format('0000.txt')
f = open(out_path, 'w')
for label_file in ann_list:
ann_path = ann_dir + '{}'.format(label_file)
anns = open(ann_path, 'r')
frame = int(label_file[:-4])
if frame < 901:
continue
frame = frame - 901
for ann_ind, txt in enumerate(anns):
tmp = txt[:-1].split(' ')
cat_id = cat_ids[tmp[0]]
truncated = int(float(tmp[1]))
occluded = int(tmp[2])
alpha = float(tmp[3])
bbox = [float(tmp[4]), float(tmp[5]), float(tmp[6]), float(tmp[7])]
dim = [float(tmp[8]), float(tmp[9]), float(tmp[10])]
location = [float(tmp[11]), float(tmp[12]), float(tmp[13])]
rotation_y = float(tmp[14])
car_id = int(tmp[15])
#rotation = rotation_y * np.pi / 180
#box_3d = compute_box_3d(dim, location, rotation_y)
#box_2d = project_to_image(box_3d, calib)
#bbox = (np.min(box_2d[:,0]), np.min(box_2d[:,1]), np.max(box_2d[:,0]), np.max(box_2d[:,1]))
txt="{} {} {} {} {} {} {} {} {} {} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f} {}\n".format(frame,car_id,'Car', 0, 0,0, 0, 0, 0,0, dim[0], dim[1],
dim[2],location[1], -location[2], location[0], rotation_y)
# txt="{},{},{},{},{},{},{},{:.4f},{:.4f},{:.4f},{:.4f},{:.4f},{:.4f},{},{} \n".format(frame,2,0,0,0,0,score,
# dim[0],dim[1],dim[2],location[1],-location[2],location[0],rotation_y,0)
f.write(txt)
#f.write('\n')
f.close()
print('finish!') |
(* Title: The Relational Method with Message Anonymity for the Verification of Cryptographic Protocols
Author: Pasquale Noce
Software Engineer at HID Global, Italy
pasquale dot noce dot lavoro at gmail dot com
pasquale dot noce at hidglobal dot com
*)
section "The relational method and message anonymity"
theory Definitions
imports Main
begin
text \<open>
\null
\emph{This paper is dedicated to my mother, my favourite chess opponent -- in addition to being many
other wonderful things!}
\<close>
subsection "Introduction"
text \<open>
As Bertrand Russell says in the last pages of \emph{A History of Western Philosophy}, a distinctive
feature of science is that "we can make successive approximations to the truth, in which each new
stage results from an improvement, not a rejection, of what has gone before". When dealing with a
formal verification method for information processing systems, such as Paulson's inductive method
for the verification of cryptographic protocols (cf. @{cite "Paulson98"}, @{cite "Paulson20"}), a
more modest goal for this iterative improvement process, yet of significant practical importance, is
to streamline the definitions and proofs needed to model such a system and verify its properties.
With this aim, specially when it comes to verifying protocols using public key cryptography, this
paper proposes an enhancement of the inductive method, named \emph{relational method} for reasons
clarified in what follows, and puts it into practice by verifying a sample protocol. This new method
is the result of some changes to the way how events, states, spy's capabilities, and the protocol
itself are formalized in the inductive method. Here below is a description of these changes, along
with a rationale for them.
\<^descr>[Events.] In the inductive method, the fundamental building blocks of cryptographic protocols are
events of the form @{text "Says A B X"}, where @{text X} is a message being exchanged, @{text A} is
the agent that sends it, and @{text B} is the agent to which it is addressed.
\\However, any exchanged message can be intercepted by the spy and forwarded to any other agent, so
its intended recipient is not relevant for the protocol \emph{security} correctness -- though of
course being relevant for the protocol \emph{functional} correctness. Moreover, a legitimate agent
may also generate messages, e.g. ephemeral private keys, that she will never exchange with any other
agent. To model such an event, a datatype constructor other than @{text Says} should be used. How to
make things simpler?
\\The solution adopted in the relational method is to model events just as ordered pairs of the form
@{text "(A, X)"}, where @{text A} is an agent and @{text X} is a message. If event @{text "(A, X)"}
stands for @{text A}'s sending of @{text X} to another agent, where @{text A} is a legitimate agent,
then this event will be accompanied by event @{text "(Spy, X)"}, representing the spy's interception
of @{text X}. If event @{text "(A, X)"} rather stands for @{text A}'s generation of private message
@{text X}, e.g. an ephemeral private key, for her own exclusive use -- and if the spy has not hacked
@{text A} so as to steal her private messages as well --, then no companion event @{text "(Spy, X)"}
will occur instead.
\<^descr>[States.] In the inductive method, the possible states of a cryptographic protocol are modeled as
event \emph{traces}, i.e. lists, and the protocol itself is formalized as a set of such traces.
Consequently, the protocol rules and security properties are expressed as formulae satisfied by any
event trace @{text evs} belonging to this set.
\\However, these formulae are such that their truth values depend only on the events contained in
@{text evs}, rather than on the actual order in which they occur -- in fact, robust protocol rules
and security properties cannot depend on the exact sequence of message exchanges in a scenario where
the spy can freely intercept and forward messages, or even generate and send her own ones. Thus, one
library function, @{const set}, and two custom recursive functions, @{text used} and @{text knows},
are needed to convert event traces into event sets and message sets, respectively.
\\In the relational method, protocol states are simply modeled as event sets, so that the occurrence
of event @{text "(A, X)"} in state @{text s} can be expressed as the transition to the augmented
state @{term "insert (A, X) s"}. Hence, states consist of relations between agents and messages. As
a result, function @{const set} need not be used any longer, whereas functions @{text used} and
@{text spied} -- the latter one being a replacement for @{text "knows Spy"} --, which take a state
@{text s} as input, are mere abbreviations for @{term "Range s"} and @{term "s `` {Spy}"}.
\<^descr>[Spy's capabilities.] In the inductive method, the spy's attack capabilities are formalized via
two inductively defined functions, @{text analz} and @{text synth}, used to construct the sets of
all the messages that the spy can learn -- @{text "analz (knows Spy evs)"} -- and send to legitimate
agents -- @{text "synth (analz (knows Spy evs))"} -- downstream of event trace @{text evs}.
\\Indeed, the introduction of these functions goes in the direction of decoupling the formalization
of the spy's capabilities from that of the protocol itself, consistently with the fact that what the
spy can do is independent of how the protocol works -- which only matters when it comes to verifying
protocol security.
\\In principle, this promises to provide a relevant benefit: these functions need to be defined, and
their properties to be proven, just once, whereupon such definitions and properties can be reused in
the formalization and verification of whatever protocol.
\\In practice, since both functions are of type @{text "msg set \<Rightarrow> msg set"}, where @{text msg} is
the datatype defining all possible message formats, this benefit only applies as long as message
formats remain unchanged. However, when it comes to verifying a protocol making use of public key
cryptography, some new message format, and consequently some new related spy's capability as well,
are likely to be required. An example of this will be provided right away by the protocol considered
in this paper.
\\In the relational method, the representation of events as agent-message pairs offers a simpler way
to model the spy's capabilities, namely as supplementary protocol rules, analogous to the inductive
method's @{text Fake} rule, augmenting a state by one or more events of the form @{text "(Spy, X)"}.
In addition to eliminating the need for functions @{text analz} and @{text synth} -- which, in light
of the above considerations, does not significantly harm reusability --, this choice also abolishes
any distinction between what the spy can learn and what she can send. In fact, a state containing
event @{text "(Spy, X)"} is interpreted as one where the spy both knows message @{text X} and may
have sent it to whatever legitimate agent. Actually, this formalizes the facts that a real-world
attacker is free to send any message she has learned to any other party, and conversely to use any
message she has generated to further augment her knowledge.
\\In the inductive method, the former fact is modeled by property @{term "H \<subseteq> synth H"} of function
@{text synth}, but the latter one has no formal counterpart, as in general @{term "H \<subset> synth H"}.
This limitation on the spy's capabilities is not significant as long as the protocol makes use of
static keys only, but it is if session keys or ephemeral key pairs are generated -- as happens in
key establishment protocols, even in those using symmetric cryptography alone. In any such case, a
realistic spy must also be able to learn from anything she herself has generated, such as a nonce or
an ephemeral private key -- a result achieved without effort in the relational method.
\\An additional, nontrivial problem for the inductive method is that many protocols, including key
establishment ones, require the spy to be able to generate \emph{fresh} ephemeral messages only, as
otherwise the spy could succeed in breaking the protocol by just guessing the ephemeral messages
already generated at random by some legitimate agent -- a quite unrealistic attack pattern, provided
that such messages vary in a sufficiently wide range. At first glance, this need could be addressed
by extending the inductive definition of function @{text synth} with introduction rules of the form
@{term "Nonce n \<notin> H \<Longrightarrow> Nonce n \<in> synth H"} or @{term "PriKey A \<notin> H \<Longrightarrow> PriKey A \<in> synth H"}.
However, private ephemeral messages are not in general included in @{text "analz (knows Spy evs)"},
since nonces may be encrypted with uncompromised keys when exchanged and private keys are usually
not exchanged at all, so this approach would not work. The only satisfactory alternative would be to
change the signature of function @{text synth}, e.g. by adding a second input message set @{text H'}
standing for @{text "used evs"}, or else by replacing @{text H} with event trace @{text evs} itself,
but this would render the function definition much more convoluted -- a problem easily bypassed in
the relational method.
\<^descr>[Protocol.] In the inductive method, a cryptographic protocol consists of an inductively defined
set of event traces. This enables to prove the protocol security properties by induction using the
induction rule automatically generated as a result of such an inductive definition, i.e. by means of
\emph{rule induction}. Actually, this feature is exactly what gives the method its very name. Hence,
a consistent way to name a protocol verification method using some other form of induction would be
to replace adjective "inductive" with another one referring to that form of induction.
\\The relational method owes its name to this consideration. In this method, the introduction rules
defining \emph{protocol rules}, i.e. the possible transitions between protocol states, are replaced
with \emph{relations} between states, henceforth named \emph{protocol relations}. That is, for any
two states @{text s} and @{text s'}, there exists a transition leading from @{text s} to @{text s'}
just in case the ordered pair @{term "(s, s')"} is contained in at least one protocol relation --
a state of affairs denoted using infix notation @{text "s \<turnstile> s'"}. Then, the inductively defined set
itself is replaced with the \emph{reflexive transitive closure} of the union of protocol relations.
Namely, any state @{text s} may be reached from \emph{initial state} @{text s\<^sub>0}, viz. is a possible
protocol state, just in case pair @{term "(s\<^sub>0, s)"} lies within this reflexive transitive closure --
a state of affairs denoted using infix notation @{text "s\<^sub>0 \<Turnstile> s"}. As a result, rule induction is
replaced with induction over reflexive transitive closures via rule @{thm [source] rtrancl_induct},
which is the circumstance that originates the method name.
\\These changes provide the following important benefits.
\<^item> Inserting and modifying the formal definition of a protocol is much more comfortable. In fact,
any change even to a single introduction rule within a monolithic inductive set definition entails a
re-evaluation of the whole definition, whereas each protocol relation will have its own stand-alone
definition, which also makes it easier to find errors. This advantage may go almost unnoticed for a
very simple protocol providing for just a few protocol rules, but gets evident in case of a complex
protocol. An example of this will be provided by the protocol considered in this paper: when looking
at the self-contained abbreviations used to define protocol relations, the reader will easily grasp
how much more convoluted an equivalent inductive set definition would have been.
\<^item> In addition to induction via rule @{thm [source] rtrancl_induct}, a further powerful reasoning
pattern turns out to be available. It is based on the following general rule applying to reflexive
transitive closures (indeed, a rule so general and useful that it could rightfully become part of
the standard library), later on proven and assigned the name @{text rtrancl_start}:
@{prop [display] "\<lbrakk>(x, y) \<in> r\<^sup>*; P y; \<not> P x\<rbrakk> \<Longrightarrow>
\<exists>u v. (x, u) \<in> r\<^sup>* \<and> (u, v) \<in> r \<and> (v, y) \<in> r\<^sup>* \<and> \<not> P u \<and> P v"}
In natural language, this rule states that for any chain of elements linked by a relation, if some
predicate is false for the first element of the chain and true for the last one, there must exist a
link in the chain where the predicate becomes true.
\\This rule can be used to prove propositions of the form @{text "\<lbrakk>s \<Turnstile> s'; P s'[; Q]\<rbrakk> \<Longrightarrow> R s'"} for
any state @{text s} and predicate @{text P} such that @{term "\<not> P s"}, with an optional additional
assumption @{text Q}, without resorting to induction. Notably, \emph{regularity lemmas} have exactly
this form, where @{term "s = s\<^sub>0"}, @{term "P = (\<lambda>s. X \<in> parts (used s))"} for some term @{text X} of
type @{text msg}, and @{text Q}, if present, puts some constraint on @{text X} or its components.
\\Such a proof consists of two steps. First, lemma @{text "\<lbrakk>s \<turnstile> s'; P s'; \<not> P s[; Q]\<rbrakk> \<Longrightarrow> R s'"} is
proven by simplification, using the definitions of protocol relations. Then, the target proposition
is proven by applying rule @{text rtrancl_start} as a destruction rule (cf. @{cite "Paulson20"}) and
proving @{term "P s'"} by assumption, @{term "\<not> P s"} by simplification, and the residual subgoal
by means of the previous lemma.
In addition to the relational method, this paper is aimed at introducing still another enhancement:
besides message confidentiality and authenticity, it takes into consideration a further important
security property, \emph{message anonymity}. Being legitimate agents identified via natural numbers,
the fact that in state @{text s} the spy ignores that message @{text X\<^sub>n} is associated with agent
@{text n}, viz. @{text X\<^sub>n}'s property of being \emph{anonymous} in state @{text s}, can be expressed
as @{text "\<langle>n, X\<^sub>n\<rangle> \<notin> spied s"}, where notation @{text "\<langle>n, X\<^sub>n\<rangle>"} refers to a new constructor added to
datatype @{text msg} precisely for this purpose.
A basic constraint upon any protocol relation augmenting the spy's knowledge with @{text "\<langle>n, X\<rangle>"}
is that the spy must know message @{text X} in the current state, as it is impossible to identify
the agent associated with an unknown message. There is also an additional, more subtle constraint.
Any such protocol relation either augments a state in which the spy knows @{text "\<langle>n, C X\<^sub>1 \<dots> X\<^sub>m\<rangle>"},
i.e. containing event @{text "(Spy, \<langle>n, C X\<^sub>1 \<dots> X\<^sub>m\<rangle>)"}, with event @{text "(Spy, \<langle>n, X\<^sub>i\<rangle>)"}, where
$1 \leq i \leq m$ and @{text C} is some constructor of datatype @{text msg}, or conversely augments
a state containing event @{text "(Spy, \<langle>n, X\<^sub>i\<rangle>)"} with @{text "(Spy, \<langle>n, C X\<^sub>1 \<dots> X\<^sub>m\<rangle>)"}. However, the
latter spy's inference is justified only if the compound message @{text "C X\<^sub>1 \<dots> X\<^sub>m"} is part of a
message generated or accepted by some legitimate agent according to the protocol rules. Otherwise,
that is, if @{text "C X\<^sub>1 \<dots> X\<^sub>m"} were just a message generated at random by the spy, her inference
would be as sound as those of most politicians and all advertisements: even if the conclusion were
true, it would be so by pure chance.
This problem can be solved as follows.
\<^item> A further constructor @{text Log}, taking a message as input, is added to datatype @{text msg},
and every protocol relation modeling the generation or acceptance of a message @{text X} by some
legitimate agent must augment the current state with event @{term "(Spy, Log X)"}.
\\In this way, the set of all the messages that have been generated or accepted by some legitimate
agent in state @{text s} matches @{term "Log -` spied s"}.
\<^item> A function @{text crypts} is defined inductively. It takes a message set @{text H} as input, and
returns the least message set @{text H'} such that @{term "H \<subseteq> H'"} and for any (even empty) list
of keys @{text KS}, if the encryption of @{text "\<lbrace>X, Y\<rbrace>"}, @{text "\<lbrace>Y, X\<rbrace>"}, or @{text "Hash X"}
with @{text KS} is contained in @{text H'}, then the encryption of @{text X} with @{text KS} is
contained in @{text H'} as well.
\\In this way, the set of all the messages that are part of messages exchanged by legitimate agents,
viz. that may be mapped to agents, in state @{text s} matches @{term "crypts (Log -` spied s)"}.
\<^item> Another function @{text key_sets} is defined, too. It takes two inputs, a message @{text X} and
a message set @{text H}, and returns the set of the sets of @{text KS}' inverse keys for any list of
keys @{text KS} such that the encryption of @{text X} with @{text KS} is included in @{text H}.
\\In this way, the fact that in state @{text s} the spy can map a compound message @{text X} to some
agent, provided that she knows all the keys in set @{text U}, can be expressed through conditions
@{term "U \<in> key_sets X (crypts (Log -` spied s))"} and @{term "U \<subseteq> spied s"}.
\\The choice to define @{text key_sets} so as to collect the inverse keys of encryption keys, viz.
decryption ones, depends on the fact that the sample protocol verified in this paper uses symmetric
keys alone -- which match their own inverse keys -- for encryption, whereas asymmetric key pairs are
used in cryptograms only for signature generation -- so that the inverse keys are public ones. In
case of a protocol (also) using public keys for encryption, encryption keys themselves should (also)
be collected, since the corresponding decryption keys, i.e. private keys, would be unknown to the
spy by default. This would formalize the fact that encrypted messages can be mapped to agents not
only by decrypting them, but also by recomputing the cryptograms (provided that the plaintexts are
known) and checking whether they match the exchanged ones.
\<close>
subsection "A sample protocol"
text \<open>
As previously mentioned, this paper tries the relational method, including message anonymity, by
applying it to the verification of a sample authentication protocol in which Password Authenticated
Connection Establishment (PACE) with Chip Authentication Mapping (cf. @{cite "ICAO15"}) is first
used by an \emph{owner} to establish a secure channel with her own \emph{asset} and authenticate it,
and then the owner sends a password (other than the PACE one) to the asset over that channel so as
to authenticate herself. This enables to achieve a reliable mutual authentication even if the PACE
key is shared by multiple owners or is weak, as happens in electronic passports. Although the PACE
mechanism is specified for use in electronic documents, nothing prevents it in principle from being
used in other kinds of smart cards or even outside of the smart card world, which is the reason why
this paper uses the generic names \emph{asset} and \emph{owner} for the card and the cardholder,
respectively.
In more detail, this protocol provides for the following steps. In this list, messages are specified
using the same syntax that will be adopted in the formal text (for further information about PACE
with Chip Authentication Mapping, cf. @{cite "ICAO15"}).
\<^enum> \emph{Asset n} $\rightarrow$ \emph{Owner n}:
\\\hspace*{1em}@{text "Crypt (Auth_ShaKey n) (PriKey S)"}
\<^enum> \emph{Owner n} $\rightarrow$ \emph{Asset n}:
\\\hspace*{1em}@{text "\<lbrace>Num 1, PubKey A\<rbrace>"}
\<^enum> \emph{Asset n} $\rightarrow$ \emph{Owner n}:
\\\hspace*{1em}@{text "\<lbrace>Num 2, PubKey B\<rbrace>"}
\<^enum> \emph{Owner n} $\rightarrow$ \emph{Asset n}:
\\\hspace*{1em}@{text "\<lbrace>Num 3, PubKey C\<rbrace>"}
\<^enum> \emph{Asset n} $\rightarrow$ \emph{Owner n}:
\\\hspace*{1em}@{text "\<lbrace>Num 4, PubKey D\<rbrace>"}
\<^enum> \emph{Owner n} $\rightarrow$ \emph{Asset n}:
\\\hspace*{1em}@{text "Crypt (SesK SK) (PubKey D)"}
\<^enum> \emph{Asset n} $\rightarrow$ \emph{Owner n}:
\\\hspace*{1em}@{text "\<lbrace>Crypt (SesK SK) (PubKey C),"}
\\\hspace*{1.5em}@{text "Crypt (SesK SK) (Auth_PriK n \<otimes> B),"}
\\\hspace*{1.5em}@{text "Crypt (SesK SK) (Crypt SigK"}
\\\hspace*{2em}@{text "\<lbrace>Hash (Agent n), Hash (Auth_PubKey n)\<rbrace>)\<rbrace>"}
\<^enum> \emph{Owner n} $\rightarrow$ \emph{Asset n}:
\\\hspace*{1em}@{text "Crypt (SesK SK) (Pwd n)"}
\<^enum> \emph{Asset n} $\rightarrow$ \emph{Owner n}:
\\\hspace*{1em}@{text "Crypt (SesK SK) (Num 0)"}
Legitimate agents consist of an infinite population of assets and owners. For each natural number
@{text n}, @{text "Owner n"} is an owner and @{text "Asset n"} is her own asset, and these agents
are assigned the following authentication data.
\<^item> @{text "Key (Auth_ShaKey n)"}: static symmetric PACE key shared by both agents.
\<^item> @{text "Auth_PriKey n"}, @{text "Auth_PubKey n"}: static private and public keys stored on
@{text "Asset n"} and used for @{text "Asset n"}'s authentication via Chip Authentication Mapping.
\<^item> @{text "Pwd n"}: unique password (other than the PACE one) shared by both agents and used for
@{text "Owner n"}'s authentication.
Function @{text Pwd} is defined as a constructor of datatype @{text msg} and then is injective,
which formalizes the assumption that each asset-owner pair has a distinct password, whereas no such
constraint is put on functions @{text Auth_ShaKey}, @{text Auth_PriKey}, and @{text Auth_PubKey},
which allows multiple asset-owner pairs to be assigned the same keys. On the other hand, function
@{text Auth_PriKey} is constrained to be such that the complement of its range is infinite. As each
protocol run requires the generation of fresh ephemeral private keys, this constraint ensures that
an unbounded number of protocol runs can be carried out. All assumptions are formalized by applying
the definitional approach, viz. without introducing any axiom, and so is this constraint, expressed
by defining function @{text Auth_PriKey} using the indefinite description operator @{text SOME}.
The protocol starts with @{text "Asset n"} sending an ephemeral private key encrypted with the PACE
key to @{text "Owner n"}. Actually, if @{text "Asset n"} is a smart card, the protocol should rather
start with @{text "Owner n"} sending a plain request for such encrypted nonce, but this preliminary
step is omitted here as it is irrelevant for protocol security. After that, @{text "Owner n"} and
@{text "Asset n"} generate two ephemeral key pairs each and send the respective public keys to the
other party.
Then, both parties agree on the same session key by deriving it from the ephemeral keys generated
previously (actually, two distinct session keys would be derived, one for encryption and the other
one for MAC computation, but such a level of detail is unnecessary for protocol verification). The
session key is modeled as @{text "Key (SesK SK)"}, where @{text SesK} is an apposite constructor
added to datatype @{text key} and @{term "SK = (Some S, {A, B}, {C, D})"}. The adoption of type
@{typ "nat option"} for the first component enables to represent as @{term "(None, {A, B}, {C, D})"}
the wrong session key derived from @{text "Owner n"} if @{text "PriKey S"} was encrypted using a key
other than @{text "Key (Auth_ShaKey n)"} -- which reflects the fact that the protocol goes on even
without the two parties sharing the same session key. The use of type @{typ "nat set"} for the other
two components enables the spy to compute @{text "Key (SesK SK)"} if she knows \emph{either} private
key and the other public key referenced by each set, as long as she also knows @{text "PriKey S"} --
which reflects the fact that given two key pairs, Diffie-Hellman key agreement generates the same
shared secret independently of which of the respective private keys is used for computation.
This session key is used by both parties to compute their authentication tokens. Both encrypt the
other party's second ephemeral public key, but @{text "Asset n"} appends two further fields: the
Encrypted Chip Authentication Data, as provided for by Chip Authentication Mapping, and an encrypted
signature of the hash values of @{text "Agent n"} and @{text "Auth_PubKey n"}. Infix notation
@{text "Auth_PriK n \<otimes> B"} refers to a constructor of datatype @{text msg} standing for plain Chip
Authentication Data, and @{text Agent} is another such constructor standing for agent identification
data. @{text "Owner n"} is expected to validate this signature by also checking @{text "Agent n"}'s
hash value against reference identification data known by other means -- otherwise, the spy would
not be forced to know @{text "Auth_PriKey n"} to masquerade as @{text "Asset n"}, since she could do
that by just knowing @{text "Auth_PriKey m"} for some other @{text m}, even if @{term "Auth_PriKey m
\<noteq> Auth_PriKey n"}. If @{text "Asset n"} is an electronic passport, the owner, i.e. the inspection
system, could get cardholder's identification data by reading her personal data on the booklet, and
such a signature could be retrieved from the chip (actually through a distinct message, but this is
irrelevant for protocol security as long as the password is sent after the signature's validation)
by reading the Document Security Object -- provided that @{text "Auth_PubKey n"} is included within
Data Group 14.
The protocol ends with @{text "Owner n"} sending her password, encrypted with the session key, to
@{text "Asset n"}, who validates it and replies with an encrypted acknowledgment.
Here below are some concluding remarks about the way how this sample protocol is formalized.
\<^item> A single signature private key, unknown to the spy, is assumed to be used for all legitimate
agents. Similarly, the spy might have hacked some legitimate agent so as to steal her ephemeral
private keys as soon as they are generated, but here all legitimate agents are assumed to be out of
the spy's reach in this respect. Of course, this is just the choice of one of multiple possible
scenarios, and nothing prevents these assumptions from being dropped.
\<^item> In the real world, a legitimate agent would use any one of her ephemeral private keys just once,
after which the key would be destroyed. On the contrary, no such constraint is enforced here, since
it turns out to be unnecessary for protocol verification. There is a single exception, required for
the proof of a unicity lemma: after @{text "Asset n"} has used @{text "PriKey B"} to compute her
authentication token, she must discard @{text "PriKey B"} so as not to use this key any longer. The
way how this requirement is expressed emphasizes once more the flexibility of the modeling of events
in the relational method: @{text "Asset n"} may use @{text "PriKey B"} in this computation only if
event @{text "(Asset n, PubKey B)"} is not yet contained in the current state @{text s}, and then
@{text s} is augmented with that event. Namely, events can also be used to model garbage collection!
\<^item> The sets of the legitimate agents whose authentication data have been identified in advance (or
equivalently, by means other than attacking the protocol, e.g. by social engineering) by the spy are
defined consistently with the constraint that known data alone can be mapped to agents, as well as
with the definition of initial state @{text s\<^sub>0}. For instance, the set @{text bad_id_prikey} of the
agents whose Chip Authentication private keys have been identified is defined as a subset of the set
@{text bad_prikey} of the agents whose Chip Authentication private keys have been stolen. Moreover,
all the signatures included in assets' authentication tokens are assumed to be already known to the
spy in state @{text s\<^sub>0}, so that @{text bad_id_prikey} includes also any agent whose identification
data or Chip Authentication public key have been identified in advance.
\<^item> The protocol rules augmenting the spy's knowledge with some message of the form @{text "\<langle>n, X\<rangle>"}
generally require the spy to already know some other message of the same form. There is just one
exception: the spy can infer @{text "\<langle>n, Agent n\<rangle>"} from @{text "Agent n"}. This expresses the fact
that the detection of identification data within a message generated or accepted by some legitimate
agent is in itself sufficient to map any known component of that message to the identified agent,
regardless of whether any data were already mapped to that agent in advance.
\<^item> As opposed to what happens for constructors @{text "(\<otimes>)"} and @{text "MPair"}, there do not
exist two protocol rules enabling the spy to infer @{text "\<langle>n, Crypt K X\<rangle>"} from @{text "\<langle>n, X\<rangle>"} or
@{text "\<langle>n, Key K\<rangle>"} and vice versa. A single protocol rule is rather defined, which enables the spy
to infer @{text "\<langle>n, X\<rangle>"} from @{text "\<langle>n, Key K\<rangle>"} or vice versa, provided that @{text "Crypt K X"}
has been exchanged by some legitimate agent. In fact, the protocol provides for just one compound
message made up of cryptograms, i.e. the asset's authentication token, and all these cryptograms are
generated using the same encryption key @{text "Key (SesK SK)"}. Thus, if two such cryptograms have
plaintexts @{text X\<^sub>1}, @{text X\<^sub>2} and the spy knows @{text "\<langle>n, X\<^sub>1\<rangle>"}, she can infer @{text "\<langle>n, X\<^sub>2\<rangle>"}
by inferring @{text "\<langle>n, Key (SesK SK)\<rangle>"}, viz. she need not know @{text "\<langle>n, Crypt (SesK SK) X\<^sub>1\<rangle>"}
to do that.
The formal content is split into the following sections.
\<^item> Section \ref{Definitions}, \emph{Definitions}, contains all the definitions needed to formalize
the sample protocol by means of the relational method, including message anonymity.
\<^item> Section \ref{Authentication}, \emph{Confidentiality and authenticity properties}, proves that
the following theorems hold under appropriate assumptions.
\<^enum> Theorem @{text sigkey_secret}: the signature private key is secret.
\<^enum> Theorem @{text auth_shakey_secret}: an asset-owner pair's PACE key is secret.
\<^enum> Theorem @{text auth_prikey_secret}: an asset's Chip Authentication private key is secret.
\<^enum> Theorem @{text owner_seskey_unique}: an owner's session key is unknown to other owners.
\<^enum> Theorem @{text owner_seskey_secret}: an owner's session key is secret.
\<^enum> Theorem @{text owner_num_genuine}: the encrypted acknowledgment received by an owner has been
sent by the respective asset.
\<^enum> Theorem @{text owner_token_genuine}: the PACE authentication token received by an owner has
been generated by the respective asset, using her Chip Authentication private key and the same
ephemeral keys used to derive the session key.
\<^enum> Theorem @{text pwd_secret}: an asset-owner pair's password is secret.
\<^enum> Theorem @{text asset_seskey_unique}: an asset's session key is unknown to other assets, and
may be used by that asset to compute just one PACE authentication token.
\<^enum> Theorem @{text asset_seskey_secret}: an asset's session key is secret.
\<^enum> Theorem @{text asset_pwd_genuine}: the encrypted password received by an asset has been sent
by the respective owner.
\<^enum> Theorem @{text asset_token_genuine}: the PACE authentication token received by an asset has
been generated by the respective owner, using the same ephemeral key used to derive the session key.
Particularly, these proofs confirm that the mutual authentication between an owner and her asset
is reliable even if their PACE key is compromised, unless either their Chip Authentication private
key or their password also is -- namely, the protocol succeeds in implementing a two-factor mutual
authentication.
\<^item> Section \ref{Anonymity}, \emph{Anonymity properties}, proves that the following theorems hold
under appropriate assumptions.
\<^enum> Theorem @{text pwd_anonymous}: an asset-owner pair's password is anonymous.
\<^enum> Theorem @{text auth_prikey_anonymous}: an asset's Chip Authentication private key is
anonymous.
\<^enum> Theorem @{text auth_shakey_anonymous}: an asset-owner pair's PACE key is anonymous.
\<^item> Section \ref{Possibility}, \emph{Possibility properties}, shows how possibility properties (cf.
@{cite "Paulson98"}) can be proven by constructing sample protocol runs, either ordinary or attack
ones. Two such properties are proven:
\<^enum> Theorem @{text runs_unbounded}: for any possible protocol state @{text s} and any asset-owner
pair, there exists a state @{text s'} reachable from @{text s} in which a protocol run has been
completed by those agents using an ephemeral private key @{text "PriKey S"} not yet exchanged in
@{text s} -- namely, an unbounded number of protocol runs can be carried out by legitimate agents.
\<^enum> Theorem @{text pwd_compromised}: in a scenario not satisfying the assumptions of theorem
@{text pwd_anonymous}, the spy can steal an asset-owner pair's password and even identify those
agents.
The latter is an example of a possibility property aimed at confirming that the assumptions of a
given confidentiality, authenticity, or anonymity property are necessary for it to hold.
For further information about the formal definitions and proofs contained in these sections, see
Isabelle documentation, particularly @{cite "Paulson20"}, @{cite "Nipkow20"}, @{cite "Krauss20"},
and @{cite "Nipkow11"}.
\textbf{Important note.} This sample protocol was already considered in a former paper of mine (cf.
@{cite "Noce17"}). For any purpose, that paper should be regarded as being obsolete and superseded
by the present paper.
\<close>
subsection "Definitions"
text \<open>
\label{Definitions}
\<close>
type_synonym agent_id = nat
type_synonym key_id = nat
type_synonym seskey_in = "key_id option \<times> key_id set \<times> key_id set"
datatype agent =
Asset agent_id |
Owner agent_id |
Spy
datatype key =
SigK |
VerK |
PriK key_id |
PubK key_id |
ShaK key_id |
SesK seskey_in
datatype msg =
Num nat |
Agent agent_id |
Pwd agent_id |
Key key |
Mult key_id key_id (infixl "\<otimes>" 70) |
Hash msg |
Crypt key msg |
MPair msg msg |
IDInfo agent_id msg |
Log msg
syntax
"_MPair" :: "['a, args] \<Rightarrow> 'a * 'b" ("(2\<lbrace>_,/ _\<rbrace>)")
"_IDInfo" :: "[agent_id, msg] \<Rightarrow> msg" ("(2\<langle>_,/ _\<rangle>)")
translations
"\<lbrace>X, Y, Z\<rbrace>" \<rightleftharpoons> "\<lbrace>X, \<lbrace>Y, Z\<rbrace>\<rbrace>"
"\<lbrace>X, Y\<rbrace>" \<rightleftharpoons> "CONST MPair X Y"
"\<langle>n, X\<rangle>" \<rightleftharpoons> "CONST IDInfo n X"
abbreviation SigKey :: "msg" where
"SigKey \<equiv> Key SigK"
abbreviation VerKey :: "msg" where
"VerKey \<equiv> Key VerK"
abbreviation PriKey :: "key_id \<Rightarrow> msg" where
"PriKey \<equiv> Key \<circ> PriK"
abbreviation PubKey :: "key_id \<Rightarrow> msg" where
"PubKey \<equiv> Key \<circ> PubK"
abbreviation ShaKey :: "key_id \<Rightarrow> msg" where
"ShaKey \<equiv> Key \<circ> ShaK"
abbreviation SesKey :: "seskey_in \<Rightarrow> msg" where
"SesKey \<equiv> Key \<circ> SesK"
primrec InvK :: "key \<Rightarrow> key" where
"InvK SigK = VerK" |
"InvK VerK = SigK" |
"InvK (PriK A) = PubK A" |
"InvK (PubK A) = PriK A" |
"InvK (ShaK SK) = ShaK SK" |
"InvK (SesK SK) = SesK SK"
abbreviation InvKey :: "key \<Rightarrow> msg" where
"InvKey \<equiv> Key \<circ> InvK"
inductive_set parts :: "msg set \<Rightarrow> msg set"
for H :: "msg set" where
parts_used [intro]:
"X \<in> H \<Longrightarrow> X \<in> parts H" |
parts_crypt [intro]:
"Crypt K X \<in> parts H \<Longrightarrow> X \<in> parts H" |
parts_fst [intro]:
"\<lbrace>X, Y\<rbrace> \<in> parts H \<Longrightarrow> X \<in> parts H" |
parts_snd [intro]:
"\<lbrace>X, Y\<rbrace> \<in> parts H \<Longrightarrow> Y \<in> parts H"
inductive_set crypts :: "msg set \<Rightarrow> msg set"
for H :: "msg set" where
crypts_used [intro]:
"X \<in> H \<Longrightarrow> X \<in> crypts H" |
crypts_hash [intro]:
"foldr Crypt KS (Hash X) \<in> crypts H \<Longrightarrow> foldr Crypt KS X \<in> crypts H" |
crypts_fst [intro]:
"foldr Crypt KS \<lbrace>X, Y\<rbrace> \<in> crypts H \<Longrightarrow> foldr Crypt KS X \<in> crypts H" |
crypts_snd [intro]:
"foldr Crypt KS \<lbrace>X, Y\<rbrace> \<in> crypts H \<Longrightarrow> foldr Crypt KS Y \<in> crypts H"
definition key_sets :: "msg \<Rightarrow> msg set \<Rightarrow> msg set set" where
"key_sets X H \<equiv> {InvKey ` set KS | KS. foldr Crypt KS X \<in> H}"
definition parts_msg :: "msg \<Rightarrow> msg set" where
"parts_msg X \<equiv> parts {X}"
definition crypts_msg :: "msg \<Rightarrow> msg set" where
"crypts_msg X \<equiv> crypts {X}"
definition key_sets_msg :: "msg \<Rightarrow> msg \<Rightarrow> msg set set" where
"key_sets_msg X Y \<equiv> key_sets X {Y}"
fun seskey_set :: "seskey_in \<Rightarrow> key_id set" where
"seskey_set (Some S, U, V) = insert S (U \<union> V)" |
"seskey_set (None, U, V) = U \<union> V"
definition Auth_PriK :: "agent_id \<Rightarrow> key_id" where
"Auth_PriK \<equiv> SOME f. infinite (- range f)"
abbreviation Auth_PriKey :: "agent_id \<Rightarrow> msg" where
"Auth_PriKey \<equiv> PriKey \<circ> Auth_PriK"
abbreviation Auth_PubKey :: "agent_id \<Rightarrow> msg" where
"Auth_PubKey \<equiv> PubKey \<circ> Auth_PriK"
consts Auth_ShaK :: "agent_id \<Rightarrow> key_id"
abbreviation Auth_ShaKey :: "agent_id \<Rightarrow> key" where
"Auth_ShaKey \<equiv> ShaK \<circ> Auth_ShaK"
abbreviation Sign :: "agent_id \<Rightarrow> key_id \<Rightarrow> msg" where
"Sign n A \<equiv> Crypt SigK \<lbrace>Hash (Agent n), Hash (PubKey A)\<rbrace>"
abbreviation Token :: "agent_id \<Rightarrow> key_id \<Rightarrow> key_id \<Rightarrow> key_id \<Rightarrow> seskey_in \<Rightarrow> msg"
where "Token n A B C SK \<equiv> \<lbrace>Crypt (SesK SK) (PubKey C),
Crypt (SesK SK) (A \<otimes> B), Crypt (SesK SK) (Sign n A)\<rbrace>"
consts bad_agent :: "agent_id set"
consts bad_pwd :: "agent_id set"
consts bad_shak :: "key_id set"
consts bad_id_pwd :: "agent_id set"
consts bad_id_prik :: "agent_id set"
consts bad_id_pubk :: "agent_id set"
consts bad_id_shak :: "agent_id set"
definition bad_prik :: "key_id set" where
"bad_prik \<equiv> SOME U. U \<subseteq> range Auth_PriK"
abbreviation bad_prikey :: "agent_id set" where
"bad_prikey \<equiv> Auth_PriK -` bad_prik"
abbreviation bad_shakey :: "agent_id set" where
"bad_shakey \<equiv> Auth_ShaK -` bad_shak"
abbreviation bad_id_password :: "agent_id set" where
"bad_id_password \<equiv> bad_id_pwd \<inter> bad_pwd"
abbreviation bad_id_prikey :: "agent_id set" where
"bad_id_prikey \<equiv> (bad_agent \<union> bad_id_pubk \<union> bad_id_prik) \<inter> bad_prikey"
abbreviation bad_id_pubkey :: "agent_id set" where
"bad_id_pubkey \<equiv> bad_agent \<union> bad_id_pubk \<union> bad_id_prik \<inter> bad_prikey"
abbreviation bad_id_shakey :: "agent_id set" where
"bad_id_shakey \<equiv> bad_id_shak \<inter> bad_shakey"
type_synonym event = "agent \<times> msg"
type_synonym state = "event set"
abbreviation used :: "state \<Rightarrow> msg set" where
"used s \<equiv> Range s"
abbreviation spied :: "state \<Rightarrow> msg set" where
"spied s \<equiv> s `` {Spy}"
abbreviation s\<^sub>0 :: state where
"s\<^sub>0 \<equiv> range (\<lambda>n. (Asset n, Auth_PriKey n)) \<union> {Spy} \<times> insert VerKey
(range Num \<union> range Auth_PubKey \<union> range (\<lambda>n. Sign n (Auth_PriK n)) \<union>
Agent ` bad_agent \<union> Pwd ` bad_pwd \<union> PriKey ` bad_prik \<union> ShaKey ` bad_shak \<union>
(\<lambda>n. \<langle>n, Pwd n\<rangle>) ` bad_id_password \<union>
(\<lambda>n. \<langle>n, Auth_PriKey n\<rangle>) ` bad_id_prikey \<union>
(\<lambda>n. \<langle>n, Auth_PubKey n\<rangle>) ` bad_id_pubkey \<union>
(\<lambda>n. \<langle>n, Key (Auth_ShaKey n)\<rangle>) ` bad_id_shakey)"
abbreviation rel_asset_i :: "(state \<times> state) set" where
"rel_asset_i \<equiv> {(s, s') | s s' n S.
s' = insert (Asset n, PriKey S) s \<union>
{Asset n, Spy} \<times> {Crypt (Auth_ShaKey n) (PriKey S)} \<union>
{(Spy, Log (Crypt (Auth_ShaKey n) (PriKey S)))} \<and>
PriKey S \<notin> used s}"
abbreviation rel_owner_ii :: "(state \<times> state) set" where
"rel_owner_ii \<equiv> {(s, s') | s s' n S A K.
s' = insert (Owner n, PriKey A) s \<union>
{Owner n, Spy} \<times> {\<lbrace>Num 1, PubKey A\<rbrace>} \<union>
{Spy} \<times> Log ` {Crypt K (PriKey S), \<lbrace>Num 1, PubKey A\<rbrace>} \<and>
Crypt K (PriKey S) \<in> used s \<and>
PriKey A \<notin> used s}"
abbreviation rel_asset_ii :: "(state \<times> state) set" where
"rel_asset_ii \<equiv> {(s, s') | s s' n A B.
s' = insert (Asset n, PriKey B) s \<union>
{Asset n, Spy} \<times> {\<lbrace>Num 2, PubKey B\<rbrace>} \<union>
{Spy} \<times> Log ` {\<lbrace>Num 1, PubKey A\<rbrace>, \<lbrace>Num 2, PubKey B\<rbrace>} \<and>
\<lbrace>Num 1, PubKey A\<rbrace> \<in> used s \<and>
PriKey B \<notin> used s}"
abbreviation rel_owner_iii :: "(state \<times> state) set" where
"rel_owner_iii \<equiv> {(s, s') | s s' n B C.
s' = insert (Owner n, PriKey C) s \<union>
{Owner n, Spy} \<times> {\<lbrace>Num 3, PubKey C\<rbrace>} \<union>
{Spy} \<times> Log ` {\<lbrace>Num 2, PubKey B\<rbrace>, \<lbrace>Num 3, PubKey C\<rbrace>} \<and>
\<lbrace>Num 2, PubKey B\<rbrace> \<in> used s \<and>
PriKey C \<notin> used s}"
abbreviation rel_asset_iii :: "(state \<times> state) set" where
"rel_asset_iii \<equiv> {(s, s') | s s' n C D.
s' = insert (Asset n, PriKey D) s \<union>
{Asset n, Spy} \<times> {\<lbrace>Num 4, PubKey D\<rbrace>} \<union>
{Spy} \<times> Log ` {\<lbrace>Num 3, PubKey C\<rbrace>, \<lbrace>Num 4, PubKey D\<rbrace>} \<and>
\<lbrace>Num 3, PubKey C\<rbrace> \<in> used s \<and>
PriKey D \<notin> used s}"
abbreviation rel_owner_iv :: "(state \<times> state) set" where
"rel_owner_iv \<equiv> {(s, s') | s s' n S A B C D K SK.
s' = insert (Owner n, SesKey SK) s \<union>
{Owner n, Spy} \<times> {Crypt (SesK SK) (PubKey D)} \<union>
{Spy} \<times> Log ` {\<lbrace>Num 4, PubKey D\<rbrace>, Crypt (SesK SK) (PubKey D)} \<and>
{Crypt K (PriKey S), \<lbrace>Num 2, PubKey B\<rbrace>, \<lbrace>Num 4, PubKey D\<rbrace>} \<subseteq> used s \<and>
{Owner n} \<times> {\<lbrace>Num 1, PubKey A\<rbrace>, \<lbrace>Num 3, PubKey C\<rbrace>} \<subseteq> s \<and>
SK = (if K = Auth_ShaKey n then Some S else None, {A, B}, {C, D})}"
abbreviation rel_asset_iv :: "(state \<times> state) set" where
"rel_asset_iv \<equiv> {(s, s') | s s' n S A B C D SK.
s' = s \<union> {Asset n} \<times> {SesKey SK, PubKey B} \<union>
{Asset n, Spy} \<times> {Token n (Auth_PriK n) B C SK} \<union>
{Spy} \<times> Log ` {Crypt (SesK SK) (PubKey D),
Token n (Auth_PriK n) B C SK} \<and>
{Asset n} \<times> {Crypt (Auth_ShaKey n) (PriKey S),
\<lbrace>Num 2, PubKey B\<rbrace>, \<lbrace>Num 4, PubKey D\<rbrace>} \<subseteq> s \<and>
{\<lbrace>Num 1, PubKey A\<rbrace>, \<lbrace>Num 3, PubKey C\<rbrace>,
Crypt (SesK SK) (PubKey D)} \<subseteq> used s \<and>
(Asset n, PubKey B) \<notin> s \<and>
SK = (Some S, {A, B}, {C, D})}"
abbreviation rel_owner_v :: "(state \<times> state) set" where
"rel_owner_v \<equiv> {(s, s') | s s' n A B C SK.
s' = s \<union> {Owner n, Spy} \<times> {Crypt (SesK SK) (Pwd n)} \<union>
{Spy} \<times> Log ` {Token n A B C SK, Crypt (SesK SK) (Pwd n)} \<and>
Token n A B C SK \<in> used s \<and>
(Owner n, SesKey SK) \<in> s \<and>
B \<in> fst (snd SK)}"
abbreviation rel_asset_v :: "(state \<times> state) set" where
"rel_asset_v \<equiv> {(s, s') | s s' n SK.
s' = s \<union> {Asset n, Spy} \<times> {Crypt (SesK SK) (Num 0)} \<union>
{Spy} \<times> Log ` {Crypt (SesK SK) (Pwd n), Crypt (SesK SK) (Num 0)} \<and>
(Asset n, SesKey SK) \<in> s \<and>
Crypt (SesK SK) (Pwd n) \<in> used s}"
abbreviation rel_prik :: "(state \<times> state) set" where
"rel_prik \<equiv> {(s, s') | s s' A.
s' = insert (Spy, PriKey A) s \<and>
PriKey A \<notin> used s}"
abbreviation rel_pubk :: "(state \<times> state) set" where
"rel_pubk \<equiv> {(s, s') | s s' A.
s' = insert (Spy, PubKey A) s \<and>
PriKey A \<in> spied s}"
abbreviation rel_sesk :: "(state \<times> state) set" where
"rel_sesk \<equiv> {(s, s') | s s' A B C D S.
s' = insert (Spy, SesKey (Some S, {A, B}, {C, D})) s \<and>
{PriKey S, PriKey A, PubKey B, PriKey C, PubKey D} \<subseteq> spied s}"
abbreviation rel_fact :: "(state \<times> state) set" where
"rel_fact \<equiv> {(s, s') | s s' A B.
s' = s \<union> {Spy} \<times> {PriKey A, PriKey B} \<and>
A \<otimes> B \<in> spied s \<and>
(PriKey A \<in> spied s \<or> PriKey B \<in> spied s)}"
abbreviation rel_mult :: "(state \<times> state) set" where
"rel_mult \<equiv> {(s, s') | s s' A B.
s' = insert (Spy, A \<otimes> B) s \<and>
{PriKey A, PriKey B} \<subseteq> spied s}"
abbreviation rel_hash :: "(state \<times> state) set" where
"rel_hash \<equiv> {(s, s') | s s' X.
s' = insert (Spy, Hash X) s \<and>
X \<in> spied s}"
abbreviation rel_dec :: "(state \<times> state) set" where
"rel_dec \<equiv> {(s, s') | s s' K X.
s' = insert (Spy, X) s \<and>
{Crypt K X, InvKey K} \<subseteq> spied s}"
abbreviation rel_enc :: "(state \<times> state) set" where
"rel_enc \<equiv> {(s, s') | s s' K X.
s' = insert (Spy, Crypt K X) s \<and>
{X, Key K} \<subseteq> spied s}"
abbreviation rel_sep :: "(state \<times> state) set" where
"rel_sep \<equiv> {(s, s') | s s' X Y.
s' = s \<union> {Spy} \<times> {X, Y} \<and>
\<lbrace>X, Y\<rbrace> \<in> spied s}"
abbreviation rel_con :: "(state \<times> state) set" where
"rel_con \<equiv> {(s, s') | s s' X Y.
s' = insert (Spy, \<lbrace>X, Y\<rbrace>) s \<and>
{X, Y} \<subseteq> spied s}"
abbreviation rel_id_agent :: "(state \<times> state) set" where
"rel_id_agent \<equiv> {(s, s') | s s' n.
s' = insert (Spy, \<langle>n, Agent n\<rangle>) s \<and>
Agent n \<in> spied s}"
abbreviation rel_id_invk :: "(state \<times> state) set" where
"rel_id_invk \<equiv> {(s, s') | s s' n K.
s' = insert (Spy, \<langle>n, InvKey K\<rangle>) s \<and>
{InvKey K, \<langle>n, Key K\<rangle>} \<subseteq> spied s}"
abbreviation rel_id_sesk :: "(state \<times> state) set" where
"rel_id_sesk \<equiv> {(s, s') | s s' n A SK X U.
s' = s \<union> {Spy} \<times> {\<langle>n, PubKey A\<rangle>, \<langle>n, SesKey SK\<rangle>} \<and>
{PubKey A, SesKey SK} \<subseteq> spied s \<and>
(\<langle>n, PubKey A\<rangle> \<in> spied s \<or> \<langle>n, SesKey SK\<rangle> \<in> spied s) \<and>
A \<in> seskey_set SK \<and>
SesKey SK \<in> U \<and>
U \<in> key_sets X (crypts (Log -` spied s))}"
abbreviation rel_id_fact :: "(state \<times> state) set" where
"rel_id_fact \<equiv> {(s, s') | s s' n A B.
s' = s \<union> {Spy} \<times> {\<langle>n, PriKey A\<rangle>, \<langle>n, PriKey B\<rangle>} \<and>
{PriKey A, PriKey B, \<langle>n, A \<otimes> B\<rangle>} \<subseteq> spied s}"
abbreviation rel_id_mult :: "(state \<times> state) set" where
"rel_id_mult \<equiv> {(s, s') | s s' n A B U.
s' = insert (Spy, \<langle>n, A \<otimes> B\<rangle>) s \<and>
U \<union> {PriKey A, PriKey B, A \<otimes> B} \<subseteq> spied s \<and>
(\<langle>n, PriKey A\<rangle> \<in> spied s \<or> \<langle>n, PriKey B\<rangle> \<in> spied s) \<and>
U \<in> key_sets (A \<otimes> B) (crypts (Log -` spied s))}"
abbreviation rel_id_hash :: "(state \<times> state) set" where
"rel_id_hash \<equiv> {(s, s') | s s' n X U.
s' = s \<union> {Spy} \<times> {\<langle>n, X\<rangle>, \<langle>n, Hash X\<rangle>} \<and>
U \<union> {X, Hash X} \<subseteq> spied s \<and>
(\<langle>n, X\<rangle> \<in> spied s \<or> \<langle>n, Hash X\<rangle> \<in> spied s) \<and>
U \<in> key_sets (Hash X) (crypts (Log -` spied s))}"
abbreviation rel_id_crypt :: "(state \<times> state) set" where
"rel_id_crypt \<equiv> {(s, s') | s s' n X U.
s' = s \<union> {Spy} \<times> IDInfo n ` insert X U \<and>
insert X U \<subseteq> spied s \<and>
(\<langle>n, X\<rangle> \<in> spied s \<or> (\<exists>K \<in> U. \<langle>n, K\<rangle> \<in> spied s)) \<and>
U \<in> key_sets X (crypts (Log -` spied s))}"
abbreviation rel_id_sep :: "(state \<times> state) set" where
"rel_id_sep \<equiv> {(s, s') | s s' n X Y.
s' = s \<union> {Spy} \<times> {\<langle>n, X\<rangle>, \<langle>n, Y\<rangle>} \<and>
{X, Y, \<langle>n, \<lbrace>X, Y\<rbrace>\<rangle>} \<subseteq> spied s}"
abbreviation rel_id_con :: "(state \<times> state) set" where
"rel_id_con \<equiv> {(s, s') | s s' n X Y U.
s' = insert (Spy, \<langle>n, \<lbrace>X, Y\<rbrace>\<rangle>) s \<and>
U \<union> {X, Y, \<lbrace>X, Y\<rbrace>} \<subseteq> spied s \<and>
(\<langle>n, X\<rangle> \<in> spied s \<or> \<langle>n, Y\<rangle> \<in> spied s) \<and>
U \<in> key_sets \<lbrace>X, Y\<rbrace> (crypts (Log -` spied s))}"
definition rel :: "(state \<times> state) set" where
"rel \<equiv> rel_asset_i \<union> rel_owner_ii \<union> rel_asset_ii \<union> rel_owner_iii \<union>
rel_asset_iii \<union> rel_owner_iv \<union> rel_asset_iv \<union> rel_owner_v \<union> rel_asset_v \<union>
rel_prik \<union> rel_pubk \<union> rel_sesk \<union> rel_fact \<union> rel_mult \<union> rel_hash \<union> rel_dec \<union>
rel_enc \<union> rel_sep \<union> rel_con \<union> rel_id_agent \<union> rel_id_invk \<union> rel_id_sesk \<union>
rel_id_fact \<union> rel_id_mult \<union> rel_id_hash \<union> rel_id_crypt \<union> rel_id_sep \<union> rel_id_con"
abbreviation in_rel :: "state \<Rightarrow> state \<Rightarrow> bool" (infix "\<turnstile>" 60) where
"s \<turnstile> s' \<equiv> (s, s') \<in> rel"
abbreviation in_rel_rtrancl :: "state \<Rightarrow> state \<Rightarrow> bool" (infix "\<Turnstile>" 60) where
"s \<Turnstile> s' \<equiv> (s, s') \<in> rel\<^sup>*"
end |
[STATEMENT]
lemma "rel_fun (=) (\<le>) (const (0::nat)) x"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. rel_fun (=) (\<le>) (pure 0) x
[PROOF STEP]
by applicative_lifting simp |
postulate Name : Set
{-# BUILTIN QNAME Name #-}
data ⊤ : Set where
tt : ⊤
data Term : Set where
con : Name → Term → Term
data X : ⊤ → Set where
x : {t : ⊤} → X t
data Y : Set where
y : Y
-- this type checks
g : {t : ⊤} → Term → X t
g {t} (con nm args) = x {t}
-- this doesn't
f : {t : ⊤} → Term → X t
f {t} (con (quote Y.y) args) = x {t}
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- offending line is above
f t = x
-- t != args of type ⊤
-- when checking that the expression x {t} has type X args
|
#include "client.h"
#include <boost/tokenizer.hpp>
#include "mylogger.h"
#include "protos/account.pb.h"
static LoggerPtr logger(Logger::getLogger("myclient"));
|
The multiplicity of a prime $p$ in the number $1$ is $0$. |
[STATEMENT]
lemma DmdRec2: "\<And>sigma. \<lbrakk> sigma \<Turnstile> \<diamond>P; sigma \<Turnstile> \<box>\<not>P` \<rbrakk> \<Longrightarrow> sigma \<Turnstile> Init P"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>sigma. \<lbrakk>sigma \<Turnstile> \<diamond>P; sigma \<Turnstile> \<box>\<not> P$\<rbrakk> \<Longrightarrow> sigma \<Turnstile> Init P
[PROOF STEP]
apply (force simp: DmdRec [temp_rewrite] dmd_def)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done |
The UITS Central Web Server 2 provides hosting for University web sites. Currently, only UConn Departmental web pages are supported. Faculty, staff, graduate students, and student organizations must use the Homepages Web Server . Please see the Contact page for whom to contact for an account. |
theory Result
imports
Main
"HOL-Library.Monad_Syntax"
begin
datatype ('err, 'a) result =
is_err: Error 'err |
is_ok: Ok 'a
section \<open>Monadic bind\<close>
context begin
qualified fun bind :: "('a, 'b) result \<Rightarrow> ('b \<Rightarrow> ('a, 'c) result) \<Rightarrow> ('a, 'c) result" where
"bind (Error x) _ = Error x" |
"bind (Ok x) f = f x"
end
adhoc_overloading
bind Result.bind
context begin
qualified lemma bind_Ok[simp]: "x \<bind> Ok = x"
by (cases x) simp_all
qualified lemma bind_eq_Ok_conv: "(x \<bind> f = Ok z) = (\<exists>y. x = Ok y \<and> f y = Ok z)"
by (cases x) simp_all
qualified lemmas bind_eq_OkD[dest!] = bind_eq_Ok_conv[THEN iffD1]
qualified lemmas bind_eq_OkE = bind_eq_OkD[THEN exE]
qualified lemmas bind_eq_OkI[intro] = conjI[THEN exI[THEN bind_eq_Ok_conv[THEN iffD2]]]
qualified lemma bind_eq_Error_conv:
"x \<bind> f = Error z \<longleftrightarrow> x = Error z \<or> (\<exists>y. x = Ok y \<and> f y = Error z)"
by (cases x) simp_all
qualified lemmas bind_eq_ErrorD[dest!] = bind_eq_Error_conv[THEN iffD1]
qualified lemmas bind_eq_ErrorE = bind_eq_ErrorD[THEN disjE]
qualified lemmas bind_eq_ErrorI =
disjI1[THEN bind_eq_Error_conv[THEN iffD2]]
conjI[THEN exI[THEN disjI2[THEN bind_eq_Error_conv[THEN iffD2]]]]
lemma if_then_else_Ok[simp]:
"(if a then b else Error c) = Ok d \<longleftrightarrow> a \<and> b = Ok d"
"(if a then Error c else b) = Ok d \<longleftrightarrow> \<not> a \<and> b = Ok d"
by (cases a) simp_all
qualified lemma if_then_else_Error[simp]:
"(if a then Ok b else c) = Error d \<longleftrightarrow> \<not> a \<and> c = Error d"
"(if a then c else Ok b) = Error d \<longleftrightarrow> a \<and> c = Error d"
by (cases a) simp_all
qualified lemma map_eq_Ok_conv: "map_result f g x = Ok y \<longleftrightarrow> (\<exists>x'. x = Ok x' \<and> y = g x')"
by (cases x; auto)
qualified lemma map_eq_Error_conv: "map_result f g x = Error y \<longleftrightarrow> (\<exists>x'. x = Error x' \<and> y = f x')"
by (cases x; auto)
qualified lemmas map_eq_OkD[dest!] = iffD1[OF map_eq_Ok_conv]
qualified lemmas map_eq_ErrorD[dest!] = iffD1[OF map_eq_Error_conv]
end
section \<open>Conversion functions\<close>
context begin
qualified fun of_option where
"of_option e None = Error e" |
"of_option e (Some x) = Ok x"
qualified lemma of_option_injective[simp]: "(of_option e x = of_option e y) = (x = y)"
by (cases x; cases y; simp)
qualified lemma of_option_eq_Ok[simp]: "(of_option x y = Ok z) = (y = Some z)"
by (cases y) simp_all
qualified fun to_option where
"to_option (Error _) = None" |
"to_option (Ok x) = Some x"
qualified lemma to_option_Some[simp]: "(to_option r = Some x) = (r = Ok x)"
by (cases r) simp_all
qualified fun those :: "('err, 'ok) result list \<Rightarrow> ('err, 'ok list) result" where
"those [] = Ok []" |
"those (x # xs) = do {
y \<leftarrow> x;
ys \<leftarrow> those xs;
Ok (y # ys)
}"
qualified lemma those_Cons_OkD: "those (x # xs) = Ok ys \<Longrightarrow> \<exists>y ys'. ys = y # ys' \<and> x = Ok y \<and> those xs = Ok ys'"
by auto
end
end |
import data.nat.basic
example (n : ℕ) (h : n < 2) : n = 0 ∨ n = 1 :=
by dec_trivial!
example (n : ℕ) (h : n < 3) : true :=
begin
let k : ℕ := n - 1,
have : ∀ i < k, i = 0 ∨ i = 1,
by dec_trivial!,
trivial
end
example (b : bool) (h : b = tt) : true :=
begin
let b₁ : bool := b,
have : ∀ b₂ : bool, b₂ ≠ b₁ → b₂ = ff,
by dec_trivial!,
trivial
end
example (n : ℕ) : (0 : fin (n+1)) + 0 = 0 :=
begin
success_if_fail { dec_trivial! },
dec_trivial
end
|
-- {-# OPTIONS --allow-unsolved-metas #-}
module Issue2369.OpenIP where
test : Set
test = {!!} -- unsolved interaction point
-- postulate A : {!!}
|
# m4_3t.jl
using Pkg, DrWatson
@quickactivate "StatisticalRethinkingTuring"
using Turing
using StatisticalRethinking
Turing.setprogress!(false)
begin
df = CSV.read(sr_datadir("Howell1.csv"), DataFrame)
df = df[df.age .>= 18, :]
x̄ = mean(df.weight)
x = range(minimum(df.weight), maximum(df.weight), length = 100)
end;
@model function ppl4_3(weights, heights)
a ~ Normal(178, 20)
b ~ LogNormal(0, 1)
σ ~ Uniform(0, 50)
μ = a .+ b .* (weights .- x̄)
for i in eachindex(heights)
heights[i] ~ Normal(μ[i], σ)
end
end
m4_3t = ppl4_3(df.weight, df.height)
q4_3t = quap(m4_3t, NelderMead())
nchains = 4; sampler = NUTS(0.65); nsamples=2000
chns4_3t = mapreduce(c -> sample(m4_3t, sampler, nsamples), chainscat, 1:nchains)
chns4_3t_df = DataFrame(chns4_3t)
quap4_3t_df = DataFrame(rand(q4_3t.distr, 10_000)', q4_3t.params)
part4_3t = Particles(chns4_3t[[:a, :b, :σ]])
# End of m4.3t.jl
|
SUBROUTINE GBYTEC(IN,IOUT,ISKIP,NBYTE)
character*1 in(*)
integer iout(*)
CALL GBYTESC(IN,IOUT,ISKIP,NBYTE,0,1)
RETURN
END
|
{-# LANGUAGE ForeignFunctionInterface #-}
module Grenade.Layers.Internal.Pad (
pad
, crop
) where
import qualified Data.Vector.Storable as U (unsafeFromForeignPtr0,
unsafeToForeignPtr0)
import Foreign (mallocForeignPtrArray, withForeignPtr)
import Foreign.Ptr (Ptr)
import Numeric.LinearAlgebra (Matrix, flatten)
import qualified Numeric.LinearAlgebra.Devel as U
import System.IO.Unsafe (unsafePerformIO)
import Grenade.Types
pad :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum
pad channels padLeft padTop padRight padBottom rows cols rows' cols' m
= let outMatSize = rows' * cols' * channels
vec = flatten m
in unsafePerformIO $ do
outPtr <- mallocForeignPtrArray outMatSize
let (inPtr, _) = U.unsafeToForeignPtr0 vec
withForeignPtr inPtr $ \inPtr' ->
withForeignPtr outPtr $ \outPtr' ->
pad_cpu inPtr' channels rows cols padLeft padTop padRight padBottom outPtr'
let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize
return (U.matrixFromVector U.RowMajor (rows' * channels) cols' matVec)
{-# INLINE pad #-}
foreign import ccall unsafe
pad_cpu
:: Ptr RealNum -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr RealNum -> IO ()
crop :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Matrix RealNum -> Matrix RealNum
crop channels padLeft padTop padRight padBottom rows cols _ _ m
= let outMatSize = rows * cols * channels
vec = flatten m
in unsafePerformIO $ do
outPtr <- mallocForeignPtrArray outMatSize
let (inPtr, _) = U.unsafeToForeignPtr0 vec
withForeignPtr inPtr $ \inPtr' ->
withForeignPtr outPtr $ \outPtr' ->
crop_cpu inPtr' channels rows cols padLeft padTop padRight padBottom outPtr'
let matVec = U.unsafeFromForeignPtr0 outPtr outMatSize
return (U.matrixFromVector U.RowMajor (rows * channels) cols matVec)
foreign import ccall unsafe
crop_cpu
:: Ptr RealNum -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Ptr RealNum -> IO ()
|
\maketitle
\section*{Motivation: Why covering spaces?}
\todo[inline]{Topologists have a love-hate relationship with topological spaces.}
One way to understand spaces is to associate an algebraic invariant to them.
\begin{equation*}
\begin{tikzcd}
\mbox{Topological Space} \ar[rr] && \mbox{Algebraic invariant} \\
\mbox{For example: Knot} \ar[r] & \mbox{Knot projection} \ar[r] & \mbox{Knot invariant}
\end{tikzcd}
\end{equation*}
where a knot invariant can be a number, polynomial, vector space, chain complex, etc.
It is rarely possible to compute an invariant directly using definition.
Instead, there are two main strategies in algebraic topology to compute these algebraic invariants:
\begin{enumerate}
\item Break a space $X$ up into smaller spaces,
\begin{align*}
X = X_1 \cup \dots \cup X_n.
\end{align*}
This is called \emph{excision}.
\item Map another space $Y$ into $X$ and recover information about $X$ using $Y$.
\begin{align*}
Y \longrightarrow X
\end{align*}
This is where covering spaces come in. A covering map $Y \rightarrow X$ provides us information about the fundamental group/first homotopy group $\pi_1(X)$.
We will show later on that if $\pi_1(Y) \triangleleft \pi_1(X)$ then there is a short exact sequence of groups
\begin{equation*}
1 \rightarrow \pi_1(Y) \rightarrow \pi_1(X) \rightarrow \Gal(Y|X) \rightarrow 1
\end{equation*}
\end{enumerate}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.