Datasets:
AI4M
/

text
stringlengths
0
3.34M
#Install External R Packages #When a user installs a tool in Skyline this checks to make sure the required packages are also installed. If the packages don't exist on the users machine skyline will #require the user to install them before they can continue using the tool. This InstallPackages.r file checks for ______________ R packages. a<-installed.packages() packages<-a[,1] cat("INSTALLING") install.packages(c("tidyr", "plyr", "dplyr", "reshape2", "seqinr", "ggplot2", "coefplot", "forcats", "tibble", "stringr", "purrr", "gridExtra", "pracma", "hablar"), repos='http://cran.us.r-project.org') if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos='http://cran.us.r-project.org') BiocManager::install("qvalue") ##The following code can install a custom package from a URL. #if (!is.element("ExampleTool",packages) || packageVersion("ExampleTool") < "1.0" ){ #directory <- tempdir() #gsub("\\", "/", directory, fixed = TRUE) #filename <- "ExampleTool_1.0.tar.gz" #path <- file.path(directory, filename) #ExampleToolPackage <-normalizePath(path) #download.file("http://www.exampletoolwebsite.com/ExampleTool_1.0.tar.gz", ExampleToolPackage) #install.packages(ExampleToolPackage, repos = NULL, type="source") #}
from __future__ import print_function, division import os import numpy as np import tensorflow as tf from tensorflow.contrib.rnn import GRUCell from tensorflow.python.ops.rnn import bidirectional_dynamic_rnn as bi_rnn import pickle,sys gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.1) ### Directory of current exec### dir_path = os.path.dirname(os.path.realpath(__file__)) #####################Get the model builder code ready#################### # Define some parameters EMBEDDING_DIM = 100 HIDDEN_UNITS = 150 ATTENTION_UNITS = 50 KEEP_PROB = 0.8 DELTA = 0.5 SHUFFLE = False max_tweet_length = 47 vocab = pickle.load(open(dir_path+"/model/vocab.pkl","rb")) vocabulary_size = len(vocab.keys())+1 #add one for UNK # Set the sequence length SEQUENCE_LENGTH = max_tweet_length # This is piece of code is Copyright (c) 2017 to Ilya Ivanov and grants permission under MIT Licence # https://github.com/ilivans/tf-rnn-attention/blob/master/attention.py # Implementation as proposed by Yang et al. in "Hierarchical Attention Networks for Document Classification" (2016) def attention(inputs, attention_size, time_major=False, return_alphas=False): if isinstance(inputs, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. inputs = tf.concat(inputs, 2) if time_major: # (T,B,D) => (B,T,D) inputs = tf.array_ops.transpose(inputs, [1, 0, 2]) hidden_size = inputs.shape[2].value # D value - hidden size of the RNN layer # Trainable parameters w_omega = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1)) b_omega = tf.Variable(tf.random_normal([attention_size], stddev=0.1)) u_omega = tf.Variable(tf.random_normal([attention_size], stddev=0.1)) with tf.name_scope('v'): # Applying fully connected layer with non-linear activation to each of the B*T timestamps; # the shape of `v` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size v = tf.tanh(tf.tensordot(inputs, w_omega, axes=1) + b_omega) # For each of the timestamps its vector of size A from `v` is reduced with `u` vector vu = tf.tensordot(v, u_omega, axes=1, name='vu') # (B,T) shape alphas = tf.nn.softmax(vu, name='alphas') # (B,T) shape # Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape output = tf.reduce_sum(inputs * tf.expand_dims(alphas, -1), 1) if not return_alphas: return output else: return output, alphas def build_attention_model(): # Different placeholders with tf.name_scope('Inputs'): batch_ph = tf.placeholder(tf.int32, [None, SEQUENCE_LENGTH], name='batch_ph') target_ph = tf.placeholder(tf.float32, [None], name='target_ph') seq_len_ph = tf.placeholder(tf.int32, [None], name='seq_len_ph') keep_prob_ph = tf.placeholder(tf.float32, name='keep_prob_ph') # Embedding layer with tf.name_scope('Embedding_layer'): embeddings_var = tf.Variable(tf.random_uniform([vocabulary_size, EMBEDDING_DIM], -1.0, 1.0), trainable=True) tf.summary.histogram('embeddings_var', embeddings_var) batch_embedded = tf.nn.embedding_lookup(embeddings_var, batch_ph) # (Bi-)RNN layer(-s) rnn_outputs, _ = bi_rnn(GRUCell(HIDDEN_UNITS), GRUCell(HIDDEN_UNITS), inputs=batch_embedded, sequence_length=seq_len_ph, dtype=tf.float32) tf.summary.histogram('RNN_outputs', rnn_outputs) # Attention layer with tf.name_scope('Attention_layer'): attention_output, alphas = attention(rnn_outputs, ATTENTION_UNITS, return_alphas=True) tf.summary.histogram('alphas', alphas) # Dropout drop = tf.nn.dropout(attention_output, keep_prob_ph) # Fully connected layer with tf.name_scope('Fully_connected_layer'): W = tf.Variable( tf.truncated_normal([HIDDEN_UNITS * 2, 1], stddev=0.1)) # Hidden size is multiplied by 2 for Bi-RNN b = tf.Variable(tf.constant(0., shape=[1])) y_hat = tf.nn.xw_plus_b(drop, W, b) y_hat = tf.squeeze(y_hat) pred = tf.sigmoid(y_hat) #pred = tf.round(tf.sigmoid(y_hat)) tf.summary.histogram('W', W) with tf.name_scope('Metrics'): # Cross-entropy loss and optimizer initialization loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_hat, labels=target_ph)) tf.summary.scalar('loss', loss) optimizer = tf.train.AdamOptimizer(learning_rate=1e-3).minimize(loss) # Accuracy metric accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.round(tf.sigmoid(y_hat)), target_ph), tf.float32)) tf.summary.scalar('accuracy', accuracy) merged = tf.summary.merge_all() # Batch generators session_conf = tf.ConfigProto(gpu_options=gpu_options) saver = tf.train.Saver() return batch_ph, target_ph, seq_len_ph, keep_prob_ph, alphas,pred, session_conf, saver ##############Now prepare test scenario########### MODEL_PATH = dir_path+"/model/" batch_ph, target_ph, seq_len_ph, keep_prob_ph, alphas,pred, session_conf, saver = build_attention_model() sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) saver.restore(sess, MODEL_PATH) print ("Sarcasm Detection Model Restored") def get_sentence_score(sent,max_len=47): sent = " ".join(sent.split()[:45]) array1 = [0]*max_len i = 0 for w in sent.split(): array1[i] = vocab.get(w.lower(),0) i+=1 array2 = np.array(array1) #print (array2.shape) seql = [len(array1)]#len(sent.split()) x_batch = [array2] y_batch = [0] out = sess.run([pred],feed_dict={batch_ph: x_batch,target_ph: y_batch,seq_len_ph: seql,keep_prob_ph: 1.0}) return out[0] def prepare_sents(sents,max_len=47): x_batch = [] y_batch = [] seqls = [] i = 0 for sent in sents: array1 = [0]*max_len i=0 for w in sent.split(): array1[i] = vocab.get(w.lower(),0) i+=1 array2 = np.array(array1) x_batch.append(array2) y_batch.append(0) seqls.append(len(array1)) return [x_batch,y_batch,seqls] def get_batch_reward_score(sents): scores = [] x_batch,y_batch,seqls = prepare_sents(sents) out = sess.run([pred],feed_dict={batch_ph: x_batch,target_ph: y_batch,seq_len_ph: seqls,keep_prob_ph: 1.0}) out = 1-out[0] #print (out) return np.mean(out) if __name__=="__main__": sents = ["i love being ignored"]*10 print (get_batch_reward_score(sents)) #while True: # print ("Enter Sent") # inp = input() # print (get_sentence_score(inp))
{-# OPTIONS --without-K #-} {- This module serves to develop some basic theory about pointed types. After defining the usual notions of pointed types, pointed equivalences, and loop spaces, we derive a version of univalence for pointed equivalences and observe that univalence between identical types is a pointed equivalence. We define pointed versions of dependent sums and products using the usual notion of pointed families and observe that they commute in a certain sense with taking loop spaces. We finish by deriving a generalization to n-truncation and n-th loop spaces of the fact allowing us to 'forget' contractible components in a dependent sum type that will be needed in the Hierarchy module. -} module Universe.Utility.Pointed where open import lib.Basics open import lib.NType2 open import lib.types.Nat hiding (_+_) open import lib.types.Pi open import lib.types.Sigma open import lib.types.TLevel open import Universe.Utility.General open import Universe.Utility.TruncUniverse {- Pointed types. A pointed type is a type (base) together with a chosen element (pt). The loop space construction Ω takes a pointed type and returns the type of all loops at the given basepoint. The trivial loop is taken as canonical element, thus forming a new pointed type. -} Type• : (i : ULevel) → Type (lsucc i) Type• i = Σ (Type i) (idf _) module _ {i} (X : Type• i) where base = fst X pt = snd X -- Alternate definition: Σ (n -Type i) ⟦_⟧ _-Type•_ : (n : ℕ₋₂) (i : ULevel) → Type (lsucc i) n -Type• i = Σ (Type• i) (has-level n ∘ base) -- For alternate definition: Σ-≤ (n -Type-≤ i) raise _-Type•-≤_ : (n : ℕ₋₂) (i : ULevel) → S n -Type lsucc i n -Type•-≤ i = (n -Type• i , equiv-preserves-level Σ-comm-snd (snd (Σ-≤ (n -Type-≤ i) raise))) {- Pointed equivalences. An equivalence of pointed types is an equivalences of the bases that preserves the points -} _≃•_ : ∀ {i j} → Type• i → Type• j → Set (i ⊔ j) A ≃• B = Σ (base A ≃ base B) (λ f → –> f (pt A) == pt B) ide• : ∀ {i} (X : Type• i) → X ≃• X ide• _ = ide _ , idp _∘e•_ : ∀ {i j k} {X : Type• i} {Y : Type• j} {Z : Type• k} → Y ≃• Z → X ≃• Y → X ≃• Z (u , p) ∘e• (v , q) = (u ∘e v , ap (–> u) q ∙ p) _⁻¹• : ∀ {i j} {X : Type• i} {Y : Type• j} → X ≃• Y → Y ≃• X (u , p) ⁻¹• = (u ⁻¹ , ap (<– u) (! p) ‌∙ <–-inv-l u _) -- Equational reasoning for pointed equivalences. infix 2 _≃•∎ infixr 2 _≃•⟨_⟩_ _≃•⟨_⟩_ : ∀ {i j k} (X : Type• i) {Y : Type• j} {Z : Type• k} → X ≃• Y → Y ≃• Z → X ≃• Z _ ≃•⟨ u ⟩ v = v ∘e• u _≃•∎ : ∀ {i} (X : Type• i) → X ≃• X _≃•∎ = ide• -- The loop space construction. Ω : ∀ {i} → Type• i → Type• i Ω (A , a) = (a == a , idp) Ω-≤ : ∀ {i} {n : ℕ₋₂} → (S n) -Type• i → n -Type• i Ω-≤ ((A , a) , t) = (Ω (A , a) , t a a) -- Loop spaces are preserved by pointed equivalences. equiv-Ω : ∀ {i j} {X : Type• i} {Y : Type• j} → X ≃• Y → Ω X ≃• Ω Y equiv-Ω (u , p) = split u p where split : ∀ u {a} {b} → –> u a == b → Ω (_ , a) ≃• Ω (_ , b) split u idp = (equiv-ap u _ _ , idp) equiv-Ω^ : ∀ {i j} {X : Type• i} {Y : Type• j} (n : ℕ) → X ≃• Y → (Ω ^ n) X ≃• (Ω ^ n) Y equiv-Ω^ 0 e = e equiv-Ω^ (S n) e = equiv-Ω^ n (equiv-Ω e) {- We call a pointed type n-truncated if its base is. Constructing the loop space decrements the truncation level. -} has-level• : ∀ {i} → ℕ₋₂ → Type• i → Type i has-level• n = has-level n ∘ base trunc-many : ∀ {i} {X : Type• i} {k : ℕ} (n : ℕ) → has-level• (k + n -2) X → has-level• (k -2) ((Ω ^ n) X) trunc-many 0 t = t trunc-many (S n) t = trunc-many n (t _ _) --Ω^-≤ : ∀ {i} {k : ℕ} (n : ℕ) → (k + n -2) -Type• i → (k -2) -Type• i --Ω^-≤ O X = X --Ω^-≤ (S n) X = Ω^-≤ n (Ω-≤ X) Ω^-≤ : ∀ {i} {k : ℕ} (n : ℕ) → (k + n -2) -Type• i → (k -2) -Type• i Ω^-≤ n (X , t) = ((Ω ^ n) X , trunc-many n t) Ω^-≤' : ∀ {i} {k : ℕ} (n : ℕ) → (n + k -2) -Type• i → (k -2) -Type• i Ω^-≤' n (X , t) = ((Ω ^ n) X , trunc-many n (transport (λ z → has-level• (z -2) X) (+-comm _ n) t)) {- Pointedness allows for a more direct notion of contractibility. Beware that is-contr• will be equivalent --- not definitionally equal --- to has-level∙ ⟨-2⟩. -} module _ {i} (X : Type• i) where is-contr• : Type i is-contr• = ∀ a → pt X == a {- Since pointed types are always inhabited, being contractible and propositional is equivalent. -} module _ {i} {X : Type• i} where contr•-equiv-contr : is-contr• X ≃ is-contr (base X) contr•-equiv-contr = prop-equiv' (λ c → Π-level (λ a → raise-level-<T (ltSR ltS) c _ _)) (cst is-contr-is-prop) (λ x → (pt X , x)) (λ y _ → prop-has-all-paths (contr-is-prop y) _ _) is-contr•-is-prop : is-prop (is-contr• X) is-contr•-is-prop = equiv-preserves-level (contr•-equiv-contr ⁻¹) is-contr-is-prop prop-equiv-contr : is-prop (base X) ≃ is-contr (base X) prop-equiv-contr = prop-equiv is-prop-is-prop is-contr-is-prop (inhab-prop-is-contr (pt X)) contr-is-prop contr•-equiv-prop : is-contr• X ≃ is-prop (base X) contr•-equiv-prop = prop-equiv-contr ⁻¹ ∘e contr•-equiv-contr -- ** Lemma 5.4 *** {- The induction step for Lemma 7.2.9 in the HoTT Book is much more complicated than neccesarry. Associating iterated loop spaces in the reverse order, we can do away with the prerequisites 7.2.7 and 7.2.8 as well as further auxiliary steps. -} has-level-equiv-contr-loops : ∀ {i} {n : ℕ} {A : Type i} → has-level (n -1) A ≃ ((a : A) → is-contr• ((Ω ^ n) (A , a))) has-level-equiv-contr-loops {n = O} {A} = is-prop A ≃⟨ prop-equiv-inhab-to-contr ⟩ (A → is-contr A) ≃⟨ equiv-Π-r (λ _ → contr•-equiv-contr ⁻¹) ⟩ ((a : A) → is-contr• (A , a)) ≃∎ has-level-equiv-contr-loops {n = S n} {A} = equiv-Π-r lem where lem = λ a → (((b : A) → has-level ( n -1) (a == b))) ≃⟨ equiv-Π-r (λ _ → has-level-equiv-contr-loops) ⟩ (((b : A) (p : a == b) → is-contr• ((Ω ^ n) (a == b , p)))) ≃⟨ Π₁-contr (pathfrom-is-contr _) ∘e curry-equiv ⁻¹ ⟩ is-contr• ((Ω ^ n) (a == a , idp)) ≃∎ -- Pointed equivalences preserve (pointed) contractibility. equiv-is-contr• : ∀ {i j} {X : Type• i} {Y : Type• j} → X ≃• Y → is-contr• X ≃ is-contr• Y equiv-is-contr• (u , p) = contr•-equiv-contr ⁻¹ ∘e equiv-level u ∘e contr•-equiv-contr -- Univalence for pointed equivalences. module _ {i} {A B : Type• i} where ua•-equiv : (A ≃• B) ≃ (A == B) ua•-equiv = A ≃• B ≃⟨ ide _ ⟩ Σ (base A ≃ base B) (λ f → –> f (pt A) == pt B) ≃⟨ equiv-Σ-fst _ (snd (ua-equiv ⁻¹)) ⁻¹ ⟩ Σ (base A == base B) (λ q → coe q (pt A) == pt B) ≃⟨ equiv-Σ-snd (λ q → coe-equiv (ap (λ f → coe f (pt A) == pt B) (! (ap-idf q)))) ⟩ Σ (base A == base B) (λ q → coe (ap (idf _) q) (pt A) == pt B) ≃⟨ equiv-Σ-snd (λ q → to-transp-equiv _ q ⁻¹) ⟩ Σ (base A == base B) (λ q → pt A == pt B [ idf _ ↓ q ]) ≃⟨ =Σ-eqv _ _ ⟩ A == B ≃∎ ua• : A ≃• B → A == B ua• = –> ua•-equiv coe•-equiv : A == B → A ≃• B coe•-equiv = <– ua•-equiv -- Normal univalence can be made pointed in the endo-setting. module _ {i} {A : Type i} where ua-equiv• : (A ≃ A , ide _) ≃• (A == A , idp) ua-equiv• = ((ua-equiv ⁻¹) , idp) ⁻¹• -- *** Definition 4.1 *** {- Pointed families. A pointed family over a pointed type is a family over the base together with a inhabitant of the family at the point. Note that pointed types are equivalent to pointed families over the pointed unit type (not shown here). -} Fam• : ∀ {i} (X : Type• i) (j : ULevel) → Type (i ⊔ lsucc j) Fam• X j = Σ (base X → Type j) (λ P → P (pt X)) -- We have fibered notions of the loop space contruction and n-truncatedness. module _ {i} {X : Type• i} {j} where -- *** Definition 4.3 *** {- Note that the definition of the family of path types differs slightly from that of the article, which would correspond to transport P p x == x. We use dependent paths since this follows the design of the HoTT community's Agda library. Clearly, both types are equivalent. -} Ω̃ : Fam• X j → Fam• (Ω X) j Ω̃ (P , x) = ((λ p → x == x [ P ↓ p ]) , idp) fam-has-level : ℕ₋₂ → Fam• X j → Type (i ⊔ j) fam-has-level n Q = (a : base X) → has-level n (fst Q a) {- == Pointed dependent sums == Pointed families as defined above enable us to introduce a Σ-connective for pointed types. Because of the abstract nature of some of our lemmata, we give Σ• in its uncurried form and first define the type of its parameter. -} Σ•-param : ∀ i j → Type (lsucc (i ⊔ j)) Σ•-param i j = Σ (Type• i) (λ X → Fam• X j) module _ {i j} where Ω-Σ•-param : Σ•-param i j → Σ•-param i j Ω-Σ•-param (X , W) = (Ω X , Ω̃ W) -- *** Definition 4.4 *** Σ• : Σ•-param i j → Type• (i ⊔ j) Σ• (X , Q) = (Σ (base X) (fst Q) , (pt X , snd Q)) -- *** Lemma 4.5 *** {- Commutativity of pointed dependent sums and the loop space construction will become an important technical tool, enabling us to work at a more abstract level later on. -} Ω-Σ•-comm : (R : Σ•-param i j) → Ω (Σ• R) ≃• Σ• (Ω-Σ•-param R) Ω-Σ•-comm _ = (=Σ-eqv _ _ , idp) ⁻¹• {- Pointed dependent products. This is not quite the equivalent of Π for pointed types: the domain parameter is just an ordinary non-pointed type. However, to enable our goal of abstractly working with pointed types, defining this notion is useful. -} Π•-param : ∀ i j → Type (lsucc (i ⊔ j)) Π•-param i j = Σ (Type i) (λ A → A → Type• j) module _ {i j} where Ω-Π•-param : Π•-param i j → Π•-param i j Ω-Π•-param (A , F) = (A , Ω ∘ F) -- *** Definition 4.6 *** Π• : Π•-param i j → Type• (i ⊔ j) Π• (A , Y) = (Π A (base ∘ Y) , pt ∘ Y) -- *** Lemma 4.7 *** {- Pointed dependent products and loop space construction on its codomain parameter commute as well. -} Ω-Π•-comm : (R : Π•-param i j) → Ω (Π• R) ≃• Π• (Ω-Π•-param R) Ω-Π•-comm _ = (app=-equiv , idp) Ω^-Π•-comm : (C : Type i) (F : C → Type• j) (n : ℕ) → (Ω ^ n) (Π• (C , F)) ≃• Π• (C , Ω ^ n ∘ F) Ω^-Π•-comm C F 0 = ide• _ Ω^-Π•-comm C F (S n) = Ω^-Π•-comm C _ n ∘e• equiv-Ω^ n (Ω-Π•-comm _) equiv-Π• : ∀ {i₀ i₁ j₀ j₁} {R₀ : Π•-param i₀ j₀} {R₁ : Π•-param i₁ j₁} → Σ (fst R₀ ≃ fst R₁) (λ u → ∀ a → snd R₀ (<– u a) ≃• snd R₁ a) → Π• R₀ ≃• Π• R₁ equiv-Π• (u , v) = (equiv-Π u (fst ∘ v) , λ= (snd ∘ v)) -- *** Lemma 5.1 *** -- In an n-th loop space, we can forget components of truncation level n. forget-Ω^-Σ•₂ : ∀ {i j} {X : Type• i} (Q : Fam• X j) (n : ℕ) → fam-has-level (n -2) Q → (Ω ^ n) (Σ• (X , Q)) ≃• (Ω ^ n) X forget-Ω^-Σ•₂ {X = X} Q O h = (Σ₂-contr h , idp) forget-Ω^-Σ•₂ {i} {X = X} Q (S n) h = (Ω ^ (S n)) (Σ• (X , Q)) ≃•⟨ equiv-Ω^ n (Ω-Σ•-comm _) ⟩ (Ω ^ n) (Σ• (Ω X , Ω̃ Q)) ≃•⟨ forget-Ω^-Σ•₂ {i} _ n (λ _ → =-[-↓-]-level h) ⟩ (Ω ^ (S n)) X ≃•∎
[STATEMENT] lemma finite_intersection_of_complement: "(finite intersection_of P) S \<longleftrightarrow> (finite union_of (\<lambda>S. P(- S))) (- S)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (finite intersection_of P) S = (finite union_of (\<lambda>S. P (- S))) (- S) [PROOF STEP] by (simp add: finite_union_of_complement)
%+========================================================================+ %| | %| This script uses the GYPSILAB toolbox for Matlab | %| | %| COPYRIGHT : Matthieu Aussal & Francois Alouges (c) 2017-2018 | %| PROPERTY : Centre de Mathematiques Appliquees, Ecole polytechnique, | %| route de Saclay, 91128 Palaiseau, France. All rights reserved. | %| LICENCE : This program is free software, distributed in the hope that| %| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use, | %| redistribute and/or modify it under the terms of the GNU General Public| %| License, as published by the Free Software Foundation (version 3 or | %| later, http://www.gnu.org/licenses). For private use, dual licencing | %| is available, please contact us to activate a "pay for remove" option. | %| CONTACT : [email protected] | %| [email protected] | %| WEBSITE : www.cmap.polytechnique.fr/~aussal/gypsilab      | %| | %| Please acknowledge the gypsilab toolbox in programs or publications in | %| which you use it. | %|________________________________________________________________________| %| '&` | | %| # | FILE : nrtHmxFemBemEFIEhalf.m | %| # | VERSION : 0.40 | %| _#_ | AUTHOR(S) : Matthieu Aussal & Francois Alouges | %| ( # ) | CREATION : 14.03.2017 | %| / 0 \ | LAST MODIF : 14.03.2018 | %| ( === ) | SYNOPSIS : Solve fem/bem with PEC scatering problem | %| `---' | Volumic ans surfacic EFIE formulation | %+========================================================================+ % Cleaning clear all close all clc % Gypsilab path run('../../addpathGypsilab.m') %%% PREPARATION disp('~~~~~~~~~~~~~ PREPARATION ~~~~~~~~~~~~~') % Spherical mesh mesh = msh('sphere_1e3.msh'); % Normalization interior sphere mesh.vtx = mesh.vtx/0.8; % Interior boundary bound = mesh.bnd; Iint = (sum(bound.ctr.*bound.nrm,2) <= 0); int = swap(bound.sub(Iint)); % Final volumn ctr = mesh.ctr; vol = mesh.sub(ctr(:,3)>=0); % Boundaries tmp = vol.bnd; tmp1 = setdiff(int,tmp); dvol = setdiff(tmp,int); ext = union(tmp1,dvol); int = intersect(int,tmp); figure plot(ext) hold on plotNrm(ext,'w') plot(dvol,'b') plot(int,'r') axis equal alpha(0.5) % Domaine volumique omega = dom(vol,4); % Domaines surfacic sigma = dom(dvol,3); gamma = dom(ext,3); % Frequency adjusted to maximum edge size stp = mesh.stp; k = 1/stp(2); c = 299792458; f = (k*c)/(2*pi); disp(['Frequency : ',num2str(f/1e6),' MHz']); % Accuracy tol = 1e-3; disp(['Accuracy : ',num2str(tol)]); % Incident direction and field X0 = [0 0 -1]; E = [0 1 0]; % Polarization (+x for Theta-Theta and +y for Phi-Phi) H = cross(X0,E); % Incident Plane wave (electromagnetic field) PWE{1} = @(X) exp(1i*k*X*X0') * E(1); PWE{2} = @(X) exp(1i*k*X*X0') * E(2); PWE{3} = @(X) exp(1i*k*X*X0') * E(3); % Incident wave representation figure plot(ext,real(PWE{2}(ext.vtx))) title('Incident wave') xlabel('X'); ylabel('Y'); zlabel('Z'); axis equal view(0,10) %%% FORMUMATIONS disp('~~~~~~~~~~~~~ FORMULATIONS ~~~~~~~~~~~~~') % Green kernel Gxy = @(X,Y) femGreenKernel(X,Y,'[exp(ikr)/r]',k); Hxy{1} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]1',k) ; Hxy{2} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]2',k) ; Hxy{3} = @(X,Y) femGreenKernel(X,Y,'grady[exp(ikr)/r]3',k) ; % Surfacic finite elements for magnetic current Jh = fem(ext,'RWG'); N1 = size(Jh.unk,1); % Volumique finite elements for electric field Eh = fem(vol,'NED'); Eh = dirichlet(Eh,int); N2 = size(Eh.unk,1); % Restriction matrix for regularization [~,I1,I2] = intersect(Jh.unk,Eh.unk,'rows'); P = sparse(I1,I2,1,size(Jh.unk,1),size(Eh.unk,1)); % Sparse operators tic rotErotE = integral(omega,curl(Eh),curl(Eh)); EE = integral(omega,Eh,Eh); JE = integral(sigma,Jh,Eh); toc % Full operators tic JTJ = 1/(4*pi) .* integral(gamma, gamma, Jh, Gxy, Jh,tol) ... - 1/(4*pi*k^2) * integral(gamma, gamma, div(Jh), Gxy, div(Jh),tol) ; JTJ = JTJ + 1/(4*pi) * regularize(gamma, gamma, Jh, '[1/r]', Jh) ... - 1/(4*pi*k^2) * regularize(gamma, gamma, div(Jh), '[1/r]', div(Jh)); toc tic JKExn = - 1/(4*pi) * integral(gamma, sigma, Jh, Hxy, nx(Eh),tol); JKExn = JKExn - 1/(4*pi) * regularize(gamma, gamma, Jh, 'grady[1/r]', Jh) * P; toc % LHS = [A B ; C D] A = 1i*k * JTJ; size(A) B = JKExn - 0.5 * JE; size(B) C = JE.'; size(C) D = 1/(1i*k) * (rotErotE - k^2*EE); size(D) % Right hand side Y = - integral(gamma,Jh,PWE); RHS = [Y;zeros(size(D,1),1)]; %%% SOLVE LINEAR PROBLEM disp('~~~~~~~~~~~~~ SOLVE LINEAR PROBLEM ~~~~~~~~~~~~~') % Factorization LU H-Matrix tic [La,Ua] = lu(A); toc figure subplot(1,2,1) spy(La) subplot(1,2,2) spy(Ua) % Shurr complement resolution tic Sm1V = @(V) Ua\(La\V); SV = @(V) A*V - B*(D\(C*V)); J = gmres(SV,Y,[],tol,100,Sm1V); E = - D\(C*J); toc %%% INFINITE SOLUTION disp('~~~~~~~~~~~~~ INFINITE RADIATION ~~~~~~~~~~~~~') % Plane waves direction Ninf = 1e3; theta = 2*pi/1e3 .* (1:Ninf)'; nu = [sin(theta),zeros(size(theta)),cos(theta)]; % Green kernel function xdoty = @(X,Y) X(:,1).*Y(:,1) + X(:,2).*Y(:,2) + X(:,3).*Y(:,3); Ginf = @(X,Y) exp(-1i*k*xdoty(X,Y)); % Magnetic current radiation Tinf = integral(nu,gamma,Ginf,Jh); Jinf = 1i*k/(4*pi)*cross(nu, cross([Tinf{1}*J, Tinf{2}*J, Tinf{3}*J], nu)); % Electric field radiation Kinf = integral(nu,sigma,Ginf,nx(Eh)); Einf = 1i*k/(4*pi) * cross(nu, [-Kinf{1}*E, -Kinf{2}*E, -Kinf{3}*E] ); % Total electric field radiation sol = Jinf - Einf; % Radiation infinie de reference, convention e^(+ikr)/r nMax = 100; refInf = zeros(Ninf,1); if E(1) == 1 for jj = 1:Ninf refInf(jj,:) = sphereMaxwell(1, -f, theta(jj), 0.0, nMax); end else for jj = 1:Ninf [~,refInf(jj)] = sphereMaxwell(1, -f, theta(jj), pi/2, nMax); end end refInf = refInf ./ sqrt(4*pi); % Radiations infinies en X if E(1) == 1 sol = sin(theta)'.*sol(:,3) - cos(theta)'.*sol(:,1); else sol = sol(:,2); end % Erreur eL2 = norm(refInf-sol,2)/norm(refInf,2) eLINF = norm(refInf-sol,'inf')/norm(refInf,'inf') % Representation graphique figure subplot(1,2,1) plot(theta,20*log10(abs(sol)),'b',theta,20*log10(abs(refInf)),'r--') subplot(1,2,2) plot(theta,real(sol),'--b', theta,imag(sol),'--r', theta, real(refInf),':b', theta,imag(refInf),':r'); drawnow disp('~~> Michto gypsilab !')
% Version 1.000 % % Code provided by Ruslan Salakhutdinov and Geoff Hinton % % Permission is granted for anyone to copy, use, modify, or distribute this % program and accompanying programs and documents for any purpose, provided % this copyright notice is retained and prominently displayed, along with % a note saying that the original programs are available from our % web page. % The programs and documents are distributed without any warranty, express or % implied. As the programs were written for research purposes only, they have % not been tested to the degree that would be advisable in any important % application. All use of these programs is entirely at the user's own risk. function [f, df] = CG_CLASSIFY(VV,Dim,XX,target); l1 = Dim(1); l2 = Dim(2); l3= Dim(3); l4= Dim(4); l5= Dim(5); N = size(XX,1); % Do decomversion. w1 = reshape(VV(1:(l1+1)*l2),l1+1,l2); xxx = (l1+1)*l2; w2 = reshape(VV(xxx+1:xxx+(l2+1)*l3),l2+1,l3); xxx = xxx+(l2+1)*l3; w3 = reshape(VV(xxx+1:xxx+(l3+1)*l4),l3+1,l4); xxx = xxx+(l3+1)*l4; w_class = reshape(VV(xxx+1:xxx+(l4+1)*l5),l4+1,l5); XX = [XX ones(N,1)]; w1probs = 1./(1 + exp(-XX*w1)); w1probs = [w1probs ones(N,1)]; w2probs = 1./(1 + exp(-w1probs*w2)); w2probs = [w2probs ones(N,1)]; w3probs = 1./(1 + exp(-w2probs*w3)); w3probs = [w3probs ones(N,1)]; targetout = exp(w3probs*w_class); targetout = targetout./repmat(sum(targetout,2),1,10); f = -sum(sum( target(:,1:end).*log(targetout))) ; IO = (targetout-target(:,1:end)); Ix_class=IO; dw_class = w3probs'*Ix_class; Ix3 = (Ix_class*w_class').*w3probs.*(1-w3probs); Ix3 = Ix3(:,1:end-1); dw3 = w2probs'*Ix3; Ix2 = (Ix3*w3').*w2probs.*(1-w2probs); Ix2 = Ix2(:,1:end-1); dw2 = w1probs'*Ix2; Ix1 = (Ix2*w2').*w1probs.*(1-w1probs); Ix1 = Ix1(:,1:end-1); dw1 = XX'*Ix1; df = [dw1(:)' dw2(:)' dw3(:)' dw_class(:)']';
(* Title: HOL/Algebra/Sylow.thy Author: Florian Kammueller, with new proofs by L C Paulson *) theory Sylow imports Coset Exponent begin text \<open> See also @{cite "Kammueller-Paulson:1999"}. \<close> text\<open>The combinatorial argument is in theory Exponent\<close> lemma le_extend_mult: fixes c::nat shows "\<lbrakk>0 < c; a \<le> b\<rbrakk> \<Longrightarrow> a \<le> b * c" by (metis divisors_zero dvd_triv_left leI less_le_trans nat_dvd_not_less zero_less_iff_neq_zero) locale sylow = group + fixes p and a and m and calM and RelM assumes prime_p: "prime p" and order_G: "order(G) = (p^a) * m" and finite_G [iff]: "finite (carrier G)" defines "calM == {s. s \<subseteq> carrier(G) & card(s) = p^a}" and "RelM == {(N1,N2). N1 \<in> calM & N2 \<in> calM & (\<exists>g \<in> carrier(G). N1 = (N2 #> g) )}" begin lemma RelM_refl_on: "refl_on calM RelM" apply (auto simp add: refl_on_def RelM_def calM_def) apply (blast intro!: coset_mult_one [symmetric]) done lemma RelM_sym: "sym RelM" proof (unfold sym_def RelM_def, clarify) fix y g assume "y \<in> calM" and g: "g \<in> carrier G" hence "y = y #> g #> (inv g)" by (simp add: coset_mult_assoc calM_def) thus "\<exists>g'\<in>carrier G. y = y #> g #> g'" by (blast intro: g) qed lemma RelM_trans: "trans RelM" by (auto simp add: trans_def RelM_def calM_def coset_mult_assoc) lemma RelM_equiv: "equiv calM RelM" apply (unfold equiv_def) apply (blast intro: RelM_refl_on RelM_sym RelM_trans) done lemma M_subset_calM_prep: "M' \<in> calM // RelM ==> M' \<subseteq> calM" apply (unfold RelM_def) apply (blast elim!: quotientE) done end subsection\<open>Main Part of the Proof\<close> locale sylow_central = sylow + fixes H and M1 and M assumes M_in_quot: "M \<in> calM // RelM" and not_dvd_M: "~(p ^ Suc(multiplicity p m) dvd card(M))" and M1_in_M: "M1 \<in> M" defines "H == {g. g\<in>carrier G & M1 #> g = M1}" begin lemma M_subset_calM: "M \<subseteq> calM" by (rule M_in_quot [THEN M_subset_calM_prep]) lemma card_M1: "card(M1) = p^a" using M1_in_M M_subset_calM calM_def by blast lemma exists_x_in_M1: "\<exists>x. x \<in> M1" using prime_p [THEN prime_gt_Suc_0_nat] card_M1 by (metis Suc_lessD card_eq_0_iff empty_subsetI equalityI gr_implies_not0 nat_zero_less_power_iff subsetI) lemma M1_subset_G [simp]: "M1 \<subseteq> carrier G" using M1_in_M M_subset_calM calM_def mem_Collect_eq subsetCE by blast lemma M1_inj_H: "\<exists>f \<in> H\<rightarrow>M1. inj_on f H" proof - from exists_x_in_M1 obtain m1 where m1M: "m1 \<in> M1".. have m1G: "m1 \<in> carrier G" by (simp add: m1M M1_subset_G [THEN subsetD]) show ?thesis proof show "inj_on (\<lambda>z\<in>H. m1 \<otimes> z) H" by (simp add: inj_on_def l_cancel [of m1 x y, THEN iffD1] H_def m1G) show "restrict (op \<otimes> m1) H \<in> H \<rightarrow> M1" proof (rule restrictI) fix z assume zH: "z \<in> H" show "m1 \<otimes> z \<in> M1" proof - from zH have zG: "z \<in> carrier G" and M1zeq: "M1 #> z = M1" by (auto simp add: H_def) show ?thesis by (rule subst [OF M1zeq], simp add: m1M zG rcosI) qed qed qed qed end subsection\<open>Discharging the Assumptions of \<open>sylow_central\<close>\<close> context sylow begin lemma EmptyNotInEquivSet: "{} \<notin> calM // RelM" by (blast elim!: quotientE dest: RelM_equiv [THEN equiv_class_self]) lemma existsM1inM: "M \<in> calM // RelM ==> \<exists>M1. M1 \<in> M" using RelM_equiv equiv_Eps_in by blast lemma zero_less_o_G: "0 < order(G)" by (simp add: order_def card_gt_0_iff carrier_not_empty) lemma zero_less_m: "m > 0" using zero_less_o_G by (simp add: order_G) lemma card_calM: "card(calM) = (p^a) * m choose p^a" by (simp add: calM_def n_subsets order_G [symmetric] order_def) lemma zero_less_card_calM: "card calM > 0" by (simp add: card_calM zero_less_binomial le_extend_mult zero_less_m) lemma max_p_div_calM: "~ (p ^ Suc(multiplicity p m) dvd card(calM))" proof assume "p ^ Suc (multiplicity p m) dvd card calM" with zero_less_card_calM prime_p have "Suc (multiplicity p m) \<le> multiplicity p (card calM)" by (intro multiplicity_geI) auto hence "multiplicity p m < multiplicity p (card calM)" by simp also have "multiplicity p m = multiplicity p (card calM)" by (simp add: const_p_fac prime_p zero_less_m card_calM) finally show False by simp qed lemma finite_calM: "finite calM" unfolding calM_def by (rule_tac B = "Pow (carrier G) " in finite_subset) auto lemma lemma_A1: "\<exists>M \<in> calM // RelM. ~ (p ^ Suc(multiplicity p m) dvd card(M))" using RelM_equiv equiv_imp_dvd_card finite_calM max_p_div_calM by blast end subsubsection\<open>Introduction and Destruct Rules for @{term H}\<close> lemma (in sylow_central) H_I: "[|g \<in> carrier G; M1 #> g = M1|] ==> g \<in> H" by (simp add: H_def) lemma (in sylow_central) H_into_carrier_G: "x \<in> H ==> x \<in> carrier G" by (simp add: H_def) lemma (in sylow_central) in_H_imp_eq: "g : H ==> M1 #> g = M1" by (simp add: H_def) lemma (in sylow_central) H_m_closed: "[| x\<in>H; y\<in>H|] ==> x \<otimes> y \<in> H" apply (unfold H_def) apply (simp add: coset_mult_assoc [symmetric]) done lemma (in sylow_central) H_not_empty: "H \<noteq> {}" apply (simp add: H_def) apply (rule exI [of _ \<one>], simp) done lemma (in sylow_central) H_is_subgroup: "subgroup H G" apply (rule subgroupI) apply (rule subsetI) apply (erule H_into_carrier_G) apply (rule H_not_empty) apply (simp add: H_def, clarify) apply (erule_tac P = "%z. lhs(z) = M1" for lhs in subst) apply (simp add: coset_mult_assoc ) apply (blast intro: H_m_closed) done lemma (in sylow_central) rcosetGM1g_subset_G: "[| g \<in> carrier G; x \<in> M1 #> g |] ==> x \<in> carrier G" by (blast intro: M1_subset_G [THEN r_coset_subset_G, THEN subsetD]) lemma (in sylow_central) finite_M1: "finite M1" by (rule finite_subset [OF M1_subset_G finite_G]) lemma (in sylow_central) finite_rcosetGM1g: "g\<in>carrier G ==> finite (M1 #> g)" using rcosetGM1g_subset_G finite_G M1_subset_G cosets_finite rcosetsI by blast lemma (in sylow_central) M1_cardeq_rcosetGM1g: "g \<in> carrier G ==> card(M1 #> g) = card(M1)" by (simp (no_asm_simp) add: card_cosets_equal rcosetsI) lemma (in sylow_central) M1_RelM_rcosetGM1g: "g \<in> carrier G ==> (M1, M1 #> g) \<in> RelM" apply (simp add: RelM_def calM_def card_M1) apply (rule conjI) apply (blast intro: rcosetGM1g_subset_G) apply (simp add: card_M1 M1_cardeq_rcosetGM1g) apply (metis M1_subset_G coset_mult_assoc coset_mult_one r_inv_ex) done subsection\<open>Equal Cardinalities of @{term M} and the Set of Cosets\<close> text\<open>Injections between @{term M} and @{term "rcosets\<^bsub>G\<^esub> H"} show that their cardinalities are equal.\<close> lemma ElemClassEquiv: "[| equiv A r; C \<in> A // r |] ==> \<forall>x \<in> C. \<forall>y \<in> C. (x,y)\<in>r" by (unfold equiv_def quotient_def sym_def trans_def, blast) lemma (in sylow_central) M_elem_map: "M2 \<in> M ==> \<exists>g. g \<in> carrier G & M1 #> g = M2" apply (cut_tac M1_in_M M_in_quot [THEN RelM_equiv [THEN ElemClassEquiv]]) apply (simp add: RelM_def) apply (blast dest!: bspec) done lemmas (in sylow_central) M_elem_map_carrier = M_elem_map [THEN someI_ex, THEN conjunct1] lemmas (in sylow_central) M_elem_map_eq = M_elem_map [THEN someI_ex, THEN conjunct2] lemma (in sylow_central) M_funcset_rcosets_H: "(%x:M. H #> (SOME g. g \<in> carrier G & M1 #> g = x)) \<in> M \<rightarrow> rcosets H" by (metis (lifting) H_is_subgroup M_elem_map_carrier rcosetsI restrictI subgroup_imp_subset) lemma (in sylow_central) inj_M_GmodH: "\<exists>f \<in> M \<rightarrow> rcosets H. inj_on f M" apply (rule bexI) apply (rule_tac [2] M_funcset_rcosets_H) apply (rule inj_onI, simp) apply (rule trans [OF _ M_elem_map_eq]) prefer 2 apply assumption apply (rule M_elem_map_eq [symmetric, THEN trans], assumption) apply (rule coset_mult_inv1) apply (erule_tac [2] M_elem_map_carrier)+ apply (rule_tac [2] M1_subset_G) apply (rule coset_join1 [THEN in_H_imp_eq]) apply (rule_tac [3] H_is_subgroup) prefer 2 apply (blast intro: M_elem_map_carrier) apply (simp add: coset_mult_inv2 H_def M_elem_map_carrier subset_eq) done subsubsection\<open>The Opposite Injection\<close> lemma (in sylow_central) H_elem_map: "H1 \<in> rcosets H ==> \<exists>g. g \<in> carrier G & H #> g = H1" by (auto simp add: RCOSETS_def) lemmas (in sylow_central) H_elem_map_carrier = H_elem_map [THEN someI_ex, THEN conjunct1] lemmas (in sylow_central) H_elem_map_eq = H_elem_map [THEN someI_ex, THEN conjunct2] lemma (in sylow_central) rcosets_H_funcset_M: "(\<lambda>C \<in> rcosets H. M1 #> (@g. g \<in> carrier G \<and> H #> g = C)) \<in> rcosets H \<rightarrow> M" apply (simp add: RCOSETS_def) apply (fast intro: someI2 intro!: M1_in_M in_quotient_imp_closed [OF RelM_equiv M_in_quot _ M1_RelM_rcosetGM1g]) done text\<open>close to a duplicate of \<open>inj_M_GmodH\<close>\<close> lemma (in sylow_central) inj_GmodH_M: "\<exists>g \<in> rcosets H\<rightarrow>M. inj_on g (rcosets H)" apply (rule bexI) apply (rule_tac [2] rcosets_H_funcset_M) apply (rule inj_onI) apply (simp) apply (rule trans [OF _ H_elem_map_eq]) prefer 2 apply assumption apply (rule H_elem_map_eq [symmetric, THEN trans], assumption) apply (rule coset_mult_inv1) apply (erule_tac [2] H_elem_map_carrier)+ apply (rule_tac [2] H_is_subgroup [THEN subgroup.subset]) apply (rule coset_join2) apply (blast intro: H_elem_map_carrier) apply (rule H_is_subgroup) apply (simp add: H_I coset_mult_inv2 H_elem_map_carrier) done lemma (in sylow_central) calM_subset_PowG: "calM \<subseteq> Pow(carrier G)" by (auto simp add: calM_def) lemma (in sylow_central) finite_M: "finite M" by (metis M_subset_calM finite_calM rev_finite_subset) lemma (in sylow_central) cardMeqIndexH: "card(M) = card(rcosets H)" apply (insert inj_M_GmodH inj_GmodH_M) apply (blast intro: card_bij finite_M H_is_subgroup rcosets_subset_PowG [THEN finite_subset] finite_Pow_iff [THEN iffD2]) done lemma (in sylow_central) index_lem: "card(M) * card(H) = order(G)" by (simp add: cardMeqIndexH lagrange H_is_subgroup) lemma (in sylow_central) lemma_leq1: "p^a \<le> card(H)" apply (rule dvd_imp_le) apply (rule div_combine [OF prime_imp_prime_elem[OF prime_p] not_dvd_M]) prefer 2 apply (blast intro: subgroup.finite_imp_card_positive H_is_subgroup) apply (simp add: index_lem order_G power_add mult_dvd_mono multiplicity_dvd zero_less_m) done lemma (in sylow_central) lemma_leq2: "card(H) \<le> p^a" apply (subst card_M1 [symmetric]) apply (cut_tac M1_inj_H) apply (blast intro!: M1_subset_G intro: card_inj H_into_carrier_G finite_subset [OF _ finite_G]) done lemma (in sylow_central) card_H_eq: "card(H) = p^a" by (blast intro: le_antisym lemma_leq1 lemma_leq2) lemma (in sylow) sylow_thm: "\<exists>H. subgroup H G & card(H) = p^a" apply (cut_tac lemma_A1, clarify) apply (frule existsM1inM, clarify) apply (subgoal_tac "sylow_central G p a m M1 M") apply (blast dest: sylow_central.H_is_subgroup sylow_central.card_H_eq) apply (simp add: sylow_central_def sylow_central_axioms_def sylow_axioms calM_def RelM_def) done text\<open>Needed because the locale's automatic definition refers to @{term "semigroup G"} and @{term "group_axioms G"} rather than simply to @{term "group G"}.\<close> lemma sylow_eq: "sylow G p a m = (group G & sylow_axioms G p a m)" by (simp add: sylow_def group_def) subsection \<open>Sylow's Theorem\<close> theorem sylow_thm: "[| prime p; group(G); order(G) = (p^a) * m; finite (carrier G)|] ==> \<exists>H. subgroup H G & card(H) = p^a" apply (rule sylow.sylow_thm [of G p a m]) apply (simp add: sylow_eq sylow_axioms_def) done end
Require Import Bool String List. Require Import Lib.CommonTactics Lib.ilist Lib.Word. Require Import Lib.Struct Lib.FMap Lib.StringEq Lib.Indexer. Require Import Kami.Syntax Kami.Semantics Kami.RefinementFacts Kami.Renaming Kami.Wf. Require Import Kami.Renaming Kami.Specialize Kami.Inline Kami.InlineFacts Kami.Decomposition. Require Import Kami.Tactics Kami.Notations Kami.PrimBram. Require Import Ex.MemTypes Ex.SC Ex.NativeFifo Ex.MemAsync Ex.ProcFetch Ex.ProcFInl. Require Import Eqdep ProofIrrelevance. Set Implicit Arguments. Section Invariants. Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat. Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes). Variable (f2dElt: Kind). Variable (f2dPack: forall ty, Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *) Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *) Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *) Expr ty (SyntaxKind Bool) -> (* epoch *) Expr ty (SyntaxKind f2dElt)). Variables (f2dRawInst: forall ty, fullType ty (SyntaxKind f2dElt) -> Expr ty (SyntaxKind (Data instBytes))) (f2dCurPc: forall ty, fullType ty (SyntaxKind f2dElt) -> Expr ty (SyntaxKind (Pc addrSize))) (f2dNextPc: forall ty, fullType ty (SyntaxKind f2dElt) -> Expr ty (SyntaxKind (Pc addrSize))) (f2dEpoch: forall ty, fullType ty (SyntaxKind f2dElt) -> Expr ty (SyntaxKind Bool)). Context {indexSize tagSize: nat}. Variables (getIndex: forall ty, fullType ty (SyntaxKind (Bit addrSize)) -> Expr ty (SyntaxKind (Bit indexSize))) (getTag: forall ty, fullType ty (SyntaxKind (Bit addrSize)) -> Expr ty (SyntaxKind (Bit tagSize))). Variables (pcInit : ConstT (Pc addrSize)). Definition fetchICacheInl := projT1 (fetchICacheInl fetch f2dPack getIndex getTag pcInit). Record fetchICache_inv (o: RegsT) : Prop := { pcv : fullType type (SyntaxKind (Pc addrSize)); Hpcv : M.find "pc"%string o = Some (existT _ _ pcv); pinitv : fullType type (SyntaxKind Bool); Hpinitv : M.find "pinit"%string o = Some (existT _ _ pinitv); pinitRqv : fullType type (SyntaxKind Bool); HpinitRqv : M.find "pinitRq"%string o = Some (existT _ _ pinitRqv); pinitRqOfsv : fullType type (SyntaxKind (Bit iaddrSize)); HpinitRqOfsv : M.find "pinitRqOfs"%string o = Some (existT _ _ pinitRqOfsv); pinitRsOfsv : fullType type (SyntaxKind (Bit iaddrSize)); HpinitRsOfsv : M.find "pinitRsOfs"%string o = Some (existT _ _ pinitRsOfsv); fepochv : fullType type (SyntaxKind Bool); Hfepochv : M.find "fEpoch"%string o = Some (existT _ _ fepochv); pcuv : fullType type (SyntaxKind Bool); Hpcuv : M.find "pcUpdated"%string o = Some (existT _ _ pcuv); bramv : fullType type (SyntaxKind (Vector (Data instBytes) iaddrSize)); Hbramv : M.find "pgm"--"bram" o = Some (existT _ _ bramv); breadv : fullType type (bramReadValK (Data instBytes) type); Hbreadv : M.find "pgm"--"readVal" o = Some (existT _ _ breadv); Hinv0 : pinitv = false -> breadv = None; Hinv1 : pinitv = true -> pcuv = false -> match breadv with | Some val => val = bramv (evalExpr (toIAddr _ pcv)) | None => True end }. Ltac fetchICache_inv_old := repeat match goal with | [H: fetchICache_inv _ |- _] => destruct H end; kinv_red. Ltac fetchICache_inv_new := econstructor; (* let's prove that the invariant holds for the next state *) try (findReify; (reflexivity || eassumption); fail); kinv_red; (* unfolding invariant definitions *) try eassumption; intros; try reflexivity. (* intuition kinv_simpl; intuition idtac. *) Ltac fetchICache_inv_tac := fetchICache_inv_old; fetchICache_inv_new. Lemma fetchICache_inv_ok': forall init n ll, init = initRegs (getRegInits fetchICacheInl) -> Multistep fetchICacheInl init n ll -> fetchICache_inv n. Proof. (* SKIP_PROOF_ON induction 2. - fetchICache_inv_old. unfold getRegInits, fetchICacheInl, ProcFInl.fetchICacheInl, projT1. fetchICache_inv_new. - kinvert. + mred. + mred. + kinv_dest_custom fetchICache_inv_tac. + kinv_dest_custom fetchICache_inv_tac. + kinv_dest_custom fetchICache_inv_tac. + kinv_dest_custom fetchICache_inv_tac. + kinv_dest_custom fetchICache_inv_tac. + kinv_dest_custom fetchICache_inv_tac. + kinv_dest_custom fetchICache_inv_tac. + kinv_dest_custom fetchICache_inv_tac. END_SKIP_PROOF_ON *) apply cheat. Qed. Lemma fetchICache_inv_ok: forall o, reachable o fetchICacheInl -> fetchICache_inv o. Proof. intros; inv H; inv H0. eapply fetchICache_inv_ok'; eauto. Qed. End Invariants.
module lambda.vec where open import Data.Nat open import Data.Fin hiding (_+_) infixr 40 _▸_ data vec (T : Set) : ℕ → Set where ε : vec T 0 _▸_ : ∀ {n} → vec T n → T → vec T (suc n) lookup : ∀ {n} → {T : Set} → Fin n → vec T n → T lookup zero (Γ ▸ x) = x lookup (suc i) (Γ ▸ x) = lookup i Γ
% ========== Chapter on paired pulse stimulation \chapter {Paired pulse conditioning paradigms for in-vivo plasticity induction in humans} Appropriately timed stimulation protocols can induce plasticity changes in cortex. The best parameters to elicit measurable changes in cortical excitability, with potential positive functional rehabilitation outcomes, are unknown. Both animal work, as well as theoretical modeling, need to be translated to humans. Here we implement paired pulse conditioning paradigms with different parameters in a human, intraoperative setting to induce changes in cortical plasticity. The key parameters tested are the use of paired bipolar pairs, as well as single bipolar pairs, as well as time lags ranging from 25 ms to 200 ms between conditioning pulses. We assess excitability changes through measuring cortically evoked potentials (CEPs). We perform these conditioning experiments in patients with both Essential Tremor and Parkinson’s disease, and under varying states of anesthesia. We note minimal impact within a subject on cortical excitability during different levels of anesthesia, suggesting that intraoperative CEP paradigms reveal meaningful connectivity patterns that could translate to neuroprosthetics in awake individuals. We observe a trend towards conditioning paradigms with 200 ms delays resulting in greater degrees of change than 25 ms conditions, and a trend towards paired stimulation between sites being more effective than single site stimulation. Additionally, we observe statistically significant changes in excitability in some patients, and not others. These results speak to the complex network dynamics affected by cortical stimulation at the length scale of clinical iEEG electrodes, as well as the area depolarized by direct cortical stimulation. \section{Introduction} A potential protocol to induce plasticity between regions is paired pulse stimulation. This technique has been shown in rodent models with micro-stimulation to drive changes in plasticity in sensorimotor cortex \cite{Rebesco2010}. Recently, this work has been extended into a primate model \cite{Seeman2017}. A key advantage of this method is the simplicity of hardware programming that would be required for implementation, as the only requirements are the delivery of stimuli to two sites with a consistent, known delay. Demonstration of this protocl \section{Methods} \subsection{Electrode Strips} We used the ECoG electrodes placed intraoperatively with 8 contact electrode strips, with 10 mm spacing between electrodes (Ad-tech Medical, Racine, WI), and either 1.8 mm or 2.3 mm diameter exposed platinum contacts. These electrodes were placed by the neurosurgeon via a burr hole using standard techniques. The ECoG strip was removed at the end of surgery \subsection{Recording and Stimulation} We used the Tucker-Davis Technologies (TDT, Alachua, Fl) hardware suite for recording and stimulation (Model RZ5D digital signal processor/ controller, PZ5-128 channel biosignal amplifier, IZ2H-16 channel stimulator, and the LZ48-400 battery pack) controlled with a PC running the proprietary TDT software suite. We recorded raw neural data at 12207 Hz to resolve short-latency signal components and for artifact suppression. We employed a constant-current stimulation mode, which delivered voltage to meet a given current requirement. Our pulse duration ranged from 200 $\mu s$ to 1000 $\mu s$ for each phase of our biphasic, bipolar rectangular pulse stimulation. \subsection{Screening} Patients undergoing DBS surgery have an 8 contact ECOG strips placed intraoperatively during surgery. In a subset of patients, we located the central sulcus, and corresponding sensory and motor regions using somatosensory evoked potential. We then test bipolar stimulation pairs in sensory, motor, and premotor cortex to elicit EPs in adjacent contacts (Figure \ref{fig:pairedPulseScreening}). Once we find a pair (site A) that reliably elicits EPs in a different electrode, we consider this to be the location from which we are trying to drive plasticity. \begin{figure}[ht] \centering \includegraphics[width=0.8\textwidth]{figures/pairedPulse/pairPulseScreening} \caption[Paired pulse screening protocol]{The first step in the paradigm is localization of sensory cortex via phase reversal through SSEP testing. The next is assessing baseline cortical excitability through EP screening, and subsequent EP testing at four different amplitude levels} \label{fig:pairedPulseScreening} \end{figure} \subsection{Conditioning and Testing} Once EPs have been localized, we proceed to a paired pulse conditioning paradigm, inspired by Seeman et al. 2017. We apply 3 pulses at 330 Hz in 2 Hz intervals to both site A and site B, with site A leading site B stimulation by 25 or 200 ms (Figure \ref{fig:pairedPulseConditioning}). We carry out the conditioning for between 5 and 20 minutes, depending on operating room constraints. \begin{figure}[ht] \centering \includegraphics[width=0.8\textwidth]{figures/pairedPulse/pairPulseConditioning} \caption[Different Paired Pulse Conditioning Protocols]{The first step in the paradigm is localization of sensory cortex via phase reversal through SSEP testing. The next is assessing baseline cortical excitability through EP screening, and subsequent EP testing at four different amplitude levels} \label{fig:pairedPulseConditioning} \end{figure} In the second set of experiments, we will condition Site A and Site B with a lag of 100 ms following Site A and Site B , which as mentioned above, should not result in facilitation of responses as a control. If possible with time constraints, we will carry out the same conditioning paradigm, except with stimulation at site B leading stimulation at site A by 25 ms with the same stimulation parameters as mentioned above. This hypothetically will result in LTD, but from the primate work, it would not be expected to be a robust effect. We will then test MEPs and EPs again at both sites A and B. One concern is the fact that our potential patients are under anesthesia during DBS electrode implantation, ECoG strip placement, and recording. However, from prior animal work, we expect the MEP results from the anesthetized subjects to be applicable to our human patients (Sykes 2016). Additionally, the clinical team will attempt to keep the depth of anesthesia low to minimize reductions in cortical excitability. \subsection{Data Analysis} We discard any peak-to-peak values with magnitudes below 25 $ \mu V $ or above 1500 $ \mu V $. \section{Results} In one Essential Tremor patient brought in and out of anesthesia during evoked potential measurement, we observed no statistically significant changes in the peak-to-peak magnitude of the EPs during different levels of anesthesia induction (Figure ???). This suggests that EPs elicited during anesthesia would be transferable to those in an awake state, suggesting that intraoperative EP screening during neuromodulation device placement could be informative for \section{Discussion} \section{Conclusions} For the first time in humans, we measure intraoperative cortically evoked potentials (CEPs, or EPs), which are a marker of cortical excitability and connectivity, during DBS surgery. We observe the greater density of intraoperatively measured responses in premotor/motor/sensory cortices. We are able to modulate CEPs with paired-pulse conditioning protocols. In contrast to previous primate literature, we observe greater potentiation at longer delays between stimulation sites, suggesting that the mechanisms responsible are less dependent on spike-timing dependent plasticity and rather on larger network scale phenomena due to the scale of our stimulation electrodes and larger areas of cortex targeted. EP magnitudes during various levels of responsiveness do not change, suggesting that intraoperative screening for EPs could be illustrative of connectivity during awake states. We observe a greater effect of conditioning with longer conditioning protocols, suggesting there is a total stimulation dosage effect. These studies further our understanding of plasticity induction in humans, and pave the way for future exploration of how to enhance cortical connections in a rehabilitation context following neurological damage from diseases such as stroke. \section{Supplemental Information}
[STATEMENT] lemma Fourier_sum_offset_Dirichlet_kernel: assumes f: "f absolutely_integrable_on {-pi..pi}" and periodic: "\<And>x. f(x + 2*pi) = f x" shows "(\<Sum>k\<le>2*n. Fourier_coefficient f k * trigonometric_set k t) = integral\<^sup>L (lebesgue_on {-pi..pi}) (\<lambda>x. Dirichlet_kernel n x * f(x+t)) / pi" (is "?lhs = ?rhs") [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have ft: "(\<lambda>x. f(x+t)) absolutely_integrable_on {-pi..pi}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<lambda>x. f (x + t)) absolutely_integrable_on {- pi..pi} [PROOF STEP] using absolutely_integrable_periodic_offset [OF f, of t] periodic [PROOF STATE] proof (prove) using this: (\<And>x. f (x + (pi - - pi)) = f x) \<Longrightarrow> (\<lambda>x. f (x + t)) absolutely_integrable_on {- pi..pi} (\<And>x. f (x + (pi - - pi)) = f x) \<Longrightarrow> (\<lambda>x. f (t + x)) absolutely_integrable_on {- pi..pi} f (?x + 2 * pi) = f ?x goal (1 subgoal): 1. (\<lambda>x. f (x + t)) absolutely_integrable_on {- pi..pi} [PROOF STEP] by simp [PROOF STATE] proof (state) this: (\<lambda>x. f (x + t)) absolutely_integrable_on {- pi..pi} goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have "?lhs = (\<Sum>k=0..n. Fourier_coefficient (\<lambda>x. f(x+t)) (2*k) * trigonometric_set (2*k) 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (\<Sum>k = 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) * trigonometric_set (2 * k) 0) [PROOF STEP] using Fourier_sum_offset_unpaired assms atMost_atLeast0 [PROOF STATE] proof (prove) using this: \<lbrakk>?f absolutely_integrable_on {- pi..pi}; \<And>x. ?f (x + 2 * pi) = ?f x\<rbrakk> \<Longrightarrow> (\<Sum>k\<le>2 * ?n. Fourier_coefficient ?f k * trigonometric_set k ?t) = (\<Sum>k\<le>?n. Fourier_coefficient (\<lambda>x. ?f (x + ?t)) (2 * k) * trigonometric_set (2 * k) 0) f absolutely_integrable_on {- pi..pi} f (?x + 2 * pi) = f ?x {..?n} = {0..?n} goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (\<Sum>k = 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) * trigonometric_set (2 * k) 0) [PROOF STEP] by auto [PROOF STATE] proof (state) this: (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (\<Sum>k = 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) * trigonometric_set (2 * k) 0) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] also [PROOF STATE] proof (state) this: (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (\<Sum>k = 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) * trigonometric_set (2 * k) 0) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have "\<dots> = Fourier_coefficient (\<lambda>x. f(x+t)) 0 / sqrt (2 * pi) + (\<Sum>k = Suc 0..n. Fourier_coefficient (\<lambda>x. f(x+t)) (2*k) / sqrt pi)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<Sum>k = 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) * trigonometric_set (2 * k) 0) = Fourier_coefficient (\<lambda>x. f (x + t)) 0 / sqrt (2 * pi) + (\<Sum>k = Suc 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) / sqrt pi) [PROOF STEP] by (simp add: sum.atLeast_Suc_atMost trigonometric_set_def) [PROOF STATE] proof (state) this: (\<Sum>k = 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) * trigonometric_set (2 * k) 0) = Fourier_coefficient (\<lambda>x. f (x + t)) 0 / sqrt (2 * pi) + (\<Sum>k = Suc 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) / sqrt pi) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] also [PROOF STATE] proof (state) this: (\<Sum>k = 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) * trigonometric_set (2 * k) 0) = Fourier_coefficient (\<lambda>x. f (x + t)) 0 / sqrt (2 * pi) + (\<Sum>k = Suc 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) / sqrt pi) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have "\<dots> = (LINT x|lebesgue_on {-pi..pi}. f(x+t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {-pi..pi}. cos (real k * x) * f(x+t)) / pi)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Fourier_coefficient (\<lambda>x. f (x + t)) 0 / sqrt (2 * pi) + (\<Sum>k = Suc 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) / sqrt pi) = (LINT x|lebesgue_on {- pi..pi}. f (x + t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {- pi..pi}. cos (real k * x) * f (x + t)) / pi) [PROOF STEP] by (simp add: Fourier_coefficient_def orthonormal_coeff_def trigonometric_set_def l2product_def) [PROOF STATE] proof (state) this: Fourier_coefficient (\<lambda>x. f (x + t)) 0 / sqrt (2 * pi) + (\<Sum>k = Suc 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) / sqrt pi) = (LINT x|lebesgue_on {- pi..pi}. f (x + t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {- pi..pi}. cos (real k * x) * f (x + t)) / pi) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] also [PROOF STATE] proof (state) this: Fourier_coefficient (\<lambda>x. f (x + t)) 0 / sqrt (2 * pi) + (\<Sum>k = Suc 0..n. Fourier_coefficient (\<lambda>x. f (x + t)) (2 * k) / sqrt pi) = (LINT x|lebesgue_on {- pi..pi}. f (x + t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {- pi..pi}. cos (real k * x) * f (x + t)) / pi) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have "\<dots> = LINT x|lebesgue_on {-pi..pi}. f(x+t) / (2 * pi) + (\<Sum>k = Suc 0..n. (cos (real k * x) * f(x+t)) / pi)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (LINT x|lebesgue_on {- pi..pi}. f (x + t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {- pi..pi}. cos (real k * x) * f (x + t)) / pi) = LINT x|lebesgue_on {- pi..pi}. f (x + t) / (2 * pi) + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t) / pi) [PROOF STEP] using Fourier_products_integrable_cos [OF ft] absolutely_integrable_imp_integrable [OF ft] [PROOF STATE] proof (prove) using this: integrable (lebesgue_on {- pi..pi}) (\<lambda>x. cos (?k * x) * f (x + t)) {- pi..pi} \<in> sets lebesgue \<Longrightarrow> integrable (lebesgue_on {- pi..pi}) (\<lambda>x. f (x + t)) goal (1 subgoal): 1. (LINT x|lebesgue_on {- pi..pi}. f (x + t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {- pi..pi}. cos (real k * x) * f (x + t)) / pi) = LINT x|lebesgue_on {- pi..pi}. f (x + t) / (2 * pi) + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t) / pi) [PROOF STEP] by simp [PROOF STATE] proof (state) this: (LINT x|lebesgue_on {- pi..pi}. f (x + t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {- pi..pi}. cos (real k * x) * f (x + t)) / pi) = LINT x|lebesgue_on {- pi..pi}. f (x + t) / (2 * pi) + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t) / pi) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] also [PROOF STATE] proof (state) this: (LINT x|lebesgue_on {- pi..pi}. f (x + t)) / (2 * pi) + (\<Sum>k = Suc 0..n. (LINT x|lebesgue_on {- pi..pi}. cos (real k * x) * f (x + t)) / pi) = LINT x|lebesgue_on {- pi..pi}. f (x + t) / (2 * pi) + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t) / pi) goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have "\<dots> = (LINT x|lebesgue_on {-pi..pi}. f(x+t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f(x+t))) / pi" [PROOF STATE] proof (prove) goal (1 subgoal): 1. LINT x|lebesgue_on {- pi..pi}. f (x + t) / (2 * pi) + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t) / pi) = (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi [PROOF STEP] by (simp add: divide_simps sum_distrib_right mult.assoc) [PROOF STATE] proof (state) this: LINT x|lebesgue_on {- pi..pi}. f (x + t) / (2 * pi) + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t) / pi) = (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] also [PROOF STATE] proof (state) this: LINT x|lebesgue_on {- pi..pi}. f (x + t) / (2 * pi) + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t) / pi) = (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have "\<dots> = ?rhs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] have "LINT x|lebesgue_on {-pi..pi}. f(x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f(x + t)) = LINT x|lebesgue_on {-pi..pi}. Dirichlet_kernel n x * f(x + t)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) [PROOF STEP] have eq: "f(x+t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f(x + t)) = Dirichlet_kernel n x * f(x + t)" if "- pi \<le> x" "x \<le> pi" for x [PROOF STATE] proof (prove) goal (1 subgoal): 1. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) [PROOF STEP] proof (cases "x = 0") [PROOF STATE] proof (state) goal (2 subgoals): 1. x = 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) 2. x \<noteq> 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) [PROOF STEP] case False [PROOF STATE] proof (state) this: x \<noteq> 0 goal (2 subgoals): 1. x = 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) 2. x \<noteq> 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: x \<noteq> 0 [PROOF STEP] have "sin (x/2) \<noteq> 0" [PROOF STATE] proof (prove) using this: x \<noteq> 0 goal (1 subgoal): 1. sin (x / 2) \<noteq> 0 [PROOF STEP] using that [PROOF STATE] proof (prove) using this: x \<noteq> 0 - pi \<le> x x \<le> pi goal (1 subgoal): 1. sin (x / 2) \<noteq> 0 [PROOF STEP] by (auto simp: sin_zero_iff) [PROOF STATE] proof (state) this: sin (x / 2) \<noteq> 0 goal (2 subgoals): 1. x = 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) 2. x \<noteq> 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: sin (x / 2) \<noteq> 0 [PROOF STEP] have "f(x + t) * (1/2 + (\<Sum>k = Suc 0..n. cos(real k * x))) = f(x + t) * sin((real n + 1/2) * x) / 2 / sin(x/2)" [PROOF STATE] proof (prove) using this: sin (x / 2) \<noteq> 0 goal (1 subgoal): 1. f (x + t) * (1 / 2 + (\<Sum>k = Suc 0..n. cos (real k * x))) = f (x + t) * sin ((real n + 1 / 2) * x) / 2 / sin (x / 2) [PROOF STEP] using cosine_sum_lemma [of x n] [PROOF STATE] proof (prove) using this: sin (x / 2) \<noteq> 0 (1 / 2 + (\<Sum>k = Suc 0..n. cos (real k * x))) * sin (x / 2) = sin ((real n + 1 / 2) * x) / 2 goal (1 subgoal): 1. f (x + t) * (1 / 2 + (\<Sum>k = Suc 0..n. cos (real k * x))) = f (x + t) * sin ((real n + 1 / 2) * x) / 2 / sin (x / 2) [PROOF STEP] by (simp add: divide_simps) [PROOF STATE] proof (state) this: f (x + t) * (1 / 2 + (\<Sum>k = Suc 0..n. cos (real k * x))) = f (x + t) * sin ((real n + 1 / 2) * x) / 2 / sin (x / 2) goal (2 subgoals): 1. x = 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) 2. x \<noteq> 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: f (x + t) * (1 / 2 + (\<Sum>k = Suc 0..n. cos (real k * x))) = f (x + t) * sin ((real n + 1 / 2) * x) / 2 / sin (x / 2) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: f (x + t) * (1 / 2 + (\<Sum>k = Suc 0..n. cos (real k * x))) = f (x + t) * sin ((real n + 1 / 2) * x) / 2 / sin (x / 2) goal (1 subgoal): 1. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) [PROOF STEP] by (simp add: Dirichlet_kernel_def False field_simps sum_distrib_left) [PROOF STATE] proof (state) this: f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) goal (1 subgoal): 1. x = 0 \<Longrightarrow> f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = Dirichlet_kernel n x * f (x + t) [PROOF STEP] qed (simp add: Dirichlet_kernel_def algebra_simps) [PROOF STATE] proof (state) this: \<lbrakk>- pi \<le> ?x; ?x \<le> pi\<rbrakk> \<Longrightarrow> f (?x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * ?x) * f (?x + t)) = Dirichlet_kernel n ?x * f (?x + t) goal (1 subgoal): 1. LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) [PROOF STEP] by (rule Bochner_Integration.integral_cong [OF refl]) (simp add: eq) [PROOF STATE] proof (state) this: LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) goal (1 subgoal): 1. (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] then [PROOF STATE] proof (chain) picking this: LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t)) = LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t) goal (1 subgoal): 1. (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] by simp [PROOF STATE] proof (state) this: (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (LINT x|lebesgue_on {- pi..pi}. f (x + t) / 2 + (\<Sum>k = Suc 0..n. cos (real k * x) * f (x + t))) / pi = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi goal (1 subgoal): 1. (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi [PROOF STEP] . [PROOF STATE] proof (state) this: (\<Sum>k\<le>2 * n. Fourier_coefficient f k * trigonometric_set k t) = (LINT x|lebesgue_on {- pi..pi}. Dirichlet_kernel n x * f (x + t)) / pi goal: No subgoals! [PROOF STEP] qed
//#define BOOST_PYTHON_STATIC_LIB #include <fstream> #include <iostream> #include <sstream> #include <string> #include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/numpy.hpp> #include <boost/python/operators.hpp> #include <boost/python/dict.hpp> #include "json.hpp" namespace obp { using namespace std; namespace bp = boost::python; namespace bn = bp::numpy; template <typename... Args> std::string operator%(std::string fmt, std::tuple<Args...> args) { char line[800]; sprintf(line, fmt.c_str(), args); return line; } char const *greet() { // string str; // auto a = "%d-%d" % std::tuple<int, int>(2, 3); return "hello, world"; } struct World { void set(string msg) { this->msg = msg; } string greet() { return msg; } string msg; }; class ArrayHandler { public: ArrayHandler(); bp::object Generate(); bp::object GeneratebyTuple(bp::object &data); bp::object GeneratebyList(bp::object &data); bp::object Reshape(bp::object &data); void ShowData(bp::object &data); void DataType(bp::object &data); }; ArrayHandler::ArrayHandler() { } bp::object ArrayHandler::Generate() { bp::tuple shape = bp::make_tuple(4, 4); bn::dtype type = bn::dtype::get_builtin<float>(); bn::ndarray newArray = bn::zeros(shape, type); //bn::ndarray newArray = bn::empty(shape, type); return newArray; } bp::object ArrayHandler::GeneratebyTuple(bp::object &data) { bp::tuple dataList = (bp::tuple)data; bn::ndarray newArray = bn::array(dataList); return newArray; } bp::object ArrayHandler::GeneratebyList(bp::object &data) { bp::list dataList = (bp::list)data; bn::ndarray newArray = bn::array(dataList); return newArray; } bp::object ArrayHandler::Reshape(bp::object &data) { bn::ndarray dataArray = bn::from_object(data); for (int i = 0; i < dataArray.get_nd(); i++) { std::cout << "Size of Dim" << i + 1 << ": " << dataArray.get_shape()[i] << std::endl; } bp::tuple newShape = bp::make_tuple(2, 2, 2, 2); bn::ndarray newArray = dataArray.reshape(newShape); return newArray; } void ArrayHandler::ShowData(bp::object &data) { std::cout << "Original Array:" << bp::extract<char const *>(bp::str(data)) << std::endl; bn::ndarray dataArray = bn::from_object(data); data = dataArray.reshape(bp::make_tuple(16)); std::cout << "Reshaped Array:" << bp::extract<char const *>(bp::str(data)) << std::endl; } void ArrayHandler::DataType(bp::object &data) { bn::ndarray dataArray = bn::from_object(data); std::cout << "Datatype is " << bp::extract<char const *>(bp::str(dataArray.get_dtype())) << std::endl; } template<class T> struct _point:bp::object{ public: T _x,_y; _point():_x(),_y(){} _point(bp::object obj){_x=((_point<T>)obj)._x;_y=((_point<T>)obj)._y;} _point( T x, T y):_x((T)x),_y((T)y){} T abs(){return std::sqrt(_x*_x+_y*_y);} std::string to_json(){ nlohmann::json j1; j1["x"]=_x; j1["y"]=_y; stringstream ss; ss<<j1; return ss.str(); } // T& x(){return _x;} // T& y(){return _y;} /* friend _point operator+(_point x,_point y){ return _point(x._x+y._x,x._y+y._y); } friend _point operator-(_point x,_point y){ return _point(x._x-y._x,x._y-y._y); } */ }; /* struct point_add:bp::detail::binary_op<bp::detail::op_add>{ };*/ template<class T> using point=struct _point<T>; template<class T> struct _line:bp::object{ point<T> _s; point<T> _e; _line():_s(),_e(){} _line(bp::object obj){_s=((_line<T>)obj)._s;_e=((_line<T>)obj)._e;} _line( point<T> s, point<T> e):_s(s),_e(e){} point<T> dif(){return point<T>(_e._x-_s._x,_e._y-_s._y);} T abs(){return dif().abs();} std::string to_json(){ nlohmann::json j1; stringstream ss; j1["s"]["x"]=_s._x; j1["s"]["y"]=_s._y; j1["e"]["x"]=_e._x; j1["e"]["y"]=_e._y; ss<<j1; return ss.str(); } }; template<class T> using line=struct _line<T>; line<double> from_dict(bp::object&obj){ double sx=0,sy=0,ex=0,ey=0; bp::dict dict=(bp::dict)(obj); auto s=bp::extract<bp::dict>(dict["s"]); if(s.check()){ bp::dict xy=s(); sx=bp::extract<double>(xy["x"]); sy=bp::extract<double>(xy["y"]); } auto e=bp::extract<bp::dict>(dict["e"]); if(e.check()){ bp::dict xy=e(); ex=bp::extract<double>(xy["x"]); ey=bp::extract<double>(xy["y"]); } return line<double>(point<double>(sx,sy),point<double>(ex,ey)); } line<double> from_json(string str){ double sx=0,sy=0,ex=0,ey=0; nlohmann::json j1=nlohmann::json::parse(str); sx=j1["s"]["x"]; sy=j1["s"]["y"]; ex=j1["e"]["x"]; ey=j1["e"]["y"]; return line<double>(point<double>(sx,sy),point<double>(ex,ey)); } } // namespace obp BOOST_PYTHON_MODULE(cpp_example) //导出的module 名字 { obp::bn::initialize(); obp::bp::def("greet", obp::greet); obp::bp::class_<obp::World>("World") .def("greet", &obp::World::greet) .def("set", &obp::World::set); //bp::def("SetDictValue", SetDictValue); obp::bp::class_<obp::ArrayHandler>("ArrayHandler", obp::bp::init<>()) .def("Generate", &obp::ArrayHandler::Generate) .def("GeneratebyTuple", &obp::ArrayHandler::GeneratebyTuple) .def("GeneratebyList", &obp::ArrayHandler::GeneratebyList) .def("ShowData", &obp::ArrayHandler::ShowData) .def("DataType", &obp::ArrayHandler::DataType) .def("Reshape", &obp::ArrayHandler::Reshape); obp::bp::class_<obp::point<double>>("point",obp::bp::init<>()) .def(obp::bp::init<double,double>()) .def_readwrite("x",&obp::point<double>::_x) .def_readwrite("y",&obp::point<double>::_y) .def_readonly("abs",&obp::point<double>::abs) .def("to_json",&obp::point<double>::to_json); obp::bp::class_<obp::line<double>>("line",obp::bp::init<>()) .def(obp::bp::init<obp::point<double>,obp::point<double>>()) .def_readwrite("s",&obp::line<double>::_s) .def_readwrite("e",&obp::line<double>::_e) .def_readonly("dif",&obp::line<double>::dif) .def_readonly("abs",&obp::line<double>::abs) .def("to_json",&obp::line<double>::to_json); obp::bp::def("from_dict",&obp::from_dict); obp::bp::def("from_json",&obp::from_json); } #if 0 int main(){ Py_Initialize(); PyRun_SimpleString("import helloworld"); PyRun_SimpleString("helloworld.printHello()"); Py_Finalize(); } #endif
Formal statement is: lemma measure_count_space: "measure (count_space A) X = (if X \<subseteq> A then of_nat (card X) else 0)" Informal statement is: The measure of a subset of a countable set is the number of elements in the subset.
#redirect Academic Improvement Center Tutoring in Davis
# Copyright (c) 2021, Eric Sabo # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # I want to remove this dependence using Primes import Base: ==, ∩, + import Primes: factor include("cyclotomic.jl") include("linearcode.jl") abstract type AbstractCyclicCode <: AbstractLinearCode end abstract type AbstractBCHCode <: AbstractCyclicCode end abstract type AbstractReedSolomonCode <: AbstractBCHCode end # need to write == functions struct CyclicCode <: AbstractCyclicCode F::FqNmodFiniteField # base field E::FqNmodFiniteField # splitting field R::FqNmodPolyRing # polynomial ring of generator polynomial β::fq_nmod # n-th root of primitive element of splitting field n::Integer k::Integer d::Union{Integer, Missing} b::Integer δ::Integer qcosets::Vector{Vector{Int64}} qcosetsreps::Vector{Int64} defset::Vector{Int64} g::fq_nmod_poly h::fq_nmod_poly e::fq_nmod_poly G::fq_nmod_mat Gorig::Union{fq_nmod_mat, Missing} H::fq_nmod_mat Horig::Union{fq_nmod_mat, Missing} Gstand::fq_nmod_mat Hstand::fq_nmod_mat weightenum::Union{WeightEnumerator, Missing} end struct BCHCode <: AbstractBCHCode F::FqNmodFiniteField # base field E::FqNmodFiniteField # splitting field R::FqNmodPolyRing # polynomial ring of generator polynomial β::fq_nmod # n-th root of primitive element of splitting field n::Integer k::Integer d::Union{Integer, Missing} b::Integer δ::Integer qcosets::Vector{Vector{Int64}} qcosetsreps::Vector{Int64} defset::Vector{Int64} g::fq_nmod_poly h::fq_nmod_poly e::fq_nmod_poly G::fq_nmod_mat Gorig::Union{fq_nmod_mat, Missing} H::fq_nmod_mat Horig::Union{fq_nmod_mat, Missing} Gstand::fq_nmod_mat Hstand::fq_nmod_mat weightenum::Union{WeightEnumerator, Missing} end struct ReedSolomonCode <: AbstractReedSolomonCode F::FqNmodFiniteField # base field E::FqNmodFiniteField # splitting field R::FqNmodPolyRing # polynomial ring of generator polynomial β::fq_nmod # n-th root of primitive element of splitting field n::Integer k::Integer d::Union{Integer, Missing} b::Integer δ::Integer qcosets::Vector{Vector{Int64}} qcosetsreps::Vector{Int64} defset::Vector{Int64} g::fq_nmod_poly h::fq_nmod_poly e::fq_nmod_poly G::fq_nmod_mat Gorig::Union{fq_nmod_mat, Missing} H::fq_nmod_mat Horig::Union{fq_nmod_mat, Missing} Gstand::fq_nmod_mat Hstand::fq_nmod_mat weightenum::Union{WeightEnumerator, Missing} end function _generatorpolynomial(R::FqNmodPolyRing, β::fq_nmod, Z::Vector{Int64}) # from_roots(R, [β^i for i in Z]) - R has wrong type for this g = one(R) for i in Z g *= (gen(R) - β^i) end return g end _generatorpolynomial(R::FqNmodPolyRing, β::fq_nmod, qcosets::Vector{Vector{Int64}}) = _generatorpolynomial(R, β, vcat(qcosets...)) function _generatormatrix(F::FqNmodFiniteField, n::Integer, k::Integer, g::fq_nmod_poly) # if g = x^10 + α^2*x^9 + x^8 + α*x^7 + x^3 + α^2*x^2 + x + α # g.coeffs = [α 1 α^2 1 0 0 0 α 1 α^2 1] coeffs = collect(coefficients(g)) len = length(coeffs) k + len - 1 <= n || error("Too many coefficients for $k shifts in _generatormatrix.") G = zero_matrix(F, k, n) for i in 1:k G[i, i:i + len - 1] = coeffs end return G end function definingset(nums::Vector{Int64}, q::Integer, n::Integer, flat::Bool=true) arr = Vector{Vector{Int64}}() arrflat = Vector{Int64}() for x in nums Cx = cyclotomiccoset(x, q, n) if Cx[1] ∉ arrflat arrflat = [arrflat; Cx] push!(arr, Cx) end end !flat || return sort!(vcat(arr...)) return arr end function _idempotent(g::fq_nmod_poly, h::fq_nmod_poly, n::Integer) # solve 1 = a(x) g(x) + b(x) h(x) for a(x) then e(x) = a(x) g(x) mod x^n - 1 d, a, b = gcdx(g, h) return mod(g * a, gen(parent(g))^n - 1) end # MattsonSolomontransform(f, n) # inverseMattsonSolomontransform basefield(C::AbstractCyclicCode) = C.F splittingfield(C::AbstractCyclicCode) = C.E polynomialring(C::AbstractCyclicCode) = C.R primitiveroot(C::AbstractCyclicCode) = C.β offset(C::AbstractCyclicCode) = C.b designdistance(C::AbstractCyclicCode) = C.δ qcosets(C::AbstractCyclicCode) = C.qcosets qcosetsreps(C::AbstractCyclicCode) = C.qcosetsreps definingset(C::AbstractCyclicCode) = C.defset generatorpolynomial(C::AbstractCyclicCode) = C.g paritycheckpolynomial(C::AbstractCyclicCode) = C.h idempotent(C::AbstractCyclicCode) = C.e isprimitive(C::AbstractCyclicCode) = length(n) == order(basefield(C)) - 1 isnarrowsense(C::AbstractCyclicCode) = iszero(offset(C)) # should we define this as b = 1 instead? isreversible(C::AbstractCyclicCode) = [length(C) - i for i in defset] ⊆ defset function Base.show(io::IO, C::AbstractCyclicCode) if get(io, :compact, false) # to use type "show(IOContext(stdout, :compact=>true), C)" instead if typeof(C) <: ReedSolomonCode println(io, "[$(length(C)), $(dimension(C)), ≥$(designdistance(C)); $(offset(C))]_$(order(field(C))) Reed Solomon code.") elseif typeof(C) <: BCHCode println(io, "[$(length(C)), $(dimension(C)), ≥$(designdistance(C)); $(offset(C))]_$(order(field(C))) BCH code over splitting field GF($(order(splittingfield(C)))).") else println(io, "[$(length(C)), $(dimension(C)), ≥$(designdistance(C)); $(offset(C))]_$(order(field(C))) cyclic code over splitting field GF($(order(splittingfield(C)))).") end else if typeof(C) <: ReedSolomonCode println(io, "[$(length(C)), $(dimension(C)), ≥$(designdistance(C)); $(offset(C))]_$(order(field(C))) Reed Solomon code.") elseif typeof(C) <: BCHCode println(io, "[$(length(C)), $(dimension(C)), ≥$(designdistance(C)); $(offset(C))]_$(order(field(C))) BCH code over splitting field GF($(order(splittingfield(C)))).") else println(io, "[$(length(C)), $(dimension(C)), ≥$(designdistance(C)); $(offset(C))]_$(order(field(C))) cyclic code over splitting field GF($(order(splittingfield(C)))).") end println(io, "$(order(field(C)))-Cyclotomic cosets: ") for (i, x) in enumerate(qcosetsreps(C)) if i == 1 print(io, "\tC_$x ∪ ") elseif i == 1 && i == length(qcosetsreps(C)) println(io, "\tC_$x") elseif i != length(qcosetsreps(C)) print(io, "C_$x ∪ ") else println(io, "C_$x") end end println(io, "Generator polynomial:") println(io, "\t", generatorpolynomial(C)) println(io, "Generator matrix: $(dimension(C)) × $(length(C))") for i in 1:dimension(C) print(io, "\t") for j in 1:length(C) if j != length(C) print(io, "$(C.G[i, j]) ") elseif j == length(C) && i != dimension(C) println(io, "$(C.G[i, j])") else print(io, "$(C.G[i, j])") end end end end end function finddelta(n::Integer, cosets::Vector{Vector{Int64}}) # println(cosets) defset = sort!(vcat(cosets...)) runs = Vector{Vector{Int64}}() for x in defset useddefset = Vector{Int64}() reps = Vector{Int64}() cosetnum = 0 for i in 1:length(cosets) if x ∈ cosets[i] cosetnum = i append!(useddefset, cosets[i]) append!(reps, x) break end end y = x + 1 while y ∈ defset if y ∈ useddefset append!(reps, y) else cosetnum = 0 for i in 1:length(cosets) if y ∈ cosets[i] cosetnum = i append!(useddefset, cosets[i]) append!(reps, y) break end end end y += 1 end push!(runs, reps) end runlens = [length(i) for i in runs] (consec, ind) = findmax(runlens) # there are δ - 1 consecutive numbers for designed distance δ δ = consec + 1 # start of run offset = runs[ind][1] # BCH Bound is thus d≥δ # moving to Hartmann-Tzeng Bound refinement currbound = δ if consec > 1 for A in runs if length(A) == consec for b in 1:(n - 1) if gcd(b, n) ≤ δ for s in 0:(δ - 2) B = [mod(j * b, n) for j in 0:s] AB = [x + y for x in A for y in B] if AB ⊆ defset if currbound < δ + s currbound = δ + s end end end end end end end end return δ, offset, currbound end function largestconsecrun(arr::Vector{Int64}) n = length(arr) maxlen = 1 for i = 1:n mn = arr[i] mx = arr[i] for j = (i + 1):n mn = min(mn, arr[j]) mx = max(mx, arr[j]) if (mx - mn) == (j - i) maxlen = max(maxlen, mx - mn + 1) end end end return maxlen end function dualdefiningset(arr::Vector{Int64}, n::Integer) full = [i for i in 0:(n - 1)] temp = Vector{Int64}() for i in full if i ∉ arr append!(temp, i) end end return sort!([mod(n - i, n) for i in temp]) end function CyclicCode(q::Integer, n::Integer, cosets::Vector{Vector{Int64}}, verify::Bool=true) !(q <= 1 || n <= 1) ||error("Invalid parameters past to CyclicCode constructor: q = $q, n = $n.") if !isprime(q) # this used to work with just AbstractAlgebra factors = Primes.factor(q) if length(factors) != 1 error("There is no finite field of order $(prod(factors)).") end (p, t), = factors else p = q t = 1 end F, _ = FiniteField(p, t, "α") # changed to keep ReedSolomonCodes printing α's' deg = ord(n, q) E, α = FiniteField(p, t * deg, "α") R, _ = PolynomialRing(E, "x") β = α^(div(q^deg - 1, n)) # println("here so far") defset = sort!(vcat(cosets...)) k = n - length(defset) # println(k) comcosets = complementqcosets(q, n, cosets) # println("here 2") g = _generatorpolynomial(R, β, defset) h = _generatorpolynomial(R, β, vcat(comcosets...)) e = _idempotent(g, h, n) G = _generatormatrix(F, n, k, g) H = _generatormatrix(F, n, n - k, reverse(h)) # println("here 3") # println(G) Gstand, Hstand = _standardform(G) # println("here 4") δ, b, HT = finddelta(n, cosets) # println("here 5") if verify # println("above") flag, htest = divides(gen(R)^n - 1, g) # println(flag) # println(htest) flag || error("Incorrect generator polynomial, does not divide x^$n - 1.") # println(htest, parent(h)) # println(h, parent(h)) htest == h || error("Division of x^$n - 1 by the generator polynomial does not yield the constructed parity check polynomial.") # if htest != h # println("sucks") # # error("test") # end if size(H) == (n - k, k) H = deepcopy(H') end !(!iszero(G * H') || !iszero(H * G')) || error("Generator and parity check matrices are not transpose orthogonal.") for r in 1:size(Gstand, 1) iszero(Gstand[r, :] * H') || error("Column swap appeared in _standardform.") end # check e=e^2 end if δ >= 2 && defset == definingset([i for i = b:(b + δ - 2)], q, n, true) if deg == 1 && n == q - 1 return ReedSolomonCode(F, E, R, β, n, k, n - k + 1, b, HT, cosets, sort!([arr[1] for arr in cosets]), defset, g, h, e, G, missing, H, missing, Gstand, Hstand, missing) end return BCHCode(F, E, R, β, n, k, missing, b, HT, cosets, sort!([arr[1] for arr in cosets]), defset, g, h, e, G, missing, H, missing, Gstand, Hstand, missing) end return CyclicCode(F, E, R, β, n, k, missing, b, HT, cosets, sort!([arr[1] for arr in cosets]), defset, g, h, e, G, missing, H, missing, Gstand, Hstand, missing) end # currently untested - not fully fixed yet function CyclicCode(q::Integer, n::Integer, g::fq_nmod_poly, verify::Bool=true) flag, htest = divides(gen(R)^n - 1, g) flag || error("Given polynomial does not divide x^$n - 1.") if !isprime(q) factors = factor(q) if length(factors) != 1 error("There is no finite field of order $(prod(factors)).") end (q, n), = factors end R = parent(g) F = base_ring(R) α = gen(F) t = ord(n, q) β = α^(div(q^t - 1, n)) dic = Dict{fq_nmod, Int64}() for i in 1:n dic[β^i] = i end rts = roots(g) defset = sort!([dic[rt] for rt in rts]) qcosets = definingset(defset, q, n, false) k = n - length(defset) comcosets = complementqcosets(q, n, qcosets) e = _idempotent(g, h) G = _generatormatrix(n, k, g) H = _generatormatrix(n, n - k, reverse(htest)) Gstand, Hstand = _standardform(G) _, _, HT = finddelta(n, qcosets) if verify h, _, _, _ = _generatorpolynomial(q, n, vcat(comcosets...)) htest == h || error("Division of x^$n - 1 by the generator polynomial does not yield the constructed parity check polynomial.") if size(H) == (n - k, k) H = deepcopy(H') end !(!iszero(G * H') || !iszero(H * G')) || error("Generator and parity check matrices are not transpose orthogonal.") for r in 1:size(Gstand, 1) iszero(Gstand[r, :] * H') || error("Column swap appeared in _standardform.") end end return CyclicCode(F, E, R, β, n, k, missing, b, HT, qcosets, sort!([arr[1] for arr in qcosets]), defset, g, h, e, G, H, Gstand, Hstand, missing) end # self orthogonal cyclic codes are even-like # does this require them too have even minimum distance? # self orthogonal code must contain all of its self orthogonal q-cosets and at least one of every q-coset pair function BCHCode(q::Integer, n::Integer, δ::Integer, b::Integer=0, verify::Bool=true) δ >= 2 || error("BCH codes require δ ≥ 2 but the constructor was given δ = $δ.") !(q <= 1 || n <= 1) || error("Invalid parameters past to BCHCode constructor: q = $q, n = $n.") if !isprime(q) factors = Primes.factor(q) if length(factors) != 1 error("There is no finite field of order $(prod(factors)).") end (p, t), = factors else p = q t = 1 end F, _ = FiniteField(p, t, "α") # changed to keep ReedSolomonCodes printing α's' deg = ord(n, q) E, α = FiniteField(p, t * deg, "α") R, _ = PolynomialRing(E, "x") β = α^(div(q^deg - 1, n)) cosets = definingset([i for i = b:(b + δ - 2)], q, n, false) defset = sort!(vcat(cosets...)) k = n - length(defset) comcosets = complementqcosets(q, n, cosets) g = _generatorpolynomial(R, β, defset) h = _generatorpolynomial(R, β, vcat(comcosets...)) e = _idempotent(g, h, n) G = _generatormatrix(F, n, k, g) H = _generatormatrix(F, n, n - k, reverse(h)) Gstand, Hstand = _standardform(G) δ, b, HT = finddelta(n, cosets) if verify flag, htest = divides(gen(R)^n - 1, g) flag || error("Incorrect generator polynomial, does not divide x^$n - 1.") htest == h || error("Division of x^$n - 1 by the generator polynomial does not yield the constructed parity check polynomial.") if size(H) == (n - k, k) H = deepcopy(H') end !(!iszero(G * H') || !iszero(H * G')) || error("Generator and parity check matrices are not transpose orthogonal.") for r in 1:size(Gstand, 1) iszero(Gstand[r, :] * H') || error("Column swap appeared in _standardform.") end end if deg == 1 && n == q - 1 return ReedSolomonCode(F, E, R, β, n, k, n - k + 1, b, HT, cosets, sort!([arr[1] for arr in cosets]), defset, g, h, e, G, missing, H, missing, Gstand, Hstand, missing) end return BCHCode(F, E, R, β, n, k, n - k + 1, b, HT, cosets, sort!([arr[1] for arr in cosets]), defset, g, h, e, G, missing, H, missing, Gstand, Hstand, missing) end function ReedSolomonCode(q::Integer, δ::Integer, b::Integer=0, verify::Bool=true) δ >= 2 || error("Reed Solomon codes require δ ≥ 2 but the constructor was given δ = $δ.") q > 4 || error("Invalid or too small parameters past to ReedSolomonCode constructor: q = $q.") # n = q - 1 # if ord(n, q) != 1 # error("Reed Solomon codes require n = q - 1.") # end if !isprime(q) factors = factor(q) if length(factors) != 1 error("There is no finite field of order $(prod(factors)).") end (p, t), = factors else p = q t = 1 end F, α = FiniteField(p, t, "α") # changed to keep ReedSolomonCodes printing α's' R, _ = PolynomialRing(F, "x") n = q - 1 cosets = definingset([i for i = b:(b + δ - 2)], q, n, false) defset = sort!(vcat(cosets...)) k = n - length(defset) comcosets = complementqcosets(q, n, cosets) g = _generatorpolynomial(R, α, defset) h = _generatorpolynomial(R, α, vcat(comcosets...)) e = _idempotent(g, h, n) G = _generatormatrix(F, n, k, g) H = _generatormatrix(F, n, n - k, reverse(h)) Gstand, Hstand = _standardform(G) δ, b, HT = finddelta(n, cosets) if verify flag, htest = divides(gen(R)^n - 1, g) flag || error("Incorrect generator polynomial, does not divide x^$n - 1.") htest == h || error("Division of x^$n - 1 by the generator polynomial does not yield the constructed parity check polynomial.") if size(H) == (n - k, k) H = deepcopy(H') end !(!iszero(G * H') || !iszero(H * G')) || error("Generator and parity check matrices are not transpose orthogonal.") for r in 1:size(Gstand, 1) iszero(Gstand[r, :] * H) || error("Column swap appeared in _standardform.") end end return ReedSolomonCode(F, F, R, α, n, k, n - k + 1, b, HT, cosets, sort!([arr[1] for arr in cosets]), defset, g, h, e, G, missing, H, missing, Gstand, Hstand, missing) end function complement(C::AbstractCyclicCode, verify::Bool=true) D = CyclicCode(Int64(order(field(C))), length(C), complementqcosets(Int64(order(field(C))), length(C), qcosets(C))) if verify if paritycheckpolynomial(C) != generatorpolynomial(D) || idempotent(D) != (1 - idempotent(C)) error("Error constructing the complement cyclic code.") end end return D end # C1 ⊆ C2 iff g_2(x) | g_1(x) iff T_2 ⊆ T_1 ⊆(C1::AbstractCyclicCode, C2::AbstractCyclicCode) = C2.defset ⊆ C1.defset issubcode(C1::AbstractCyclicCode, C2::AbstractCyclicCode) = C1 ⊆ C2 function ==(C1::AbstractCyclicCode, C2::AbstractCyclicCode) # should also check primitive root but so far the user is not given a choice here return field(C1) == field(C2) && length(C1) == length(C2) && definingset(C1) == definingset(C2) end function dual(C::AbstractCyclicCode) # one is even-like and the other is odd-like return CyclicCode(Int64(order(field(C))), length(C), dualqcosets(Int64(order(field(C))), length(C), qcosets(C))) end # this checks def set, need to rewrite == for linear first isselfdual(C::AbstractCyclicCode) = C == dual(C) # don't think this is necessary in order to invoke the ⊆ for CyclicCode # function isselforthogonal(C::AbstractCyclicCode) # # A code is self-orthogonal if it is a subcode of its dual. # return C ⊆ dual(C) # end # function μa(C::CyclicCode) # # check gcd(a, n) = 1 # # technically changes g(x) and e(x) but the q-cosets are the same? # end function ∩(C1::AbstractCyclicCode, C2::AbstractCyclicCode) # has generator polynomial lcm(g_1(x), g_2(x)) # has generator idempotent e_1(x) e_2(x) if field(C1) == field(C2) && length(C1) == length(C2) return CyclicCode(Int64(order(field(C1))), length(C1), definingset(definingset(C1) ∪ definingset(C2), Int64(order(field(C1))), length(C1), false)) else error("Cannot intersect two codes over different base fields or lengths.") end end function +(C1::AbstractCyclicCode, C2::AbstractCyclicCode) # has generator polynomial gcd(g_1(x), g_2(x)) # has generator idempotent e_1(x) + e_2(x) - e_1(x) e_2(x) if field(C1) == field(C2) && length(C1) == length(C2) defset = definingset(C1) ∩ definingset(C2) if length(defset) != 0 return CyclicCode(Int64(order(field(C1))), length(C1), definingset(defset, Int64(order(field(C1))), length(C1), false)) else error("Addition of codes has empty defining set.") end else error("Cannot add two codes over different base fields or lengths.") end end
What did you get at the last gun show you attended? Notice: No liberals were offended in the creation of this video. I’ve recently helped a friend set up at the local gun show. I’ve been a big fan of gun shows all my life. I started going as a kid with my dad and haven’t missed many shows since then, I even try to attend gun shows when I travel if possible. So it’s always discouraging to hear a fellow shooter or firearms enthusiast complain about gun shows. I hope I can offer a few reasons why you may want to attend the next gun show in your area. First let’s explain what a gun show is for anyone who is not clear. They are basically swap meets or flea markets that concentrate on firearms and their accessories. One common complaint about gun shows is the other items besides firearms that show up sometimes. Thinking about it from the promoters point of view, they need to find the public venue to hold the show, arrange for vendors to come and sell, provide security, tables, insurance and all the behind the scenes work involved with an event like this. So if a show doesn’t bring in a lot of people to buy, it will attract fewer vendors to sell, then fewer vendors attract less people and you can see the downward spiral. Of course the bills for the promoter are the same no matter how many vendors or people show up to buy. Since the 1968 Gun Control Act, which created the FFL system of licensing gun shops manufacturers in gunsmiths, licensed gun shops who do business in firearms are only able to sell at their location which is why we don’t see door to door gun sales . However in the FFL licensing it states that the gun shops can sell at official gun shows. Another common complaint is prices at gun shows. Now, I am not rich and I like a bargain as well as the next guy, however I also live in a free market and understand supply and demand. Having a lot of firearms dealers in a single location can create a competitive pricing environment but it is not guaranteed to be. At some gun shows you might find political candidates reaching out to firearms owners, local and state level pro guns pro rights organizations and even one to one conversation with other gun owners. There is so much talk of preparing for emergencies and many people include making contacts in their community as part of that preparation what better place than a gun show to find those like minded individuals? Small Arms Review will be hosting their Western US show from December 2nd to the 4th at the Arizona State Fairgrounds. For a great opportunity to see and purchase the latest and greatest from countless dealers, check it out.
(* Title: A Definitional Encoding of TLA in Isabelle/HOL Authors: Gudmund Grov <ggrov at inf.ed.ac.uk> Stephan Merz <Stephan.Merz at loria.fr> Year: 2011 Maintainer: Gudmund Grov <ggrov at inf.ed.ac.uk> *) section \<open>(Infinite) Sequences\<close> theory Sequence imports Main begin text \<open> Lamport's Temporal Logic of Actions (TLA) is a linear-time temporal logic, and its semantics is defined over infinite sequence of states, which we simply represent by the type \<open>'a seq\<close>, defined as an abbreviation for the type \<open>nat \<Rightarrow> 'a\<close>, where \<open>'a\<close> is the type of sequence elements. This theory defines some useful notions about such sequences, and in particular concepts related to stuttering (finite repetitions of states), which are important for the semantics of TLA. We identify a finite sequence with an infinite sequence that ends in infinite stuttering. In this way, we avoid the complications of having to handle both finite and infinite sequences of states: see e.g. Devillers et al \<^cite>\<open>"Devillers97"\<close> who discuss several variants of representing possibly infinite sequences in HOL, Isabelle and PVS. \<close> type_synonym 'a seq = "nat \<Rightarrow> 'a" subsection "Some operators on sequences" text \<open>Some general functions on sequences are provided\<close> definition first :: "'a seq \<Rightarrow> 'a" where "first s \<equiv> s 0" definition second :: "('a seq) \<Rightarrow> 'a" where "second s \<equiv> s 1" definition suffix :: "'a seq \<Rightarrow> nat \<Rightarrow> 'a seq" (infixl "|\<^sub>s" 60) where "s |\<^sub>s i \<equiv> \<lambda> n. s (n+i)" definition tail :: "'a seq \<Rightarrow> 'a seq" where "tail s \<equiv> s |\<^sub>s 1" definition app :: "'a \<Rightarrow> ('a seq) \<Rightarrow> ('a seq)" (infixl "##" 60) where "s ## \<sigma> \<equiv> \<lambda> n. if n=0 then s else \<sigma> (n - 1)" text \<open> \<open>s |\<^sub>s i\<close> returns the suffix of sequence @{term s} from index @{term i}. @{term first} returns the first element of a sequence while @{term second} returns the second element. @{term tail} returns the sequence starting at the second element. @{term "s ## \<sigma>"} prefixes the sequence @{term \<sigma>} by element @{term s}. \<close> subsubsection "Properties of @{term first} and @{term second}" lemma first_tail_second: "first(tail s) = second s" by (simp add: first_def second_def tail_def suffix_def) subsubsection "Properties of @{term suffix}" lemma suffix_first: "first (s |\<^sub>s n) = s n" by (auto simp add: suffix_def first_def) lemma suffix_second: "second (s |\<^sub>s n) = s (Suc n)" by (auto simp add: suffix_def second_def) lemma suffix_plus: "s |\<^sub>s n |\<^sub>s m = s |\<^sub>s (m + n)" by (simp add: suffix_def add.assoc) lemma suffix_commute: "((s |\<^sub>s n) |\<^sub>s m) = ((s |\<^sub>s m) |\<^sub>s n)" by (simp add: suffix_plus add.commute) lemma suffix_plus_com: "s |\<^sub>s m |\<^sub>s n = s |\<^sub>s (m + n)" proof - have "s |\<^sub>s n |\<^sub>s m = s |\<^sub>s (m + n)" by (rule suffix_plus) thus "s |\<^sub>s m |\<^sub>s n = s |\<^sub>s (m + n)" by (simp add: suffix_commute) qed lemma suffix_zero[simp]: "s |\<^sub>s 0 = s" by (simp add: suffix_def) lemma suffix_tail: "s |\<^sub>s 1 = tail s" by (simp add: tail_def) lemma tail_suffix_suc: "s |\<^sub>s (Suc n) = tail (s |\<^sub>s n)" by (simp add: suffix_def tail_def) subsubsection "Properties of @{term app}" lemma seq_app_second: "(s ## \<sigma>) 1 = \<sigma> 0" by (simp add: app_def) lemma seq_app_first: "(s ## \<sigma>) 0 = s" by (simp add: app_def) lemma seq_app_first_tail: "(first s) ## (tail s) = s" proof (rule ext) fix x show "(first s ## tail s) x = s x" by (simp add: first_def app_def suffix_def tail_def) qed lemma seq_app_greater_than_zero: "n > 0 \<Longrightarrow> (s ## \<sigma>) n = \<sigma> (n - 1)" by (simp add: app_def) subsection "Finite and Empty Sequences" text\<open> We identify finite and empty sequences and prove lemmas about them. \<close> definition fin :: "('a seq) \<Rightarrow> bool" where "fin s \<equiv> \<exists> i. \<forall> j \<ge> i. s j = s i" abbreviation inf :: "('a seq) \<Rightarrow> bool" where "inf s \<equiv> \<not>(fin s)" definition last :: "('a seq) \<Rightarrow> nat" where "last s \<equiv> LEAST i. (\<forall> j \<ge> i. s j = s i)" definition laststate :: "('a seq) \<Rightarrow> 'a" where "laststate s \<equiv> s (last s)" definition emptyseq :: "('a seq) \<Rightarrow> bool" where "emptyseq \<equiv> \<lambda> s. \<forall> i. s i = s 0" abbreviation notemptyseq :: "('a seq) \<Rightarrow> bool" where "notemptyseq s \<equiv> \<not>(emptyseq s)" text \<open> Predicate @{term fin} holds if there is an element in the sequence such that all subsequent elements are identical, i.e. the sequence is finite. @{term "last s"} returns the smallest index from which on all elements of a finite sequence @{term s} are identical. Note that if \<open>s\<close> is not finite then an arbitrary number is returned. @{term laststate} returns the last element of a finite sequence. We assume that the sequence is finite when using @{term last} and @{term laststate}. Predicate @{term emptyseq} identifies empty sequences -- i.e. all states in the sequence are identical to the initial one, while @{term notemptyseq} holds if the given sequence is not empty. \<close> subsubsection "Properties of @{term emptyseq}" lemma empty_is_finite: assumes "emptyseq s" shows "fin s" using assms by (auto simp: fin_def emptyseq_def) lemma empty_suffix_is_empty: assumes H: "emptyseq s" shows "emptyseq (s |\<^sub>s n)" proof (clarsimp simp: emptyseq_def) fix i from H have "(s |\<^sub>s n) i = s 0" by (simp add: emptyseq_def suffix_def) moreover from H have "(s |\<^sub>s n) 0 = s 0" by (simp add: emptyseq_def suffix_def) ultimately show "(s |\<^sub>s n) i = (s |\<^sub>s n) 0" by simp qed lemma suc_empty: assumes H1: "emptyseq (s |\<^sub>s m)" shows "emptyseq (s |\<^sub>s (Suc m))" proof - from H1 have "emptyseq ((s |\<^sub>s m) |\<^sub>s 1)" by (rule empty_suffix_is_empty) thus ?thesis by (simp add: suffix_plus) qed lemma empty_suffix_exteq: assumes H:"emptyseq s" shows "(s |\<^sub>s n) m = s m" proof (unfold suffix_def) from H have "s (m+n) = s 0" by (simp add: emptyseq_def) moreover from H have "s m = s 0" by (simp add: emptyseq_def) ultimately show "s (m + n) = s m" by simp qed lemma empty_suffix_eq: assumes H: "emptyseq s" shows "(s |\<^sub>s n) = s" proof (rule ext) fix m from H show "(s |\<^sub>s n) m = s m" by (rule empty_suffix_exteq) qed lemma seq_empty_all: assumes H: "emptyseq s" shows "s i = s j" proof - from H have "s i = s 0" by (simp add: emptyseq_def) moreover from H have "s j = s 0" by (simp add: emptyseq_def) ultimately show ?thesis by simp qed subsubsection "Properties of @{term last} and @{term laststate}" lemma fin_stut_after_last: assumes H: "fin s" shows "\<forall>j \<ge> last s. s j = s (last s)" proof (clarify) fix j assume j: "j \<ge> last s" from H obtain i where "\<forall>j \<ge> i. s j = s i" (is "?P i") by (auto simp: fin_def) hence "?P (last s)" unfolding last_def by (rule LeastI) with j show "s j = s (last s)" by blast qed subsection "Stuttering Invariance" text \<open> This subsection provides functions for removing stuttering steps of sequences, i.e. we formalise Lamports \<open>\<natural>\<close> operator. Our formal definition is close to that of Wahab in the PVS prover. The key novelty with the @{term "Sequence"} theory, is the treatment of stuttering invariance, which enables verification of stuttering invariance of the operators derived using it. Such proofs require comparing sequences up to stuttering. Here, Lamport's \<^cite>\<open>"Lamport94"\<close> method is used to mechanise the equality of sequences up to stuttering: he defines the \<open>\<natural>\<close> operator, which collapses a sequence by removing all stuttering steps, except possibly infinite stuttering at the end of the sequence. These are left unchanged. \<close> definition nonstutseq :: "('a seq) \<Rightarrow> bool" where "nonstutseq s \<equiv> \<forall> i. s i = s (Suc i) \<longrightarrow> (\<forall> j > i. s i = s j)" definition stutstep :: "('a seq) \<Rightarrow> nat \<Rightarrow> bool" where "stutstep s n \<equiv> (s n = s (Suc n))" definition nextnat :: "('a seq) \<Rightarrow> nat" where "nextnat s \<equiv> if emptyseq s then 0 else LEAST i. s i \<noteq> s 0" definition nextsuffix :: "('a seq) \<Rightarrow> ('a seq)" where "nextsuffix s \<equiv> s |\<^sub>s (nextnat s)" fun "next" :: "nat \<Rightarrow> ('a seq) \<Rightarrow> ('a seq)" where "next 0 = id" | "next (Suc n) = nextsuffix o (next n)" definition collapse :: "('a seq) \<Rightarrow> ('a seq)" ("\<natural>") where "\<natural> s \<equiv> \<lambda> n. (next n s) 0" text \<open> Predicate @{term nonstutseq} identifies sequences without any stuttering steps -- except possibly for infinite stuttering at the end. Further, @{term "stutstep s n"} is a predicate which holds if the element after @{term "s n"} is equal to @{term "s n"}, i.e. @{term "Suc n"} is a stuttering step. @{term "collapse s"} formalises Lamports @{term "\<natural>"} operator. It returns the first state of the result of @{term "next n s"}. @{term "next n s"} finds suffix of the $n^{th}$ change. Hence the first element, which @{term "\<natural> s"} returns, is the state after the $n^{th}$ change. @{term "next n s"} is defined by primitive recursion on @{term "n"} using function composition of function @{term nextsuffix}. E.g. @{term "next 3 s"} equals @{term "nextsuffix (nextsuffix (nextsuffix s))"}. @{term "nextsuffix s"} returns the suffix of the sequence starting at the next changing state. It uses @{term "nextnat"} to obtain this. All the real computation is done in this function. Firstly, an empty sequence will obviously not contain any changes, and \<open>0\<close> is therefore returned. In this case @{term "nextsuffix"} behaves like the identify function. If the sequence is not empty then the smallest number @{term "i"} such that @{term "s i"} is different from the initial state is returned. This is achieved by @{term "Least"}. \<close> subsubsection "Properties of @{term nonstutseq}" lemma seq_empty_is_nonstut: assumes H: "emptyseq s" shows "nonstutseq s" using H by (auto simp: nonstutseq_def seq_empty_all) lemma notempty_exist_nonstut: assumes H: "\<not> emptyseq (s |\<^sub>s m)" shows "\<exists> i. s i \<noteq> s m \<and> i > m" using H proof (auto simp: emptyseq_def suffix_def) fix i assume i: "s (i + m) \<noteq> s m" hence "i \<noteq> 0" by (intro notI, simp) with i show ?thesis by auto qed subsubsection "Properties of @{term nextnat}" lemma nextnat_le_unch: assumes H: "n < nextnat s" shows "s n = s 0" proof (cases "emptyseq s") assume "emptyseq s" hence "nextnat s = 0" by (simp add: nextnat_def) with H show ?thesis by auto next assume "\<not> emptyseq s" hence a1: "nextnat s = (LEAST i. s i \<noteq> s 0)" by (simp add: nextnat_def) show ?thesis proof (rule ccontr) assume a2: "s n \<noteq> s 0" (is "?P n") hence "(LEAST i. s i \<noteq> s 0) \<le> n" by (rule Least_le) hence "\<not>(n < (LEAST i. s i \<noteq> s 0))" by auto also from H a1 have "n < (LEAST i. s i \<noteq> s 0)" by simp ultimately show False by auto qed qed lemma stutnempty: assumes H: "\<not> stutstep s n" shows "\<not> emptyseq (s |\<^sub>s n)" proof (unfold emptyseq_def suffix_def) from H have "s (Suc n) \<noteq> s n" by (auto simp add: stutstep_def) hence "s (1+n) \<noteq> s (0+n)" by simp thus "\<not>(\<forall> i. s (i+n) = s (0+n))" by blast qed lemma notstutstep_nexnat1: assumes H: "\<not> stutstep s n" shows "nextnat (s |\<^sub>s n) = 1" proof - from H have h': "nextnat (s |\<^sub>s n) = (LEAST i. (s |\<^sub>s n) i \<noteq> (s |\<^sub>s n) 0)" by (auto simp add: nextnat_def stutnempty) from H have "s (Suc n) \<noteq> s n" by (auto simp add: stutstep_def) hence "(s |\<^sub>s n) 1 \<noteq> (s |\<^sub>s n) 0" (is "?P 1") by (auto simp add: suffix_def) hence "Least ?P \<le> 1" by (rule Least_le) hence g1: "Least ?P = 0 \<or> Least ?P = 1" by auto with h' have g1': "nextnat (s |\<^sub>s n) = 0 \<or> nextnat (s |\<^sub>s n) = 1" by auto also have "nextnat (s |\<^sub>s n) \<noteq> 0" proof - from H have "\<not> emptyseq (s |\<^sub>s n)" by (rule stutnempty) then obtain i where "(s |\<^sub>s n) i \<noteq> (s |\<^sub>s n) 0" by (auto simp add: emptyseq_def) hence "(s |\<^sub>s n) (LEAST i. (s |\<^sub>s n) i \<noteq> (s |\<^sub>s n) 0) \<noteq> (s |\<^sub>s n) 0" by (rule LeastI) with h' have g2: "(s |\<^sub>s n) (nextnat (s |\<^sub>s n)) \<noteq> (s |\<^sub>s n) 0" by auto show "(nextnat (s |\<^sub>s n)) \<noteq> 0" proof assume "(nextnat (s |\<^sub>s n)) = 0" with g2 show "False" by simp qed qed ultimately show "nextnat (s |\<^sub>s n) = 1" by auto qed lemma stutstep_notempty_notempty: assumes h1: "emptyseq (s |\<^sub>s Suc n)" (is "emptyseq ?sn") and h2: "stutstep s n" shows "emptyseq (s |\<^sub>s n)" (is "emptyseq ?s") proof (auto simp: emptyseq_def) fix k show "?s k = ?s 0" proof (cases k) assume "k = 0" thus ?thesis by simp next fix m assume k: "k = Suc m" hence "?s k = ?sn m" by (simp add: suffix_def) also from h1 have "... = ?sn 0" by (simp add: emptyseq_def) also from h2 have "... = s n" by (simp add: suffix_def stutstep_def) finally show ?thesis by (simp add: suffix_def) qed qed lemma stutstep_empty_suc: assumes "stutstep s n" shows "emptyseq (s |\<^sub>s Suc n) = emptyseq (s |\<^sub>s n)" using assms by (auto elim: stutstep_notempty_notempty suc_empty) lemma nextnat_empty_neq: assumes H: "\<not> emptyseq s" shows "s (nextnat s) \<noteq> s 0" proof - from H have a1: "nextnat s = (LEAST i. s i \<noteq> s 0)" by (simp add: nextnat_def) from H obtain i where "s i \<noteq> s 0" by (auto simp: emptyseq_def) hence "s (LEAST i. s i \<noteq> s 0) \<noteq> s 0" by (rule LeastI) with a1 show ?thesis by auto qed lemma nextnat_empty_gzero: assumes H: "\<not> emptyseq s" shows "nextnat s > 0" proof - from H have a1: "s (nextnat s) \<noteq> s 0" by (rule nextnat_empty_neq) have "nextnat s \<noteq> 0" proof assume "nextnat s = 0" with a1 show "False" by simp qed thus "nextnat s > 0" by simp qed subsubsection "Properties of @{term nextsuffix}" lemma empty_nextsuffix: assumes H: "emptyseq s" shows "nextsuffix s = s" using H by (simp add: nextsuffix_def nextnat_def) lemma empty_nextsuffix_id: assumes H: "emptyseq s" shows "nextsuffix s = id s" using H by (simp add: empty_nextsuffix) lemma notstutstep_nextsuffix1: assumes H: "\<not> stutstep s n" shows "nextsuffix (s |\<^sub>s n) = s |\<^sub>s (Suc n)" proof (unfold nextsuffix_def) show "(s |\<^sub>s n |\<^sub>s (nextnat (s |\<^sub>s n))) = s |\<^sub>s (Suc n)" proof - from H have "nextnat (s |\<^sub>s n) = 1" by (rule notstutstep_nexnat1) hence "(s |\<^sub>s n |\<^sub>s (nextnat (s |\<^sub>s n))) = s |\<^sub>s n |\<^sub>s 1" by auto thus ?thesis by (simp add: suffix_def) qed qed subsubsection "Properties of @{term next}" lemma next_suc_suffix: "next (Suc n) s = nextsuffix (next n s)" by simp lemma next_suffix_com: "nextsuffix (next n s) = (next n (nextsuffix s))" by (induct n, auto) lemma next_plus: "next (m+n) s = next m (next n s)" by (induct m, auto) lemma next_empty: assumes H: "emptyseq s" shows "next n s = s" proof (induct n) from H show "next 0 s = s" by auto next fix n assume a1: "next n s = s" have "next (Suc n) s = nextsuffix (next n s)" by auto with a1 have "next (Suc n) s = nextsuffix s" by simp with H show "next (Suc n) s = s" by (simp add: nextsuffix_def nextnat_def) qed lemma notempty_nextnotzero: assumes H: "\<not>emptyseq s" shows "(next (Suc 0) s) 0 \<noteq> s 0" proof - from H have g1: "s (nextnat s) \<noteq> s 0" by (rule nextnat_empty_neq) have "next (Suc 0) s = nextsuffix s" by auto hence "(next (Suc 0) s) 0 = s (nextnat s)" by (simp add: nextsuffix_def suffix_def) with g1 show ?thesis by simp qed lemma next_ex_id: "\<exists> i. s i = (next m s) 0" proof - have "\<exists> i. (s |\<^sub>s i) = (next m s)" proof (induct m) have "s |\<^sub>s 0 = next 0 s" by simp thus "\<exists> i. (s |\<^sub>s i) = (next 0 s)" .. next fix m assume a1: "\<exists> i. (s |\<^sub>s i) = (next m s)" then obtain i where a1': "(s |\<^sub>s i) = (next m s)" .. have "next (Suc m) s = nextsuffix (next m s)" by auto hence "next (Suc m) s = (next m s) |\<^sub>s (nextnat (next m s))" by (simp add: nextsuffix_def) hence "\<exists> i. next (Suc m) s = (next m s) |\<^sub>s i" .. then obtain j where "next (Suc m) s = (next m s) |\<^sub>s j" .. with a1' have "next (Suc m) s = (s |\<^sub>s i) |\<^sub>s j" by simp hence "next (Suc m) s = (s |\<^sub>s (j+i))" by (simp add: suffix_plus) hence "(s |\<^sub>s (j+i)) = next (Suc m) s" by simp thus "\<exists> i. (s |\<^sub>s i) = (next (Suc m) s)" .. qed then obtain i where "(s |\<^sub>s i) = (next m s)" .. hence "(s |\<^sub>s i) 0 = (next m s) 0" by auto hence "s i = (next m s) 0" by (auto simp add: suffix_def) thus ?thesis .. qed subsubsection "Properties of @{term collapse}" lemma emptyseq_collapse_eq: assumes A1: "emptyseq s" shows "\<natural> s = s" proof (unfold collapse_def, rule ext) fix n from A1 have "next n s = s" by (rule next_empty) moreover from A1 have "s n = s 0" by (simp add: emptyseq_def) ultimately show "(next n s) 0 = s n" by simp qed lemma empty_collapse_empty: assumes H: "emptyseq s" shows "emptyseq (\<natural> s)" using H by (simp add: emptyseq_collapse_eq) lemma collapse_empty_empty: assumes H: "emptyseq (\<natural> s)" shows "emptyseq s" proof (rule ccontr) assume a1: "\<not>emptyseq s" from H have "\<forall> i. (next i s) 0 = s 0" by (simp add: collapse_def emptyseq_def) moreover from a1 have "(next (Suc 0) s) 0 \<noteq> s 0" by (rule notempty_nextnotzero) ultimately show "False" by blast qed lemma collapse_empty_iff_empty [simp]: "emptyseq (\<natural> s) = emptyseq s" by (auto elim: empty_collapse_empty collapse_empty_empty) subsection "Similarity of Sequences" text\<open> Since adding or removing stuttering steps does not change the validity of a stuttering-invarant formula, equality is often too strong, and the weaker equality \emph{up to stuttering} is sufficient. This is often called \emph{similarity} ($\approx$) of sequences in the literature, and is required to show that logical operators are stuttering invariant. This is mechanised as: \<close> definition seqsimilar :: "('a seq) \<Rightarrow> ('a seq) \<Rightarrow> bool" (infixl "\<approx>" 50) where "\<sigma> \<approx> \<tau> \<equiv> (\<natural> \<sigma>) = (\<natural> \<tau>)" subsubsection "Properties of @{term seqsimilar}" lemma seqsim_refl [iff]: "s \<approx> s" by (simp add: seqsimilar_def) lemma seqsim_sym: assumes H: "s \<approx> t" shows "t \<approx> s" using H by (simp add: seqsimilar_def) lemma seqeq_imp_sim: assumes H: "s = t" shows "s \<approx> t" using H by simp lemma seqsim_trans [trans]: assumes h1: "s \<approx> t" and h2: "t \<approx> z" shows "s \<approx> z" using assms by (simp add: seqsimilar_def) theorem sim_first: assumes H: "s \<approx> t" shows "first s = first t" proof - from H have "(\<natural> s) 0 = (\<natural> t) 0" by (simp add: seqsimilar_def) thus ?thesis by (simp add: collapse_def first_def) qed lemmas sim_first2 = sim_first[unfolded first_def] lemma tail_sim_second: assumes H: "tail s \<approx> tail t" shows "second s = second t" proof - from H have "first (tail s) = first (tail t)" by (simp add: sim_first) thus "second s = second t" by (simp add: first_tail_second) qed lemma seqsimilarI: assumes 1: "first s = first t" and 2: "nextsuffix s \<approx> nextsuffix t" shows "s \<approx> t" unfolding seqsimilar_def collapse_def proof fix n show "next n s 0 = next n t 0" proof (cases n) assume "n = 0" with 1 show ?thesis by (simp add: first_def) next fix m assume m: "n = Suc m" from 2 have "next m (nextsuffix s) 0 = next m (nextsuffix t) 0" unfolding seqsimilar_def collapse_def by (rule fun_cong) with m show ?thesis by (simp add: next_suffix_com) qed qed lemma seqsim_empty_empty: assumes H1: "s \<approx> t" and H2: "emptyseq s" shows "emptyseq t" proof - from H2 have "emptyseq (\<natural> s)" by simp with H1 have "emptyseq (\<natural> t)" by (simp add: seqsimilar_def) thus ?thesis by simp qed lemma seqsim_empty_iff_empty: assumes H: "s \<approx> t" shows "emptyseq s = emptyseq t" proof assume "emptyseq s" with H show "emptyseq t" by (rule seqsim_empty_empty) next assume t: "emptyseq t" from H have "t \<approx> s" by (rule seqsim_sym) from this t show "emptyseq s" by (rule seqsim_empty_empty) qed lemma seq_empty_eq: assumes H1: "s 0 = t 0" and H2: "emptyseq s" and H3: "emptyseq t" shows "s = t" proof (rule ext) fix n from assms have "t n = s n" by (auto simp: emptyseq_def) thus "s n = t n" by simp qed lemma seqsim_notstutstep: assumes H: "\<not> (stutstep s n)" shows "(s |\<^sub>s (Suc n)) \<approx> nextsuffix (s |\<^sub>s n)" using H by (simp add: notstutstep_nextsuffix1) lemma stut_nextsuf_suc: assumes H: "stutstep s n" shows "nextsuffix (s |\<^sub>s n) = nextsuffix (s |\<^sub>s (Suc n))" proof (cases "emptyseq (s |\<^sub>s n)") case True hence g1: "nextsuffix (s |\<^sub>s n) = (s |\<^sub>s n)" by (simp add: nextsuffix_def nextnat_def) from True have g2: "nextsuffix (s |\<^sub>s Suc n) = (s |\<^sub>s Suc n)" by (simp add: suc_empty nextsuffix_def nextnat_def) have "(s |\<^sub>s n) = (s |\<^sub>s Suc n)" proof fix x from True have "s (x + n) = s (0 + n)" "s (Suc x + n) = s (0 + n)" unfolding emptyseq_def suffix_def by (blast+) thus "(s |\<^sub>s n) x = (s |\<^sub>s Suc n) x" by (simp add: suffix_def) qed with g1 g2 show ?thesis by auto next case False with H have "(nextnat (s |\<^sub>s n)) = Suc (nextnat (s |\<^sub>s Suc n))" by (simp add: stutstep_notempty_sucnextnat) thus ?thesis by (simp add: nextsuffix_def suffix_plus) qed lemma seqsim_stutstep: assumes H: "stutstep s n" shows "(s |\<^sub>s (Suc n)) \<approx> (s |\<^sub>s n)" (is "?sn \<approx> ?s") unfolding seqsimilar_def collapse_def proof fix m show "next m (s |\<^sub>s Suc n) 0 = next m (s |\<^sub>s n) 0" proof (cases m) assume "m=0" with H show ?thesis by (simp add: suffix_def stutstep_def) next fix k assume m: "m = Suc k" with H have "next m (s |\<^sub>s Suc n) = next k (nextsuffix (s |\<^sub>s n))" by (simp add: stut_nextsuf_suc next_suffix_com) moreover from m have "next m (s |\<^sub>s n) = next k (nextsuffix (s |\<^sub>s n))" by (simp add: next_suffix_com) ultimately show "next m (s |\<^sub>s Suc n) 0 = next m (s |\<^sub>s n) 0" by simp qed qed lemma addfeqstut: "stutstep ((first t) ## t) 0" by (simp add: first_def stutstep_def app_def suffix_def) lemma addfeqsim: "((first t) ## t) \<approx> t" proof - have "stutstep ((first t) ## t) 0" by (rule addfeqstut) hence "(((first t) ## t) |\<^sub>s (Suc 0)) \<approx> (((first t) ## t) |\<^sub>s 0)" by (rule seqsim_stutstep) hence "tail ((first t) ## t) \<approx> ((first t) ## t)" by (simp add: suffix_def tail_def) hence "t \<approx> ((first t) ## t)" by (simp add: tail_def app_def suffix_def) thus ?thesis by (rule seqsim_sym) qed lemma addfirststut: assumes H: "first s = second s" shows "s \<approx> tail s" proof - have g1: "(first s) ## (tail s) = s" by (rule seq_app_first_tail) from H have "(first s) = first (tail s)" by (simp add: first_def second_def tail_def suffix_def) hence "(first s) ## (tail s) \<approx> (tail s)" by (simp add: addfeqsim) with g1 show ?thesis by simp qed lemma app_seqsimilar: assumes h1: "s \<approx> t" shows "(x ## s) \<approx> (x ## t)" proof (cases "stutstep (x ## s) 0") case True from h1 have "first s = first t" by (rule sim_first) with True have a2: "stutstep (x ## t) 0" by (simp add: stutstep_def first_def app_def) from True have "((x ## s) |\<^sub>s (Suc 0)) \<approx> ((x ## s) |\<^sub>s 0)" by (rule seqsim_stutstep) hence "tail (x ## s) \<approx> (x ## s)" by (simp add: tail_def suffix_def) hence g1: "s \<approx> (x ## s)" by (simp add: app_def tail_def suffix_def) from a2 have "((x ## t) |\<^sub>s (Suc 0)) \<approx> ((x ## t) |\<^sub>s 0)" by (rule seqsim_stutstep) hence "tail (x ## t) \<approx> (x ## t)" by (simp add: tail_def suffix_def) hence g2: "t \<approx> (x ## t)" by (simp add: app_def tail_def suffix_def) from h1 g2 have "s \<approx> (x ## t)" by (rule seqsim_trans) from this[THEN seqsim_sym] g1 show "(x ## s) \<approx> (x ## t)" by (rule seqsim_sym[OF seqsim_trans]) next case False from h1 have "first s = first t" by (rule sim_first) with False have a2: "\<not> stutstep (x ## t) 0" by (simp add: stutstep_def first_def app_def) from False have "((x ## s) |\<^sub>s (Suc 0)) \<approx> nextsuffix ((x ## s) |\<^sub>s 0)" by (rule seqsim_notstutstep) hence "(tail (x ## s)) \<approx> nextsuffix (x ## s)" by (simp add: tail_def) hence g1: "s \<approx> nextsuffix (x ## s)" by (simp add: seq_app_tail) from a2 have "((x ## t) |\<^sub>s (Suc 0)) \<approx> nextsuffix ((x ## t) |\<^sub>s 0)" by (rule seqsim_notstutstep) hence "(tail (x ## t)) \<approx> nextsuffix (x ## t)" by (simp add: tail_def) hence g2: "t \<approx> nextsuffix (x ## t)" by (simp add: seq_app_tail) with h1 have "s \<approx> nextsuffix (x ## t)" by (rule seqsim_trans) from this[THEN seqsim_sym] g1 have g3: "nextsuffix (x ## s) \<approx> nextsuffix (x ## t)" by (rule seqsim_sym[OF seqsim_trans]) have "first (x ## s) = first (x ## t)" by (simp add: first_def app_def) from this g3 show ?thesis by (rule seqsimilarI) qed text \<open> If two sequences are similar then for any suffix of one of them there exists a similar suffix of the other one. We will prove a stronger result below. \<close> lemma simstep_disj1: assumes H: "s \<approx> t" shows "\<exists> m. ((s |\<^sub>s n) \<approx> (t |\<^sub>s m))" proof (induct n) from H have "((s |\<^sub>s 0) \<approx> (t |\<^sub>s 0))" by auto thus "\<exists> m. ((s |\<^sub>s 0) \<approx> (t |\<^sub>s m))" .. next fix n assume "\<exists> m. ((s |\<^sub>s n) \<approx> (t |\<^sub>s m))" then obtain m where a1': "(s |\<^sub>s n) \<approx> (t |\<^sub>s m)" .. show "\<exists> m. ((s |\<^sub>s (Suc n)) \<approx> (t |\<^sub>s m))" proof (cases "stutstep s n") case True hence "(s |\<^sub>s (Suc n)) \<approx> (s |\<^sub>s n)" by (rule seqsim_stutstep) from this a1' have "((s |\<^sub>s (Suc n)) \<approx> (t |\<^sub>s m))" by (rule seqsim_trans) thus ?thesis .. next case False hence "(s |\<^sub>s (Suc n)) \<approx> nextsuffix (s |\<^sub>s n)" by (rule seqsim_notstutstep) moreover from a1' have "nextsuffix (s |\<^sub>s n) \<approx> nextsuffix (t |\<^sub>s m)" by (simp add: seqsim_suffix_seqsim) ultimately have "(s |\<^sub>s (Suc n)) \<approx> nextsuffix (t |\<^sub>s m)" by (rule seqsim_trans) hence "(s |\<^sub>s (Suc n)) \<approx> t |\<^sub>s (m + (nextnat (t |\<^sub>s m)))" by (simp add: nextsuffix_def suffix_plus_com) thus "\<exists> m. (s |\<^sub>s (Suc n)) \<approx> t |\<^sub>s m" .. qed qed lemma nextnat_le_seqsim: assumes n: "n < nextnat s" shows "s \<approx> (s |\<^sub>s n)" proof (cases "emptyseq s") case True \<comment> \<open>case impossible\<close> with n show ?thesis by (simp add: nextnat_def) next case False from n show ?thesis proof (induct n) show "s \<approx> (s |\<^sub>s 0)" by simp next fix n assume a2: "n < nextnat s \<Longrightarrow> s \<approx> (s |\<^sub>s n)" and a3: "Suc n < nextnat s" from a3 have g1: "s (Suc n) = s 0" by (rule nextnat_le_unch) from a3 have a3': "n < nextnat s" by simp hence "s n = s 0" by (rule nextnat_le_unch) with g1 have "stutstep s n" by (simp add: stutstep_def) hence g2: "(s |\<^sub>s n) \<approx> (s |\<^sub>s (Suc n))" by (rule seqsim_stutstep[THEN seqsim_sym]) with a3' a2 show "s \<approx> (s |\<^sub>s (Suc n))" by (auto elim: seqsim_trans) qed qed lemma seqsim_prev_nextnat: "s \<approx> s |\<^sub>s ((nextnat s) - 1)" proof (cases "emptyseq s") case True hence "s |\<^sub>s ((nextnat s)-(1::nat)) = s |\<^sub>s 0" by (simp add: nextnat_def) thus ?thesis by simp next case False hence "nextnat s > 0" by (rule nextnat_empty_gzero) thus ?thesis by (simp add: nextnat_le_seqsim) qed text \<open> Given a suffix \<open>s |\<^sub>s n\<close> of some sequence \<open>s\<close> that is similar to some suffix \<open>t |\<^sub>s m\<close> of sequence \<open>t\<close>, there exists some suffix \<open>t |\<^sub>s m'\<close> of \<open>t\<close> such that \<open>s |\<^sub>s n\<close> and \<open>t |\<^sub>s m'\<close> are similar and also \<open>s |\<^sub>s (n+1)\<close> is similar to either \<open>t |\<^sub>s m'\<close> or to \<open>t |\<^sub>s (m'+1)\<close>. \<close> lemma seqsim_suffix_suc: assumes H: "s |\<^sub>s n \<approx> t |\<^sub>s m" shows "\<exists>m'. s |\<^sub>s n \<approx> t |\<^sub>s m' \<and> ((s |\<^sub>s Suc n \<approx> t |\<^sub>s Suc m') \<or> (s |\<^sub>s Suc n \<approx> t |\<^sub>s m'))" proof (cases "stutstep s n") case True hence "s |\<^sub>s Suc n \<approx> s |\<^sub>s n" by (rule seqsim_stutstep) from this H have "s |\<^sub>s Suc n \<approx> t |\<^sub>s m" by (rule seqsim_trans) with H show ?thesis by blast next case False hence "\<not> emptyseq (s |\<^sub>s n)" by (rule stutnempty) with H have a2: "\<not> emptyseq (t |\<^sub>s m)" by (simp add: seqsim_empty_iff_empty) hence g4: "nextsuffix (t |\<^sub>s m) = (t |\<^sub>s m) |\<^sub>s Suc (nextnat (t |\<^sub>s m) - 1)" by (simp add: nextnat_empty_gzero nextsuffix_def) have g3: "(t |\<^sub>s m) \<approx> (t |\<^sub>s m) |\<^sub>s (nextnat (t |\<^sub>s m) - 1)" by (rule seqsim_prev_nextnat) with H have G1: "s |\<^sub>s n \<approx> (t |\<^sub>s m) |\<^sub>s (nextnat (t |\<^sub>s m) - 1)" by (rule seqsim_trans) from False have G1': "(s |\<^sub>s Suc n) = nextsuffix (s |\<^sub>s n)" by (rule notstutstep_nextsuffix1[THEN sym]) from H have "nextsuffix (s |\<^sub>s n) \<approx> nextsuffix (t |\<^sub>s m)" by (rule seqsim_suffix_seqsim) with G1 G1' g4 have "s |\<^sub>s n \<approx> t |\<^sub>s (m + (nextnat (t |\<^sub>s m) - 1)) \<and> s |\<^sub>s (Suc n) \<approx> t |\<^sub>s Suc (m + (nextnat (t |\<^sub>s m) - 1))" by (simp add: suffix_plus_com) thus ?thesis by blast qed text \<open> The following main result about similar sequences shows that if \<open>s \<approx> t\<close> holds then for any suffix \<open>s |\<^sub>s n\<close> of \<open>s\<close> there exists a suffix \<open>t |\<^sub>s m\<close> such that \begin{itemize} \item \<open>s |\<^sub>s n\<close> and \<open>t |\<^sub>s m\<close> are similar, and \item \<open>s |\<^sub>s (n+1)\<close> is similar to either \<open>t |\<^sub>s (m+1)\<close> or \<open>t |\<^sub>s m\<close>. \end{itemize} The idea is to pick the largest \<open>m\<close> such that \<open>s |\<^sub>s n \<approx> t |\<^sub>s m\<close> (or some such \<open>m\<close> if \<open>s |\<^sub>s n\<close> is empty). \<close> theorem sim_step: assumes H: "s \<approx> t" shows "\<exists> m. s |\<^sub>s n \<approx> t |\<^sub>s m \<and> ((s |\<^sub>s Suc n \<approx> t |\<^sub>s Suc m) \<or> (s |\<^sub>s Suc n \<approx> t |\<^sub>s m))" (is "\<exists>m. ?Sim n m") proof (induct n) from H have "s |\<^sub>s 0 \<approx> t |\<^sub>s 0" by simp thus "\<exists> m. ?Sim 0 m" by (rule seqsim_suffix_suc) next fix n assume "\<exists> m. ?Sim n m" hence "\<exists>k. s |\<^sub>s Suc n \<approx> t |\<^sub>s k" by blast thus "\<exists> m. ?Sim (Suc n) m" by (blast dest: seqsim_suffix_suc) qed end
Require Import Basics. Require Import Paths. Require Import HIT. Require Import Polygraphs. Require Import PolyMorphs. (** This file contains the definition fo the unit of the adjunction, together with the proof of the first triangular identity. To do that, we first define and show some properties of the inclusion of n-polygraphs into (n+1)-polygraphs **) Definition EmptyA (n : nat) (T : Type) : Aug T n := mkAug False (fun x => False_rect _ x.1). Definition Empty {n : nat} (p : Pol n) : Pol (S n) := Ext p (EmptyA (S n) (Free p)). Definition FreeEmptyA (n : nat) (T : Type) : T -> FreeA (EmptyA n T) := inl. Definition FreeEmpty {n :nat} (p : Pol n) : Free p -> Free (Empty p) := FreeEmptyA (S n) (Free p). Definition EmptyMA (n : nat) (T : Type) (aug : Aug T n) : MAug (fun x => x) (EmptyA n T) aug. Proof. simpl. unshelve econstructor. - exact (False_rect _). - simpl. intro. contradiction. Defined. Lemma EmptyExtensionInitial {n : nat} {p : Pol n} (aug : Aug (Free p) (S n)) : MPol (Empty p) (Ext p aug). Proof. unfold Empty. unshelve econstructor. - exact (fstd IdAndFreeM p). - simpl. change (MAug (FreeM (fstd IdAndFreeM p)) (EmptyA (S n) (Free p)) aug). simple refine (eq_rect (fun W => MAug W (EmptyA (S n) (Free p)) aug) _ _). + exact (fun x => x). + exact (EmptyMA _ _ _). + exact ((sndd IdAndFreeM p) ^). Defined. Definition injectA {n : nat} {F : Type} (aug : Aug F n) : F -> FreeA aug := compose (FreeMA (EmptyMA n F aug)) (FreeEmptyA n F). Definition injectPol {n :nat} (p : Pol n) (aug : Aug (Free p) (S n)) : Free p -> Free (Ext p aug) := injectA aug. (** Unit and triangular identity **) Definition UnitA {n : nat} {F T : Type} (aug : Aug F n) (f : FreeA aug -> T) : aug - (injectA aug) -- (ForgetA f n). Proof. unshelve econstructor. - intro e. simple refine (mkPullB _ _ _). + intro b. apply f. simpl. simple refine (inr _). exact (e, b). + intro. simple refine (inl _). exact (d aug (e, X)). + apply funext. intro. unfold nFaces. unfold compose. exact (f_equal f (incoh (e, x))^). - simpl. intros. reflexivity. Defined. Definition TriangleA {n : nat} {F T : Type} (aug : Aug F n) (f : FreeA aug -> T) : compose (CounitA n f) (FreeMA (UnitA aug f)) = f. Proof. apply funext. simple refine (eqMorphPushout _ _ _). - reflexivity. - intro b2. unfold compose. simpl. destruct b2. reflexivity. - intros [a a']. simpl. simple refine (concat_1p _ @ _). match goal with | |- _ = f_equal (compose ?f ?g) ?p => simple refine (_ @ (ap_compose g f p)^) end. unfold compose. match goal with | |- _ = f_equal ?f _ => simple refine (_ @ f_equal (@f_equal _ _ f _ _) Pushout_rect_compute_coh^) end. simpl. rewrite concat_1p. unfold CounitA. simple refine (_ @ Pushout_rect_compute_coh^). simpl. simple refine (_ @ (concat_ap_V _ _)^). simple refine (_ @ (f_equal (fun W => W ^) (funextcompute _ a')^)). simpl. match goal with | |- _ = (f_equal f ?p ^)^ => simple refine (_ @ f_equal (fun W => W^ ) (concat_ap_V f p)^); exact ((concat_VV _)^) end. Defined. (** The previous two lemmas seem like the correct notions of units and triangle identity for augmentations. However, it turns out that the proof of polygraphs requires the following two more complicated versions **) Definition UnitBisA {n : nat} {F : Type} (aug : Aug F (S n)) (f : F -> (Free (Forget (FreeA aug) n))) (H : compose (Counit (FreeA aug) n) f = injectA aug): aug - f -- (ForgetA (Counit (FreeA aug) n) (S n)). Proof. unshelve econstructor. - intro e. simpl. simple refine (mkPullB _ _ _). + intro x. exact (inr (e, x)). + intro x. simpl. apply f. exact (d aug (e, x)). + unfold nFaces. unfold compose. apply funext. intro x. simple refine (_ @ (f_equal (fun W => W (d aug (e, x))) H^)). exact ((incoh (e, x))^). - reflexivity. Defined. Lemma TriangleABis {n : nat} {F : Type} (aug : Aug F (S n)) (f : F -> (Free (Forget (FreeA aug) n))) (H : compose (Counit (FreeA aug) n) f = injectA aug): compose (CounitA (S n) (Counit (FreeA aug) n)) (FreeMA (UnitBisA aug f H)) = (fun x : FreeA aug => x). Proof. apply funext. simple refine (eqMorphPushout _ _ _). - intro b1. unfold compose. simpl. exact (f_equal (fun W => W b1) H). - intro b2. unfold compose. simpl. destruct b2. reflexivity. - intros a. unfold compose. simpl. match goal with | |- _ = f_equal (fun x => CounitA ?a1 ?a2 (@?W x)) (incoh a) => change (f_equal (fun x => CounitA a1 a2 (W x)) (incoh a)) with (f_equal (compose (CounitA a1 a2) W) (incoh a)); simple refine (_ @ (ap_compose W (CounitA a1 a2) (incoh a))^) end. unfold compose. unfold CounitA. match goal with | |- _ = f_equal ?f _ => simple refine (_ @ (f_equal (fun W => f_equal f W) Pushout_rect_compute_coh^)) end. simpl. match goal with | |- _ = f_equal ?f (1 @ ?p) => simple refine (_ @ (f_equal (fun W => f_equal f W) (concat_1p p )^)) end. match goal with | |- _ = f_equal (Pushout_rect ?a1 ?a2 ?a3) (incoh ?a4) => simple refine (_ @ (Pushout_rect_compute_coh (f1 := (fun x => pi2 x.1 x.2)) )^) end. simpl. match goal with | |- _ = f_equal ?f ?p ^ => simple refine (_ @ (concat_ap_V f p)^) end. match goal with | |- _ = (f_equal (fun W => W a.2) (funext ?p))^ => simple refine (_ @ (f_equal (fun W => W^) (funextcompute p a.2)^)) end. match goal with | |- ?p @ _ = _ => simple refine ((f_equal (fun W => p @ W) (f_equal_id _)) @ _) end. simple refine (_ @ (concat_V _ _)^). match goal with | |- _ = ?p ^ @ ?q ^ ^ => simple refine (_ @ f_equal (fun W => p ^ @ W) (concat_VV _)^); simple refine (_ @ f_equal (fun W => W ^ @ q) (concat_ap_V _ _)^); exact (f_equal (fun W => W @ q) (concat_VV _)^) end. Defined. Fixpoint UnitPol {n : nat} (p : Pol n) {struct n} : {f : MPol p (Forget (Free p) n) | compose (Counit (Free p) n) (FreeM f) = (fun x => x)}. Proof. destruct n. - simple refine (mkDPair _ _). + destruct p using case0. econstructor. exact (fun x => x). + destruct p using case0. exact 1. - simple refine (mkDPair _ _); destruct p as [p aug] using caseS'. + simpl. unshelve econstructor. * exact (ComposeM (fstd (UnitPol n p)) (ForgetM n (injectPol p aug) ) ). * simpl. simple refine (UnitBisA _ _ _). match goal with |- compose ?f _ = _ => simple refine (f_equal (fun W => compose f W) (FreeComposeM _ _) @ _) end. match goal with | |- compose ?f (compose ?g ?h) = _ => change (compose f (compose g h)) with (compose (compose f g) h); simple refine (f_equal (fun W => compose W h) (CounitM _ _) @ _) end. match goal with | |- compose (compose ?f ?g) ?h = _ => change (compose (compose f g) h) with (compose f (compose g h)); exact (f_equal (fun W => compose f W) (sndd (UnitPol _ _))) end. + simpl. simple refine (TriangleABis _ _ _). Defined. Notation Unit p := (fstd (UnitPol p)). Notation FreeTriangular p := (sndd (UnitPol p)).
%SAVE2PDF Saves a figure as a properly cropped pdf % % save2pdf(pdfFileName,handle,dpi) % % - pdfFileName: Destination to write the pdf to. % - handle: (optional) Handle of the figure to write to a pdf. If % omitted, the current figure is used. Note that handles % are typically the figure number. % - dpi: (optional) Integer value of dots per inch (DPI). Sets % resolution of output pdf. Note that 150 dpi is the Matlab % default and this function's default, but 600 dpi is typical for % production-quality. % % Saves figure as a pdf with margins cropped to match the figure size. % (c) Gabe Hoffmann, [email protected] % Written 8/30/2007 % Revised 9/22/2007 % Revised 1/14/2007 function save2pdf(pdfFileName,handle,dpi) % Verify correct number of arguments error(nargchk(0,3,nargin)); % If no handle is provided, use the current figure as default if nargin<1 [fileName,pathName] = uiputfile('*.pdf','Save to PDF file:'); if fileName == 0; return; end pdfFileName = [pathName,fileName]; end if nargin<2 handle = gcf; end if nargin<3 dpi = 150; end % Backup previous settings prePaperType = get(handle,'PaperType'); prePaperUnits = get(handle,'PaperUnits'); preUnits = get(handle,'Units'); prePaperPosition = get(handle,'PaperPosition'); prePaperSize = get(handle,'PaperSize'); % Make changing paper type possible set(handle,'PaperType','<custom>'); % Set units to all be the same set(handle,'PaperUnits','inches'); set(handle,'Units','inches'); % Set the page size and position to match the figure's dimensions paperPosition = get(handle,'PaperPosition'); position = get(handle,'Position'); set(handle,'PaperPosition',[0,0,position(3:4)]); set(handle,'PaperSize',position(3:4)); % Save the pdf (this is the same method used by "saveas") print(handle,'-dpdf',pdfFileName,sprintf('-r%d',dpi)) % Restore the previous settings set(handle,'PaperType',prePaperType); set(handle,'PaperUnits',prePaperUnits); set(handle,'Units',preUnits); set(handle,'PaperPosition',prePaperPosition); set(handle,'PaperSize',prePaperSize);
{-# OPTIONS --cubical --safe #-} module Algebra.Construct.Sign where open import Prelude data Signed {a} (A : Type a) : Type a where ⁻_ : A → Signed A ±0 : Signed A ⁺_ : A → Signed A unsign : (A → B) → B → (A → B) → Signed A → B unsign f g h (⁻ x) = f x unsign f g h ±0 = g unsign f g h (⁺ x) = h x
lemma setdist_eq_0I: "\<lbrakk>x \<in> S; x \<in> T\<rbrakk> \<Longrightarrow> setdist S T = 0"
Formal statement is: lemma poly_0_coeff_0: "poly p 0 = coeff p 0" Informal statement is: The value of a polynomial at $0$ is equal to its constant coefficient.
||| A segment is a compositional fragment of a telescope. ||| A key difference is that segments are right-nested, whereas ||| telescopes are left nested. ||| So telescopes are convenient for well-bracketing dependencies, ||| but segments are convenient for processing telescopes from left ||| to right. ||| ||| As with telescopes, indexing segments by their length (hopefully) ||| helps the type-checker infer stuff. module Data.Telescope.Segment import Data.Telescope.Telescope import Syntax.PreorderReasoning import Data.Fin import Data.Nat import Data.DPair %default total ||| A segment is a compositional fragment of a telescope, indexed by ||| the segment's length. public export data Segment : (n : Nat) -> Left.Telescope k -> Type where Nil : Segment 0 gamma (::) : (ty : TypeIn gamma) -> (delta : Segment n (gamma -. ty)) -> Segment (S n) gamma ||| A segment of size `n` indexed by `gamma` can be seen as the tabulation of a ||| function that turns environments for `gamma` into telescopes of size `n`. public export tabulate : (n : Nat) -> (Left.Environment gamma -> Left.Telescope n) -> Segment n gamma tabulate Z tel = [] tabulate (S n) tel = (sigma :: tabulate n (uncurry delta)) where sigma : TypeIn gamma sigma env = fst (uncons (tel env)) delta : (env : Environment gamma) -> sigma env -> Left.Telescope n delta env v with (uncons (tel env)) delta env v | (sig ** delt ** _) = delt v ||| Any telescope is a segment in the empty telescope. It amounts to looking ||| at it left-to-right instead of right-to-left. public export fromTelescope : {k : Nat} -> Left.Telescope k -> Segment k [] fromTelescope gamma = tabulate _ (const gamma) ||| Conversely, a segment of size `n` in telescope `gamma` can be seen as a function ||| from environments for `gamma` to telescopes of size `n`. public export untabulate : {n : Nat} -> Segment n gamma -> (Left.Environment gamma -> Left.Telescope n) untabulate [] _ = [] untabulate (ty :: delta) env = cons (ty env) (untabulate delta . (\ v => (env ** v))) ||| Any segment in the empty telescope correspond to a telescope. public export toTelescope : {k : Nat} -> Segment k [] -> Left.Telescope k toTelescope seg = untabulate seg () %name Segment delta,delta',delta1,delta2 infixl 3 |++, :++ ||| This lemma comes up all the time when mixing induction on Nat with ||| indexing modulo addition. An alternative is to use something like ||| frex. succLemma : (lft, rgt : Nat) -> lft + (S rgt) = S (lft + rgt) succLemma x y = Calc $ |~ x + (1 + y) ~~ (x + 1)+ y ...(plusAssociative x 1 y) ~~ (1 + x)+ y ...(cong (+y) $ plusCommutative x 1) ~~ 1 + (x + y) ...(sym $ plusAssociative 1 x y) -- Should go somehwere in stdlib public export keep : (0 prf : a ~=~ b) -> a ~=~ b keep Refl = Refl -- Keeping the `Nat` argument relevant, should (hopefully) only -- case-split on it and not the environment unnecessarily, allowing us -- to calculate, so long as we know the 'shape' of the Segment. -- -- This should work in theory, I don't think it actually works for -- Idris at the moment. Might work in Agda? ||| Segments act on telescope from the right. public export (|++) : (gamma : Left.Telescope k) -> {n : Nat} -> (delta : Segment n gamma) -> Left.Telescope (n + k) (|++) gamma {n = 0} delta = gamma (|++) gamma {n=S n} (ty :: delta) = rewrite sym $ succLemma n k in gamma -. ty |++ delta ||| Segments form a kind of an indexed monoid w.r.t. the action `(|++)` public export (++) : {gamma : Left.Telescope k} -> {n : Nat} -> (lft : Segment n gamma ) -> (rgt : Segment m (gamma |++ lft)) -> Segment (n + m) gamma (++) {n = 0 } delta rgt = rgt (++) {n = S n} (ty :: lft) rgt = ty :: lft ++ rewrite succLemma n k in rgt -- This monoid does act on telescopes: export actSegmentAssociative : (gamma : Left.Telescope k) -> (lft : Segment n gamma) -> (rgt : Segment m (gamma |++ lft)) -> (gamma |++ (lft ++ rgt)) ~=~ ((gamma |++ lft) |++ rgt) actSegmentAssociative gamma {n = 0} [] rgt = Refl actSegmentAssociative gamma {n = S n} (ty :: lft) rgt = let rgt' : Segment {k = n + (S k)} m (gamma -. ty |++ lft) rgt' = rewrite succLemma n k in rgt rgt_eq_rgt' : rgt ~=~ rgt' rgt_eq_rgt' = rewrite succLemma n k in Refl in rewrite sym $ succLemma (n + m) k in rewrite sym $ succLemma n k in keep $ Calc $ |~ ((gamma -. ty) |++ (lft ++ rgt')) ~~ ((gamma -. ty |++ lft) |++ rgt') ...(actSegmentAssociative (gamma -. ty) lft rgt') public export weaken : {0 gamma : Left.Telescope k} -> {delta : Segment n gamma} -> (sy : TypeIn gamma) -> TypeIn (gamma |++ delta) weaken {delta = [] } sy = sy weaken {n = S n} {delta = ty :: delta} sy = rewrite sym $ succLemma n k in weaken (weakenTypeIn sy) public export projection : {0 gamma : Left.Telescope k} -> {n : Nat} -> {0 delta : Segment n gamma} -> Environment (gamma |++ delta) -> Environment gamma projection {n = 0 } {delta = [] } env = env projection {n = S n} {delta = ty :: delta} env = let (env' ** _) = projection {n} {delta} $ rewrite succLemma n k in env in env' infixl 4 .= public export data Environment : (env : Left.Environment gamma) -> (delta : Segment n gamma) -> Type where Empty : Environment env [] (.=) : {0 gamma : Left.Telescope k} -> {0 ty : TypeIn gamma} -> {0 env : Left.Environment gamma} -> {0 delta : Segment n (gamma -. ty)} -> (x : ty env) -> (xs : Segment.Environment (env ** x) delta) -> Environment env (ty :: delta) public export (:++) : {0 gamma : Left.Telescope k} -> {0 delta : Segment n gamma} -> (env : Left.Environment gamma) -> (ext : Segment.Environment env delta) -> Left.Environment (gamma |++ delta) (:++) env Empty = env (:++) {n = S n} env (x .= xs) = rewrite sym $ succLemma n k in (env ** x) :++ xs -- This is too nasty for now, leave to later {- public export break : {0 k : Nat} -> (gamma : Telescope k') -> (pos : Position gamma) -> {auto 0 ford : k' = cast pos + k } -> Telescope k break gamma FZ {ford = Refl} = gamma break [] (FS pos) {ford = _ } impossible break {k' = S k'} (gamma -. ty) (FS pos) {ford} = break gamma pos {ford = Calc $ |~ k' ~~ cast pos + k ...(succInjective _ _ ford)} -- Should go into Data.Fin export lastIsLast : {n : Nat} -> cast (last {n}) = n lastIsLast {n = 0 } = Refl lastIsLast {n = S n} = rewrite lastIsLast {n} in Refl public export finComplement : {n : Nat} -> (i : Fin n) -> Fin n finComplement FZ = last finComplement (FS i) = weaken (finComplement i) export castNaturality : (i : Fin n) -> finToNat (weaken i) ~=~ finToNat i castNaturality FZ = Refl castNaturality (FS i) = rewrite castNaturality i in Refl export finComplementSpec : (i : Fin (S n)) -> cast i + cast (finComplement i) = n finComplementSpec FZ = keep lastIsLast finComplementSpec {n = .(S n)} (FS i@ FZ ) = rewrite castNaturality (finComplement i) in rewrite finComplementSpec i in Refl finComplementSpec {n = .(S n)} (FS i@(FS _)) = rewrite castNaturality (finComplement i) in rewrite finComplementSpec i in Refl complementLastZero : (n : Nat) -> finComplement (last {n}) = FZ complementLastZero n = finToNatInjective _ _ $ plusLeftCancel n _ _ $ Calc $ let n' : Nat n' = cast $ finComplement $ last {n} in |~ n + n' ~~ (finToNat $ last {n}) + n' ...(cong (+n') $ sym $ lastIsLast {n}) ~~ n ...(finComplementSpec $ last {n}) ~~ n + 0 ...(sym $ plusZeroRightNeutral n) public export breakOnto : {0 k,k' : Nat} -> (gamma : Telescope k) -> (pos : Position gamma) -> (delta : Segment n gamma) -> {auto 0 ford1 : k' === (finToNat $ finComplement pos) } -> {default -- disgusting, sorry (replace {p = \u => k = finToNat pos + u} (sym ford1) (sym $ finComplementSpec pos)) 0 ford2 : (k === ((finToNat pos) + k')) } -> Segment (cast pos + n) (break {k = k'} gamma pos {ford = ford2}) breakOnto gamma FZ delta {ford1 = Refl} {ford2} = rewrite sym ford2 in delta breakOnto (gamma -. ty) (FS pos) delta {ford1 = Refl} {ford2} = rewrite sym $ succLemma (cast pos) n in rewrite castNaturality (finComplement pos) in breakOnto gamma pos (ty :: delta) uip : (prf1, prf2 : x ~=~ y) -> prf1 ~=~ prf2 uip Refl Refl = Refl export breakStartEmpty : (gamma : Telescope k') -> {auto 0 ford1 : k = 0} -> {auto 0 ford2 : k' = finToNat (start gamma) + k} -> break {k} {k'} gamma (start gamma) {ford = ford2} ~=~ Telescope.Nil breakStartEmpty [] {ford1 = Refl} {ford2 = Refl} = Refl breakStartEmpty {k} {k' = S k'} {ford1} {ford2} (gamma -. ty) = -- Yuck! let 0 u : (k' = finToNat (start gamma) + k) u = succInjective _ _ ford2 v : break {k} {k'} gamma (start gamma) {ford = u} ~=~ Telescope.Nil v = breakStartEmpty {k} {k'} gamma {ford2 = u} in replace {p = \z => Equal {a = Telescope k} {b = Telescope 0} (break {k'} {k} gamma (start gamma) {ford = z}) [] } (uip u _) (keep v) public export projection : {0 gamma : Telescope k} -> (pos : Position gamma) -> (env : Environment gamma) -> Environment (break {k = cast (finComplement pos)} gamma pos {ford = sym $ finComplementSpec pos}) projection FZ env = rewrite finComplementSpec $ FZ {k} in env projection {gamma = []} (FS pos) Empty impossible projection {k = S k} {gamma = gamma -. ty} (FS pos) (env ** x) = rewrite castNaturality (finComplement pos) in projection {k} pos env -}
lemma bounded_box [simp]: fixes a :: "'a::euclidean_space" shows "bounded (box a b)"
using DifferentialEquations, Plots 𝞪 = 1 u0 = 1/2 f(t,u) = 𝞪*u tspan = (0.0, 1.0) prob = ODEProblem(f, u0, tspan) sol1 = solve(prob, Euler(), dt=1/2^1) sol2 = solve(prob, Euler(), dt=1/2^2) sol3 = solve(prob, Euler(), dt=1/2^4) #[t+2u for (t,u) in zip(sol1.t,sol.u)] x = 0.0:0.05:1.0 p = plot(x, sol1(x)) plot!(p, x, sol2(x)) plot!(p, x, sol3(x)) gui()
! RUN: %S/test_errors.sh %s %t %f18 -fopenmp ! OpenMP Version 4.5 ! 2.15.3.6 Reduction Clause program omp_reduction integer :: i integer :: k = 10 integer :: j = 10 !ERROR: 'k' appears in more than one data-sharing clause on the same OpenMP directive !$omp parallel do reduction(+:k), reduction(-:k) do i = 1, 10 k = k + 1 end do !$omp end parallel do !ERROR: 'k' appears in more than one data-sharing clause on the same OpenMP directive !$omp parallel do reduction(+:k), reduction(-:j), reduction(+:k) do i = 1, 10 k = k + 1 end do !$omp end parallel do !ERROR: 'k' appears in more than one data-sharing clause on the same OpenMP directive !$omp parallel do reduction(+:j), reduction(-:k), reduction(+:k) do i = 1, 10 k = k + 1 end do !$omp end parallel do !ERROR: 'k' appears in more than one data-sharing clause on the same OpenMP directive !$omp parallel do reduction(+:j), reduction(-:k), private(k) do i = 1, 10 k = k + 1 end do !$omp end parallel do end program omp_reduction
Stefano Guzetti is a composer, producer and sound designer based in Sardina, Italy. He has an ensemble that has released three albums, Home Piano Book (Volume One), Ensemble, and Leaf. He was previously an ambient electronic musician as Waves on Canvas. While not touring Stefano produces soundtracks and sound design for film, documentaries and video games. Innerversitysound: Stefano, a bit of background first. You had a recent earlier electronic outfit called Waves on Canvas that produced electronic music that was received well enough given the scene. But nothing in comparison to the reception that your three albums with your ensemble. Can you tell us a bit about the departure from electronic music to a form of modern classical ensemble? What was the impetus for you for this break? Stefano: Basically I had a graduation in electronic music from the conservatory in my town. I was very into electronic music and I had studied it a lot. But also from childhood I had a background in classical music because I studied organ, or an instrument with a keyboard. Then I made this Waves on Canvas project and it was very great for me and also it was a way of mine to give a rendition, or a proper tribute to what I was into when I was younger, especially 4AD stuff in the Ivo (Watts-Russell) era. But in regarding electronic music I’ve got this mixed feeling. Especially nowadays when everyone can buy a computer, a laptop and record some seagulls or birds with their smartphone and then download a version of Ableton Live, add some effects, some tweaks and then claim himself an electronic musician or a drone music musician. One of the reasons for the change was I wanted to take a distance from all of this because now a lot of people, a lot really, are making electronic music. If you take an example of the 90’s when buying music gear was really expensive and it wasn’t something that was ready at hand for everyone, which wasn’t a good thing anyway, because in my opinion everyone should have the opportunity to say something musically. It was different, now everyone is making electronic music and to my personal subjective perception most of them sound the same. Because they are done with the same environment, the same software, a laptop and so forth. This was one of the reasons but I also just wanted to get back to simple things and try to say something musically, just for me. Interested in just a few things, natural acoustic sounds for instance, and I wanted to get back to my roots, because when I was younger I was just playing an instrument as well. So this is something that really made me decide to be just me, myself, and just work with simple natural sounds. From time to time I had some electronicia, some simple sine waves and simple elements, like little noises, but these are just things that in electronic music are considered a simple thing, a sine wave. These are things you can also find in the works of Stockhausen or Xenakis, basically in the pioneers of electronic music. So we are not talking about synthesisers or computers but more about tapes. So I just decided to change and I’m ok with this decision really. Innerversitysound:In interviews you have mentioned a wide range of influences from industrial, indie pop, German electronic music, drum and bass, ambient, and the ethereal electronic pop of your teenage years. The early band of yours Antennah, what was the ideas that drove you and your friend Valentinno Murru? Stefano: When I was a child I was playing the organ and when I was a teenager I discovered New Wave bands, Joy Division and that kind of stuff from about 1986. So my decision was to buy a bass, I was a bass player and we just formed this band. We just wanted to make something new, quite naïve. It was great but after about five years I just wanted to make something else and this electronic music thing in me started when I was very young I had this computer in my house and I started programming this computer to make simple sounds and to play by pressing the keys of the keyboard while I was playing the organ. So I was tweaking a home computer to make some sounds and noises and this was my very first approach to electronic music. So after I was in a band for five years, playing the bass, I felt a real need, an urgency to widen my palette of sounds so I decided to leave them and start making electronic music. From 1992 until 2006 I was making electronic music. The last thing I did, apart from the Waves on Canvas project was a collection of remixes for Kirsten Hersch, the singer for Throwing Muses, because in a period around 2006-7 she was recording the tracks of her new album and releasing the tracks of the songs on the web. So I was just taking the vocal parts and doing the rest, a brand new arrangement with new chords, new tonal centre. Just then I was just starting to think differently about electronic music. So this is just my background, I was taught classical music, I played bass in a band but in the meantime I was still tweaking my computer at home, I embraced electronic music, but now it is like being back home again. Just being what I was when I started making music when I was a child. Innerversitysound: So the immediate reception of At Home Piano Book (Volume One) on Home Normal was decisive in its endorsement of your new approach to music. Can you tell us a bit about this album and how the collaboration with Ian Hawgood came about? Stefano: Basically I started making these little compositions on the piano, they were just little ideas. I sat at the piano when I had ideas and if I felt they were interesting I just recorded the scratch idea on the iPad. So then I started to compose them properly with a kind of structure and my idea was to make a collection of piano impressions, like little water colours, something like that. Nothing too serious. I sent a few of those tracks to Ian, about 5 years back and he was really into those tracks. Then we started emailing and I felt quite lucky, because when you have a label like Home Normal, which is kind of busy, there are a lot of people sending stuff, I felt lucky anyway. And then we became friends. Of course there is a mutual friendship now between the artist and the label as well. I wanted to keep that feeling of playing in a room, a very simple thing. Innerversitysound: You are incorporating minimal electronic touches and processing. Has it receded so far into the background that it may eventually disappear? Or has the impression of the knowledge gained by exposure to these forms indelibly informed your composition of classic forms? Stefano: There is a future release that will be out in September that is based on a work of a friend of mine who makes paintings and cartoons as well. He was living in Japan for about 9 years, he worked with Sakamoto, designed a Swatch and he made this last book about his memories in Japan. I was really inspired by his latest work because I love Japanese culture as well and then I wrote and produced this new album called Japanese Notebooks. It features some electronicia, but very subtle, there is also some in Leaf. It is just a little colour and nothing that characterises too much the overall sound. What I still like about elements that come from electronic are the sub-basses and that round warm feeling. And that is just from a simple sine wave, a regular oscillation of a wave. Yes there is still electronic music but very few and just in a very delicate measure. I am planning to use some electronic elements like arpeggios of simple waves to be a part of an arrangement in the future. I am thinking about this idea but mostly it is just acoustic music. I don’t want to be a second hand Max Richter or things like that because mostly I am still exploring and looking for a language of mine of course for otherwise it would not be very useful to be out there and be a clone of someone. Innerversitysound: You formed an ensemble which is a change from the solitary electronic musician. It involves a good deal more interpersonal communication. How did forming this ensemble come about and can you tell us a bit about the dynamics of working with 3 other people in an ensemble has changed your practice? Stefano: If you make electronic music for instance, you have a very immediate response to what you are doing because you are just playing sounds with a machine. You have got those sounds, just suddenly. When you score, when you write music on a score, yes you can make sounds to make a sort of pre-production of what you have in mind. But then again when you play with real players it will sound different again. So it’s really exciting and interesting because a player is not a machine and he will play differently every time and it will depend on how tired he is from his feeling of the day; a lot of variations can happen and anyway real instruments forever change. Yes the real feeling is in the score but the overall feeling of the track can change of course. This is something that fascinates me a lot because we are humans, we are faulty humans by nature so it’s great to transpose this aspect into music. We are not talking about recorded music that will sound the same every time you play it to your friends but music that will change every time and it’s great. I love this, I really need this aspect from music to be alive, in a way. Innerversitysound: In Quiet Fracture on the Leaf album is the most sound designed piece of the recent few albums. Is this interlude kind of thing going to happen more often or was it something that just occurred in the making of the album. Stefano: Yes, Leaf, it’s an album of that started when my father started being ill. And my father now has a very serious illness. And this illness was showing by some very strange events like from time to time he was falling but we underestimated what was happening. Quiet Fracture is about something that is very slowly starts to go, in this case it was my father, and then shows in itself completely. So there are some steps and some laughter from a few women. This is quite symbolistic about something that starts to show inside and then grows as a big laughter. Yes that album it is written, ‘from my father, to my father’ and it was a very bad time and for some reasons it still is. It’s quite personal to be honest. Innerversitysound: In reading background material about what you do I stopped at you commenting that you had adopted a very simple attitude towards life and music generally. If you could elaborate on this turn to simplicity and its effects on the whole of what you do in life. Stefano: Simplicity, simple things, it is a value that I make mine a lot. For instance my decision to move on from electronic music to apparently more simple music. Like the title Leaf, it is just a small green element that we see on the side of the road, in the trees, but if you move your attention to the inner structure of the leaf, in this structure you see a lot of little path roads and this is a clear symptom that simplicity shows us a different world if you take the right pathways and if you approach simplicity with the right attitude. I have been doing Zen meditation for about 10 years in my life so I am really attached to a simple approach to life which is not a basic approach. It is just simple because then by embracing simplicity you can embrace the complexity of life as well. So it is something very connected. Like for instance when I was making electronic music I had complexity at hand very easy because of sounds, because of all those electronic elaborations on sounds as well. But to me it wasn’t that interesting anymore. But if you use just simple sounds and you give them the proper attention to the inner structure of a simple acoustic sound, it has a lot of things that change every time. Like if you struck a note on the piano and every time it will resonate differently and this is apparently a simple sound which it definitely is not. This is an example of simplicity not being simple at all. Simplicity being a great and a good example of the complexity of life itself. Because simple things to me are just the first side of the real complexity of life. Innerversitysound: Your album Japanese Notebooks is slated for later this year. Is it completed yet, or is it still in production or in Ian Hawgood’s very long cue for mastering? Stefano: The album is just finished, mixed and mastered. I finished it in January and I am leaving it to ‘take the dust’ for 4 to 5 months and then I will listen to it again to fix a few things with fresh ears and a fresh mind because you have to take the distance from things at a certain point. Possibly, I don’t know yet, I will ask someone to master it. I still have to decide. I usually master things myself, I am very much of a DIY person, and I really love this attitude. I do almost everything about my job; like promoting, producing, I have my own label as well, Stella Recordings, for my stuff, so it’s really important for me to have most of the things under my control. I rarely work with people, one of these ones is Ian because I really trust him, we are friends, but I really trust Ian and his approach to music. So this album is basically finished, I just have to fix a few things here and there. But that’s it really. Innerversitysound: In terms of ambitions, or strategies when this simplicity gets a bit tricky and demanding. Have you an escape plan lined up? Stefano: My escape plan is that I will always have to be honest with myself and correct about what I am doing at the moment. And when all of this won’t work anymore I will ask myself what is happening and if I won’t have any reply for myself, I always tell myself and to my future wife as well, maybe I will stop making music as well. I hate the idea of riding the wave of what is going on at the moment because I wouldn’t be honest to myself and mostly I would be wasting my time. Because it is not written anywhere in the sky that I have to make music. Maybe there will be a time when I just have to stop, or maybe not. I don’ know. But what I know is that my only escape is just to be honest with myself and ask myself directly what’s happening and add a proper reply, never be negative or positive. I hope positive. Leaf is out now on Stella Recordings and digitally on Home Normal.
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.int.basic import algebra.char_zero import order.locally_finite import data.finset.locally_finite /-! # Finite intervals of integers This file proves that `ℤ` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. -/ open finset int instance : locally_finite_order ℤ := { finset_Icc := λ a b, (finset.range (b + 1 - a).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding a, finset_Ico := λ a b, (finset.range (b - a).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding a, finset_Ioc := λ a b, (finset.range (b - a).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding (a + 1), finset_Ioo := λ a b, (finset.range (b - a - 1).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding (a + 1), finset_mem_Icc := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, rw [lt_sub_iff_add_lt, int.lt_add_one_iff, add_comm] at h, exact ⟨int.le.intro rfl, h⟩ }, { rintro ⟨ha, hb⟩, use (x - a).to_nat, rw ←lt_add_one_iff at hb, rw to_nat_sub_of_le ha, exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ } end, finset_mem_Ico := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ }, { rintro ⟨ha, hb⟩, use (x - a).to_nat, rw to_nat_sub_of_le ha, exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ } end, finset_mem_Ioc := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, rw [←add_one_le_iff, le_sub_iff_add_le', add_comm _ (1 : ℤ), ←add_assoc] at h, exact ⟨int.le.intro rfl, h⟩ }, { rintro ⟨ha, hb⟩, use (x - (a + 1)).to_nat, rw [to_nat_sub_of_le ha, ←add_one_le_iff, sub_add, add_sub_cancel], exact ⟨sub_le_sub_right hb _, add_sub_cancel'_right _ _⟩ } end, finset_mem_Ioo := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, rw [sub_sub, lt_sub_iff_add_lt'] at h, exact ⟨int.le.intro rfl, h⟩ }, { rintro ⟨ha, hb⟩, use (x - (a + 1)).to_nat, rw [to_nat_sub_of_le ha, sub_sub], exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ } end } namespace int variables (a b : ℤ) lemma Icc_eq_finset_map : Icc a b = (finset.range (b + 1 - a).to_nat).map (nat.cast_embedding.trans $ add_left_embedding a) := rfl lemma Ico_eq_finset_map : Ico a b = (finset.range (b - a).to_nat).map (nat.cast_embedding.trans $ add_left_embedding a) := rfl lemma Ioc_eq_finset_map : Ioc a b = (finset.range (b - a).to_nat).map (nat.cast_embedding.trans $ add_left_embedding (a + 1)) := rfl lemma Ioo_eq_finset_map : Ioo a b = (finset.range (b - a - 1).to_nat).map (nat.cast_embedding.trans $ add_left_embedding (a + 1)) := rfl @[simp] lemma card_Icc : (Icc a b).card = (b + 1 - a).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } @[simp] lemma card_Ico : (Ico a b).card = (b - a).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } @[simp] lemma card_Ioc : (Ioc a b).card = (b - a).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } @[simp] lemma card_Ioo : (Ioo a b).card = (b - a - 1).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } lemma card_Icc_of_le (h : a ≤ b + 1) : ((Icc a b).card : ℤ) = b + 1 - a := by rw [card_Icc, to_nat_sub_of_le h] lemma card_Ico_of_le (h : a ≤ b) : ((Ico a b).card : ℤ) = b - a := by rw [card_Ico, to_nat_sub_of_le h] lemma card_Ioc_of_le (h : a ≤ b) : ((Ioc a b).card : ℤ) = b - a := by rw [card_Ioc, to_nat_sub_of_le h] lemma card_Ioo_of_lt (h : a < b) : ((Ioo a b).card : ℤ) = b - a - 1 := by rw [card_Ioo, sub_sub, to_nat_sub_of_le h] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = (b + 1 - a).to_nat := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = (b - a).to_nat := by rw [←card_Ico, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = (b - a).to_nat := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = (b - a - 1).to_nat := by rw [←card_Ioo, fintype.card_of_finset] lemma card_fintype_Icc_of_le (h : a ≤ b + 1) : (fintype.card (set.Icc a b) : ℤ) = b + 1 - a := by rw [card_fintype_Icc, to_nat_sub_of_le h] lemma card_fintype_Ico_of_le (h : a ≤ b) : (fintype.card (set.Ico a b) : ℤ) = b - a := by rw [card_fintype_Ico, to_nat_sub_of_le h] lemma card_fintype_Ioc_of_le (h : a ≤ b) : (fintype.card (set.Ioc a b) : ℤ) = b - a := by rw [card_fintype_Ioc, to_nat_sub_of_le h] lemma card_fintype_Ioo_of_lt (h : a < b) : (fintype.card (set.Ioo a b) : ℤ) = b - a - 1 := by rw [card_fintype_Ioo, sub_sub, to_nat_sub_of_le h] lemma image_Ico_mod (n a : ℤ) (h : 0 ≤ a) : (Ico n (n+a)).image (% a) = Ico 0 a := begin obtain rfl | ha := eq_or_lt_of_le h, { simp, }, ext i, simp only [mem_image, exists_prop, mem_range, mem_Ico], split, { rintro ⟨i, h, rfl⟩, exact ⟨mod_nonneg i (ne_of_gt ha), mod_lt_of_pos i ha⟩, }, intro hia, have hn := int.mod_add_div n a, obtain hi | hi := lt_or_le i (n % a), { refine ⟨i + a * (n/a + 1), ⟨_, _⟩, _⟩, { rw [add_comm (n/a), mul_add, mul_one, ← add_assoc], refine hn.symm.le.trans (add_le_add_right _ _), simpa only [zero_add] using add_le_add (hia.left) (int.mod_lt_of_pos n ha).le, }, { refine lt_of_lt_of_le (add_lt_add_right hi (a * (n/a + 1))) _, rw [mul_add, mul_one, ← add_assoc, hn], }, { rw [int.add_mul_mod_self_left, int.mod_eq_of_lt hia.left hia.right], } }, { refine ⟨i + a * (n/a), ⟨_, _⟩, _⟩, { exact hn.symm.le.trans (add_le_add_right hi _), }, { rw [add_comm n a], refine add_lt_add_of_lt_of_le hia.right (le_trans _ hn.le), simp only [zero_le, le_add_iff_nonneg_left], exact int.mod_nonneg n (ne_of_gt ha), }, { rw [int.add_mul_mod_self_left, int.mod_eq_of_lt hia.left hia.right], } }, end end int
#include <boost/json.hpp> int main() { auto jv = boost::json::parse(R"({"hello": "world"})"); return jv.as_object().at("hello") != "world"; }
[STATEMENT] lemma qtname_declclass_simp[simp]: "declclass (q::qtname) = q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. declclass q = q [PROOF STEP] by (simp add: qtname_declclass_def)
subroutine damping (linnumber) c****************************************************************************** c This subroutine computes damping 'gamma' factors c and then Voigt parameters 'a' c****************************************************************************** implicit real*8 (a-h,o-z) include 'Atmos.com' include 'Linex.com' j = linnumber iwave = int(wave1(j)) iatom10 = nint(10.*atom1(j)) if (dampnum(j) .lt. 0.) dampnum(j) = 10.**dampnum(j) c*****for a few lines, explicit detailed broadening terms have c appeared in the literature, and so do these lines with a c sepaarate subroutine if (itru .eq. 0) then c Ca II if (iatom10 .eq. 201) then if (iwave .eq. 8498 .or. . iwave .eq. 8542 .or. . iwave .eq. 8662 .or. . iwave .eq. 3933) then call trudamp (j) damptype(j) = 'TRUEgam' return endif c CH elseif(iatom10 .eq. 1060) then if (iwave .eq. 3693) then call trudamp (j) damptype(j) = 'TRUEgam' return endif c Ca I elseif (iatom10 .eq. 200) then if (iwave.eq.6717 .or. iwave.eq.6318 . .or. iwave.eq.6343 .or. iwave.eq.6361) then call trudamp (j) damptype(j) = 'TRUEgam' return endif c Ca I autoionization elseif (iatom10 .eq. 200) then if (iwave.eq.6318 .or. . iwave.eq.6343 .or. . iwave.eq.6361) then call trudamp (j) damptype(j) = 'TRUEgam' return endif endif endif c*****here are the calculations to set up the damping; for atomic lines c there are several options: c dampingopt = 0 and dampnum = 0 ---> c c6 = Unsold formula c dampingopt = 0 and dampnum < 10^(-15) ---> c c6 = dampnum c dampingopt = 0 and 10^(-15) < dampnum < 10^(-5) ---> c gamma = dampnum c dampingopt = 0 and dampnum(i) > 10^(-5) ---> c c6 = (Unsold formula)*dampnum c dampingopt = 1 ---> c gammav = gamma_Barklem if possible, c otherwise use dampingopt=0 options c dampingopt = 2 ---> c c6 = c6_Blackwell-group c dampingopt = 3 and dampnum <= 10^(-10) ---> c c6 = c6_NEXTGEN for H I, He I, H2 c dampingopt = 3 and dampnum > 10^(-10) ---> c c6 = (c6_NEXTGEN for H I, He I, H2)*dampnum c for molecular lines (lacking a better idea) ---> c c6 done as in dampingopt = 0 c*****these damping calculations are done at each atmosphere level if (linprintopt .gt. 2) write (nf1out,1001) j, wave1(j) do i=1,ntau ich = nint(charge(j)) v1 = dsqrt(2.1175d8*t(i)*(1.0/amass(j)+1.008)) c*****first calculate an Unsold approximation to gamma_VanderWaals if (atom1(j) .gt. 100.) then ebreakup = 7.0 else ebreakup = chi(j,ich) endif if (e(j,1).ge.ebreakup .or. e(j,2).ge.ebreakup) then unsold = 1.0e-33 else unsold = dabs(1.61d-33*(13.598*charge(j)/(ebreakup - . e(j,1)))**2 - 1.61d-33*(13.598*charge(j)/ . (ebreakup-e(j,2)))**2) endif c*****dampingopt = 0 or c*****dampingopt = 1 and no Barklem data if (dampingopt .eq. 0 .or. . (dampingopt.eq.1 .and. gambark(j).lt.0)) then if (dampnum(j) .eq. 0.0) then damptype(j) = 'UNSLDc6' gammav = 17.0*unsold**0.4*v1**0.6*numdens(1,1,i) elseif (dampnum(j) .lt. 1.0d-15) then damptype(j) = ' MYc6' gammav = 17.0*dampnum(j)**0.4*v1**0.6*numdens(1,1,i) elseif (dampnum(j) .lt. 1.0d-04) then damptype(j) = 'MYgamma' gammav = dampnum(j)*(t(i)/10000.)**0.3*numdens(1,1,i) else damptype(j) = 'MODUNc6' gammav = . 17.0*(unsold*dampnum(j))**0.4*v1**0.6*numdens(1,1,i) endif c*****dampingopt = 1 with extant Barklem data elseif (dampingopt.eq.1 .and. gambark(j).gt.0.) then damptype(j) = 'BKgamma' gammav = . gambark(j)*(t(i)/10000.)**alpbark(j)*numdens(1,1,i) c*****dampingopt = 2 elseif (dampingopt .eq. 2) then damptype(j) = 'BLKWLc6' gammav = 17.0*((1.0 + 0.67*e(j,1))*unsold)**0.4* . v1**0.6*numdens(1,1,i) c*****dampingopt = 3 elseif (dampingopt .eq. 3) then damptype(j) = 'NXTGNc6' if (dampnum(j) .le. 1.0d-10) dampnum(j) = 1.0 c6h = dabs(1.01d-32*(charge(j)**2)* . (13.598/(ebreakup - e(j,1)))**2 - 1.61d-33* . (13.598/(ebreakup-e(j,2)))**2) c6he = dabs((0.204956/0.666793)*1.01d-32* . (charge(j)**2)*(13.598/(ebreakup - . e(j,1)))**2 - 1.61d-33*(13.598/(ebreakup- . e(j,2)))**2) c6ht = dabs((0.806/0.666793)*1.01d-32* . (charge(j)**2)*(13.598/(ebreakup - . e(j,1)))**2 - 1.61d-33*(13.598/(ebreakup- . e(j,2)))**2) gammav = 17.0*v1**0.6*(c6h**0.4*numdens(1,1,i) + . c6he**0.4*numdens(2,1,i) + . c6ht**0.4*numdens(8,1,i))*dampnum(j)**0.4 endif c*****compute radiative broadening either by an approximate formula or c*****the value in Barklem.dat) if (gamrad(j).ne.0.0 .and. dampingopt .eq. 1) then gammar = gamrad(j) else gammar = 2.223d15/wave1(j)**2 endif c*****now Stark broadening (approximate formulae) excdiff = chi(j,nint(charge(j))) - e(j,2) if (excdiff .gt. 0.0 .and. atom1(j).lt.100.) then effn2 = 13.6*charge(j)**2/excdiff else effn2 = 25. endif gammas = 1.0e-8*ne(i)*effn2**2.5 c*****now finish by summing the gammas and computing the Voigt *a* values gammatot = gammar + gammas + gammav a(j,i) = gammatot*wave1(j)*1.0d-8/(12.56636*dopp(j,i)) if (linprintopt .gt. 2) write (nf1out,1002) i, gammar, . gammas, gammav, gammatot, a(j,i) enddo return c*****format statements 1001 format(//' LINE BROADENING PARAMETERS FOR LINE', i4, . ' AT WAVELENGTH ',f8.2/ . ' i',4x,'natural',6x,'Stark',4x,'VdWaals', . 6x,'total',5x,'a(j,i)') 1002 format (i3,1p5e11.3) end
\name{get.current.track.index} \alias{get.current.track.index} \title{ Get current track index } \description{ Get current track index } \usage{ get.current.track.index() } \value{ Simply returns the numeric index for the current track. } \examples{ # There is no example NULL }
(* * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: BSD-2-Clause *) theory ArraysMemInstance imports Arrays CompoundCTypes begin primrec array_tag_n :: "nat \<Rightarrow> ('a::c_type,'b::finite) array typ_info" where atn_base: "array_tag_n 0 = ((empty_typ_info (typ_name (typ_uinfo_t TYPE('a)) @ ''_array_'' @ nat_to_bin_string (CARD('b::finite))))::('a::c_type,'b) array typ_info)" | atn_rec: "array_tag_n (Suc n) = ((ti_typ_combine TYPE('a::c_type) (\<lambda>x. index x n) (\<lambda>x f. update f n x) (replicate n CHR ''1'') (array_tag_n n))::('a,'b::finite) array typ_info)" definition array_tag :: "('a::c_type,'b::finite) array itself \<Rightarrow> ('a,'b) array typ_info" where "array_tag t \<equiv> array_tag_n (CARD('b))" instance array :: (c_type,finite) c_type .. overloading typ_info_array \<equiv> typ_info_t begin definition typ_info_array: "typ_info_array (w::('a::c_type,'b::finite) array itself) \<equiv> array_tag w" end lemma field_names_array_tag_length [rule_format]: "x \<in> set (field_names_list (array_tag_n n)) \<longrightarrow> length x < n" by (induct n) auto lemma replicate_mem_field_names_array_tag [simp]: "replicate n x \<notin> set (field_names_list (array_tag_n n))" by (fastforce dest: field_names_array_tag_length) lemma aggregate_array_tag [simp]: "aggregate (array_tag_n n)" by (cases n; simp) lemma wf_desc_array_tag [simp]: "wf_desc ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info)" by (induct n; simp) (fastforce elim: wf_desc_ti_typ_combine) lemma wf_size_desc_array_tag [simp]: "0 < n \<Longrightarrow> wf_size_desc ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info)" apply(induct n; simp) apply(case_tac "n=0"; simp) apply(rule wf_size_desc_ti_typ_combine) apply simp done lemma g_ind_array_tag_udpate [simp]: "\<lbrakk> n \<le> m; n \<le> CARD('b) \<rbrakk> \<Longrightarrow> g_ind (lf_set ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info) []) (\<lambda>x f. update f m x)" by (induct n; fastforce elim: g_ind_ti_typ_combine) lemma fc_array_tag_udpate [simp]: "\<lbrakk> n \<le> m; n \<le> CARD('b) \<rbrakk> \<Longrightarrow> fu_commutes (update_ti_t ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info)) (\<lambda>x f. update f m x)" by (induct n; fastforce elim: fc_ti_typ_combine simp: fg_cons_def) lemma f_ind_array_tag_udpate [simp]: "\<lbrakk> n \<le> m; m < CARD('b) \<rbrakk> \<Longrightarrow> f_ind (\<lambda>x. index x m) (lf_fd ` lf_set ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info) [])" by (induct n; fastforce elim: f_ind_ti_typ_combine) lemma fa_fu_g_array_tag_udpate [simp]: "\<lbrakk> n \<le> m; m < CARD('b) \<rbrakk> \<Longrightarrow> fa_ind (lf_fd ` lf_set ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info) []) (\<lambda>x f. update f m x)" by (induct n; fastforce elim: fa_ind_ti_typ_combine) lemma wf_fdp_array_tag [simp]: "n \<le> CARD('b) \<Longrightarrow> wf_lf (lf_set ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info) [])" by (induct n; fastforce elim: wf_lf_ti_typ_combine) lemma upd_local_update [simp]: "upd_local (\<lambda>x f. update f n x)" unfolding upd_local_def by (metis update_update) lemma fu_eq_mask_array_tag [simp, rule_format]: "n \<le> CARD('b) \<longrightarrow> (\<forall>m. (\<forall>k v. k < CARD('b) \<longrightarrow> index ((m v)::('a,'b) array) k = (if n \<le> k then index (undefined::('a::mem_type,'b::finite) array) k else index v k)) \<longrightarrow> fu_eq_mask (array_tag_n n) m)" apply(induct n; clarsimp) apply(rule fu_eq_mask_empty_typ_info) apply(clarsimp simp: array_index_eq) apply(rule fu_eq_mask_ti_typ_combine; clarsimp?) apply(drule_tac x="\<lambda>v. update (m v) n (index undefined n)" in spec) apply(erule impE) apply clarsimp apply(case_tac "k=n"; simp) apply(subgoal_tac "\<forall>v bs. m (update v n bs) = update (m v) n bs"; clarsimp) apply(clarsimp simp: array_index_eq) apply(case_tac "i=n"; clarsimp) apply(case_tac "Suc n \<le> i"; clarsimp) apply(clarsimp simp: fg_cons_def) done lemma size_td_array_tag [simp]: "size_td (((array_tag_n n)::('a,'b::finite) array typ_info)) = n * size_of TYPE('a::c_type)" by (induct n; simp add: size_td_lt_ti_typ_combine size_of_def) lemma align_td_array_tag: "0 < n \<Longrightarrow> align_td ((array_tag_n n)::('a,'b::finite) array typ_info) = (align_td (typ_info_t (TYPE('a::c_type))))" by (induct n; clarsimp) (case_tac "n = 0"; clarsimp simp: align_of_def max_def) lemma align_field_array [simp]: "align_field ((array_tag_n n)::('a::mem_type,'b::finite) array typ_info)" by (induct_tac n; clarsimp) (metis align_field_ti_typ_combine align_of_def align_size_of dvd_mult size_td_array_tag) instance array :: (mem_type,finite) mem_type_sans_size apply intro_classes apply(simp_all add: typ_info_array array_tag_def size_of_def norm_bytes_def) apply clarsimp apply(rule fu_eq_mask) apply(simp add: size_of_def) apply(rule fu_eq_mask_array_tag; simp) apply (clarsimp simp: align_of_def typ_info_array array_tag_def align_td_array_tag) apply (metis align_of_def align_size_of dvd_mult size_of_def) done declare atn_base [simp del] declare atn_rec [simp del] lemma size_of_array [simp]: "size_of TYPE(('a,'b::finite) array) = CARD('b) * size_of TYPE('a::c_type)" by (simp add: size_of_def typ_info_array array_tag_def) lemma size_td_array: "size_td (typ_info_t TYPE(('a,'b::finite) array)) = CARD('b) * size_of TYPE('a::c_type)" by (simp add: size_of_def typ_info_array array_tag_def) lemma align_td_array: "2^align_td (typ_info_t TYPE(('a,'b::finite) array)) = align_of TYPE('a::c_type)" by (simp add: align_of_def typ_info_array array_tag_def align_td_array_tag) end
module JuliaZH include("basedocs.jl") end # module
The norm of the zero vector is zero.
Require Import Fiat.BinEncoders.Env.Common.Specs Fiat.BinEncoders.Env.Lib2.FixList. Require Export Coq.Lists.List. Section SteppingList. Context {A : Type}. (* data type *) Context {B : Type}. (* bin type *) Context {P : Type}. (* cache pointer type *) Context {cache : Cache}. Context {transformer : Transformer B}. Variable fuel : nat. Variable A_halt : A. Variable A_halt_dec : forall a, {a = A_halt} + {~ a = A_halt}. Variable A_predicate : A -> Prop. Variable A_encode : A -> CacheEncode -> B * CacheEncode. Variable A_decode : B -> CacheDecode -> A * B * CacheDecode. Variable A_decode_pf : encode_decode_correct cache transformer A_predicate A_encode A_decode. Variable P_predicate : P -> Prop. Variable P_predicate_dec : forall p, {P_predicate p} + {~ P_predicate p}. Variable P_encode : P -> CacheEncode -> B * CacheEncode. Variable P_decode : B -> CacheDecode -> P * B * CacheDecode. Variable P_decode_pf : encode_decode_correct cache transformer P_predicate P_encode P_decode. Variable X_encode : bool -> CacheEncode -> B * CacheEncode. Variable X_decode : B -> CacheDecode -> bool * B * CacheDecode. Variable X_decode_pf : encode_decode_correct cache transformer (fun _ => True) X_encode X_decode. Variable cacheAdd : CacheAdd cache (list A * P). Variable cacheGet : CacheGet cache (list A) P. Variable cachePeek : CachePeek cache P. (*Fixpoint encode_list_step (l : list A) (ce : CacheEncode) : B * CacheEncode := match l with | nil => let (b1, e1) := X_encode false ce in let (b2, e2) := A_encode A_halt e1 in (transform b1 b2, e2) | cons x l' => match getE ce l with | Some position => if P_predicate_dec position then let (b1, e1) := X_encode true ce in let (b2, e2) := P_encode position e1 in (transform b1 b2, e2) else let (b1, e1) := X_encode false ce in let (b2, e2) := A_encode x e1 in let (b3, e3) := encode_list_step l' e2 in (transform (transform b1 b2) b3, addE e3 (l, peekE ce)) | None => let (b1, e1) := X_encode false ce in let (b2, e2) := A_encode x e1 in let (b3, e3) := encode_list_step l' e2 in (transform (transform b1 b2) b3, addE e3 (l, peekE ce)) end end. Fixpoint decode'_list_step (f : nat) (b : B) (cd : CacheDecode) : list A * B * CacheDecode := let (x1, e1) := X_decode b cd in let (br, b1) := x1 in match br with | true => let (x2, e2) := P_decode b1 e1 in let (ps, b2) := x2 in match getD cd ps with | Some l => (l, b2, e2) | None => (nil, b, cd) (* bogus *) end | false => let (x2, e2) := A_decode b1 e1 in let (a, b2) := x2 in if A_halt_dec a then (nil, b2, e2) else match f with | O => (nil, b, cd) (* bogus *) | S f' => let (x3, e3) := decode'_list_step f' b2 e2 in let (l, b3) := x3 in (a :: l, b3, addD e3 (a :: l, peekD cd)) end end. Definition decode_list_step := decode'_list_step fuel. Theorem SteppingList_decode_correct : encode_decode_correct cache transformer (fun ls => A_predicate A_halt /\ |ls| <= fuel /\ (forall x, In x ls -> A_predicate x /\ ~ x = A_halt)) encode_list_step decode_list_step. Proof. unfold encode_decode_correct. intros env env' xenv xenv' l l' bin' ext ext' Eeq [Ppredh [PPredlen PPredA]] Penc Pdec. unfold decode_list_step in *; simpl in *. generalize dependent l'; generalize dependent fuel; clear fuel; generalize dependent env; generalize dependent env'; generalize dependent xenv; generalize dependent bin'; generalize ext; generalize dependent ext'; generalize dependent xenv'; induction l; intros; simpl in *. { destruct (X_encode false env) eqn: ?. destruct (A_encode A_halt c) eqn: ?. inversion Penc; subst; clear Penc. destruct (X_decode (transform (transform b b0) ext0) env') as [[? ?] ?] eqn: ?. rewrite <- transform_assoc in Heqp1. destruct (X_decode_pf _ _ _ _ _ _ _ _ _ Eeq I Heqp Heqp1) as [? [? ?]]; subst. destruct fuel eqn: ?; subst; simpl in *; try rewrite !transform_assoc in Heqp1. { rewrite Heqp1 in Pdec. destruct (A_decode (transform b0 ext0) c0) as [[? ?] ?] eqn: ?. destruct (A_decode_pf _ _ _ _ _ _ _ _ _ H Ppredh Heqp0 Heqp2) as [? [? ?]]; subst. destruct (A_halt_dec a); inversion Pdec; subst; intuition. } { rewrite Heqp1 in Pdec. destruct (A_decode (transform b0 ext0) c0) as [[? ?] ?] eqn: ?. destruct (A_halt_dec a); inversion Pdec; subst; clear Pdec. destruct (A_decode_pf _ _ _ _ _ _ _ _ _ H Ppredh Heqp0 Heqp2) as [? [? ?]]; intuition. destruct (A_decode_pf _ _ _ _ _ _ _ _ _ H Ppredh Heqp0 Heqp2) as [? [? ?]]; congruence. } } { destruct fuel as [| fuel']; try solve [ exfalso; intuition; inversion PPredlen ]. destruct (getE env (a :: l)) eqn: ?. { destruct (P_predicate_dec p). { destruct (X_encode true env) eqn: ?. destruct (P_encode p c) eqn: ?. simpl in *. destruct (X_decode (transform bin' ext0) env') as [[? ?] ?] eqn: ?. destruct (P_decode (transform b0 ext0) c1) as [[? ?] ?] eqn: ?. inversion Penc; subst; clear Penc. rewrite <- transform_assoc in Heqp2. destruct (X_decode_pf _ _ _ _ _ _ _ _ _ Eeq I Heqp1 Heqp2) as [? [? ?]]; subst. destruct (P_decode_pf _ _ _ _ _ _ _ _ _ H p0 Heqp0 Heqp3) as [? [? ?]]; subst. eapply get_correct in Heqo; eauto. rewrite Heqp3, Heqo in Pdec. inversion Pdec; subst; eauto. } { destruct (X_encode false env) eqn: ?. destruct (A_encode a c) eqn: ?. destruct (encode_list_step l c0) eqn: ?. simpl in *. inversion Penc; subst; clear Penc. destruct (X_decode (transform (transform (transform b b0) b1) ext0) env') as [[? ?] ?] eqn: ?. rewrite <- !transform_assoc in Heqp3. destruct (X_decode_pf _ _ _ _ _ _ _ _ _ Eeq I Heqp0 Heqp3) as [? [? ?]]; subst. destruct (A_decode (transform b0 (transform b1 ext0)) c2) as [[? ?] ?] eqn: ?. destruct (A_decode_pf _ _ _ _ _ _ _ _ _ H (proj1 (PPredA _ (or_introl eq_refl))) Heqp1 Heqp4) as [? [? ?]]; subst. destruct (A_halt_dec a0). { inversion Pdec; subst; clear Pdec. exfalso. specialize (PPredA _ (or_introl eq_refl)). intuition congruence. } { destruct (decode'_list_step fuel' (transform b1 ext0) c3) as [[? ?] ?] eqn: ?. inversion Pdec; subst; clear Pdec. destruct (IHl (fun x H => PPredA x (or_intror H)) _ _ _ _ _ _ _ H0 Heqp2 _ (Le.le_S_n _ _ PPredlen) _ Heqp5) as [? [? ?]]; subst. intuition eauto. erewrite peek_correct; eauto. eapply add_correct; eauto. } } } { destruct (X_encode false env) eqn: ?. destruct (A_encode a c) eqn: ?. destruct (encode_list_step l c0) eqn: ?. simpl in *. inversion Penc; subst; clear Penc. destruct (X_decode (transform (transform (transform b b0) b1) ext0) env') as [[? ?] ?] eqn: ?. rewrite <- !transform_assoc in Heqp2. destruct (X_decode_pf _ _ _ _ _ _ _ _ _ Eeq I Heqp Heqp2) as [? [? ?]]; subst. destruct (A_decode (transform b0 (transform b1 ext0)) c2) as [[? ?] ?] eqn: ?. destruct (A_decode_pf _ _ _ _ _ _ _ _ _ H (proj1 (PPredA _ (or_introl eq_refl))) Heqp0 Heqp3) as [? [? ?]]; subst. destruct (A_halt_dec a0). { inversion Pdec; subst; clear Pdec. exfalso. specialize (PPredA _ (or_introl eq_refl)). intuition congruence. } { destruct (decode'_list_step fuel' (transform b1 ext0) c3) as [[? ?] ?] eqn: ?. inversion Pdec; subst; clear Pdec. destruct (IHl (fun x H => PPredA x (or_intror H)) _ _ _ _ _ _ _ H0 Heqp1 _ (Le.le_S_n _ _ PPredlen) _ Heqp4) as [? [? ?]]; subst. intuition eauto. erewrite peek_correct; eauto. eapply add_correct; eauto. } } } Qed. *) End SteppingList.
function Z = projectData(X, U, K) %PROJECTDATA Computes the reduced data representation when projecting only %on to the top k eigenvectors % Z = projectData(X, U, K) computes the projection of % the normalized inputs X into the reduced dimensional space spanned by % the first K columns of U. It returns the projected examples in Z. % % You need to return the following variables correctly. Z = zeros(size(X, 1), K); % ====================== YOUR CODE HERE ====================== % Instructions: Compute the projection of the data using only the top K % eigenvectors in U (first K columns). % For the i-th example X(i,:), the projection on to the k-th % eigenvector is given as follows: % x = X(i, :)'; % projection_k = x' * U(:, k); % Ureduce = U(:, 1:K); for i=1:size(X, 1) z = Ureduce' * X(i, :)'; Z(i, :) = z; end; % ============================================================= end
State Before: R : Type u S : Type v σ : Type u_1 τ : Type u_2 r : R e : ℕ n m : σ s : σ →₀ ℕ inst✝ : CommSemiring R p✝ q p : MvPolynomial σ R f : σ → τ h : Injective f i : σ ⊢ degreeOf (f i) (↑(rename f) p) = degreeOf i p State After: no goals Tactic: classical simp only [degreeOf, degrees_rename_of_injective h, Multiset.count_map_eq_count' f p.degrees h] State Before: R : Type u S : Type v σ : Type u_1 τ : Type u_2 r : R e : ℕ n m : σ s : σ →₀ ℕ inst✝ : CommSemiring R p✝ q p : MvPolynomial σ R f : σ → τ h : Injective f i : σ ⊢ degreeOf (f i) (↑(rename f) p) = degreeOf i p State After: no goals Tactic: simp only [degreeOf, degrees_rename_of_injective h, Multiset.count_map_eq_count' f p.degrees h]
[STATEMENT] lemma SQ_sub_Q: "SQ \<subseteq> Q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. SQ \<subseteq> Q [PROOF STEP] by (auto simp add: SQ_def Q_def)
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.basic /-! # Prefixes, subfixes, infixes This file proves properties about * `list.prefix`: `l₁` is a prefix of `l₂` if `l₂` starts with `l₁`. * `list.subfix`: `l₁` is a subfix of `l₂` if `l₂` ends with `l₁`. * `list.infix`: `l₁` is an infix of `l₂` if `l₁` is a prefix of some subfix of `l₂`. * `list.inits`: The list of prefixes of a list. * `list.tails`: The list of prefixes of a list. * `insert` on lists All those (except `insert`) are defined in `data.list.defs`. ## Notation `l₁ <+: l₂`: `l₁` is a prefix of `l₂`. `l₁ <:+ l₂`: `l₁` is a subfix of `l₂`. `l₁ <:+: l₂`: `l₁` is an infix of `l₂`. -/ open nat variables {α β : Type*} namespace list variables {l l₁ l₂ l₃ : list α} {a b : α} {m n : ℕ} /-! ### prefix, suffix, infix -/ section fix @[simp] lemma prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] lemma suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ lemma infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] lemma infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append lemma is_prefix.is_infix : l₁ <+: l₂ → l₁ <:+: l₂ := λ ⟨t, h⟩, ⟨[], t, h⟩ lemma is_suffix.is_infix : l₁ <:+ l₂ → l₁ <:+: l₂ := λ ⟨t, h⟩, ⟨t, [], by rw [h, append_nil]⟩ lemma nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ lemma nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ lemma nil_infix (l : list α) : [] <:+: l := (nil_prefix _).is_infix @[refl] lemma prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] lemma suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[refl] lemma infix_refl (l : list α) : l <:+: l := (prefix_refl l).is_infix lemma prefix_rfl : l <+: l := prefix_refl _ lemma suffix_rfl : l <:+ l := suffix_refl _ lemma infix_rfl : l <:+: l := infix_refl _ @[simp] lemma suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] lemma prefix_concat (a : α) (l) : l <+: concat l a := by simp lemma infix_cons : l₁ <:+: l₂ → l₁ <:+: a :: l₂ := λ ⟨L₁, L₂, h⟩, ⟨a :: L₁, L₂, h ▸ rfl⟩ lemma infix_concat : l₁ <:+: l₂ → l₁ <:+: concat l₂ a := λ ⟨L₁, L₂, h⟩, ⟨L₁, concat L₂ a, by simp_rw [←h, concat_eq_append, append_assoc]⟩ @[trans] lemma is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] lemma is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] lemma is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ protected lemma is_infix.sublist : l₁ <:+: l₂ → l₁ <+ l₂ := λ ⟨s, t, h⟩, by { rw [← h], exact (sublist_append_right _ _).trans (sublist_append_left _ _) } protected lemma is_prefix.sublist (h : l₁ <+: l₂) : l₁ <+ l₂ := h.is_infix.sublist protected lemma is_suffix.sublist (h : l₁ <:+ l₂) : l₁ <+ l₂ := h.is_infix.sublist @[simp] lemma reverse_suffix : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ @[simp] lemma reverse_prefix : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] alias reverse_prefix ↔ _ list.is_suffix.reverse alias reverse_suffix ↔ _ list.is_prefix.reverse lemma infix.length_le (h : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist h.sublist lemma eq_nil_of_infix_nil (h : l <:+: []) : l = [] := eq_nil_of_sublist_nil h.sublist @[simp] lemma infix_nil_iff : l <:+: [] ↔ l = [] := ⟨λ h, eq_nil_of_sublist_nil h.sublist, λ h, h ▸ infix_rfl⟩ alias infix_nil_iff ↔ list.eq_nil_of_infix_nil _ @[simp] lemma prefix_nil_iff : l <+: [] ↔ l = [] := ⟨λ h, eq_nil_of_infix_nil h.is_infix, λ h, h ▸ prefix_rfl⟩ @[simp] lemma suffix_nil_iff : l <:+ [] ↔ l = [] := ⟨λ h, eq_nil_of_infix_nil h.is_infix, λ h, h ▸ suffix_rfl⟩ alias prefix_nil_iff ↔ list.eq_nil_of_prefix_nil _ alias suffix_nil_iff ↔ list.eq_nil_of_suffix_nil _ lemma infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ ⟨._, ⟨t, rfl⟩, s, e⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ lemma eq_of_infix_of_length_eq (h : l₁ <:+: l₂) : l₁.length = l₂.length → l₁ = l₂ := eq_of_sublist_of_length_eq h.sublist lemma eq_of_prefix_of_length_eq (h : l₁ <+: l₂) : l₁.length = l₂.length → l₁ = l₂ := eq_of_sublist_of_length_eq h.sublist lemma eq_of_suffix_of_length_eq (h : l₁ <:+ l₂) : l₁.length = l₂.length → l₁ = l₂ := eq_of_sublist_of_length_eq h.sublist lemma prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a :: l₁) (b :: l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end lemma prefix_or_prefix_of_prefix (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) lemma suffix_of_suffix_length_le (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) lemma suffix_or_suffix_of_suffix (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 lemma suffix_cons_iff : l₁ <:+ a :: l₂ ↔ l₁ = a :: l₂ ∨ l₁ <:+ l₂ := begin split, { rintro ⟨⟨hd, tl⟩, hl₃⟩, { exact or.inl hl₃ }, { simp only [cons_append] at hl₃, exact or.inr ⟨_, hl₃.2⟩ } }, { rintro (rfl | hl₁), { exact (a :: l₂).suffix_refl }, { exact hl₁.trans (l₂.suffix_cons _) } } end lemma infix_of_mem_join : ∀ {L : list (list α)}, l ∈ L → l <:+: join L | (_ :: L) (or.inl rfl) := infix_append [] _ _ | (l' :: L) (or.inr h) := is_infix.trans (infix_of_mem_join h) $ (suffix_append _ _).is_infix lemma prefix_append_right_inj (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] lemma prefix_cons_inj (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] lemma take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ lemma drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ lemma take_sublist (n) (l : list α) : take n l <+ l := (take_prefix n l).sublist lemma drop_sublist (n) (l : list α) : drop n l <+ l := (drop_suffix n l).sublist lemma take_subset (n) (l : list α) : take n l ⊆ l := (take_sublist n l).subset lemma drop_subset (n) (l : list α) : drop n l ⊆ l := (drop_sublist n l).subset lemma mem_of_mem_take (h : a ∈ l.take n) : a ∈ l := take_subset n l h lemma mem_of_mem_drop (h : a ∈ l.drop n) : a ∈ l := drop_subset n l h lemma init_prefix : ∀ (l : list α), l.init <+: l | [] := ⟨nil, by rw [init, list.append_nil]⟩ | (a :: l) := ⟨_, init_append_last (cons_ne_nil a l)⟩ lemma tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix lemma init_sublist (l : list α) : l.init <+ l := (init_prefix l).sublist lemma prefix_iff_eq_append : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ lemma suffix_iff_eq_append : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, add_tsub_cancel_right, take_left], λ e, ⟨_, e⟩⟩ lemma prefix_iff_eq_take : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ lemma suffix_iff_eq_drop : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a :: l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a :: l₁) (b :: l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a :: l₁) [] := is_false $ mt (length_le_of_sublist ∘ is_suffix.sublist) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ h.sublist lemma prefix_take_le_iff {L : list (list (option α))} (hm : m < L.length) : L.take m <+: L.take n ↔ m ≤ n := begin simp only [prefix_iff_eq_take, length_take], induction m with m IH generalizing L n, { simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] }, cases L with l ls, { exact (not_lt_bot hm).elim }, cases n, { refine iff_of_false _ (zero_lt_succ _).not_le, rw [take_zero, take_nil], simp only [take], exact not_false }, { simp only [length] at hm, specialize @IH ls n (nat.lt_of_succ_lt_succ hm), simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH, simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take], exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } end lemma cons_prefix_iff : a :: l₁ <+: b :: l₂ ↔ a = b ∧ l₁ <+: l₂ := begin split, { rintro ⟨L, hL⟩, simp only [cons_append] at hL, exact ⟨hL.left, ⟨L, hL.right⟩⟩ }, { rintro ⟨rfl, h⟩, rwa [prefix_cons_inj] } end lemma is_prefix.map (h : l₁ <+: l₂) (f : α → β) : l₁.map f <+: l₂.map f := begin induction l₁ with hd tl hl generalizing l₂, { simp only [nil_prefix, map_nil] }, { cases l₂ with hd₂ tl₂, { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, simp only [h, prefix_cons_inj, hl, map] } } end lemma is_prefix.filter_map (h : l₁ <+: l₂) (f : α → option β) : l₁.filter_map f <+: l₂.filter_map f := begin induction l₁ with hd₁ tl₁ hl generalizing l₂, { simp only [nil_prefix, filter_map_nil] }, { cases l₂ with hd₂ tl₂, { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, rw [←@singleton_append _ hd₁ _, ←@singleton_append _ hd₂ _, filter_map_append, filter_map_append, h.left, prefix_append_right_inj], exact hl h.right } } end lemma is_prefix.reduce_option {l₁ l₂ : list (option α)} (h : l₁ <+: l₂) : l₁.reduce_option <+: l₂.reduce_option := h.filter_map id lemma is_prefix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <+: l₂) : l₁.filter p <+: l₂.filter p := begin obtain ⟨xs, rfl⟩ := h, rw filter_append, exact prefix_append _ _ end lemma is_suffix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <:+ l₂) : l₁.filter p <:+ l₂.filter p := begin obtain ⟨xs, rfl⟩ := h, rw filter_append, exact suffix_append _ _ end lemma is_infix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <:+: l₂) : l₁.filter p <:+: l₂.filter p := begin obtain ⟨xs, ys, rfl⟩ := h, rw [filter_append, filter_append], exact infix_append _ _ _ end end fix section inits_tails @[simp] lemma mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λ h, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a :: t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λ o, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λ mi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b :: s), ⟨r, hr⟩ := list.no_confusion hr $ λ ba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] lemma mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λ h, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a :: t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λ o, match s, t, o with | ._, t, or.inl rfl := suffix_rfl | s, ._, or.inr ⟨l, rfl⟩ := ⟨a :: l, rfl⟩ end, λ e, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b :: l, he⟩ := list.no_confusion he (λ ab lt, or.inr ⟨l, lt⟩) end⟩ lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) := by simp lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails := by simp @[simp] lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l) | [] [] := by simp | [] (a :: t) := by simp | (a :: s) t := by simp [inits_append s t] @[simp] lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail | [] [] := by simp | [] (a :: t) := by simp | (a :: s) t := by simp [tails_append s t] -- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'` lemma inits_eq_tails : ∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l) | [] := by simp | (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff] lemma tails_eq_inits : ∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l) | [] := by simp | (a :: l) := by simp [tails_eq_inits l, append_left_inj] lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self] } lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self] } lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self] } lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self] } @[simp] lemma length_tails (l : list α) : length (tails l) = length l + 1 := begin induction l with x l IH, { simp }, { simpa using IH } end @[simp] lemma length_inits (l : list α) : length (inits l) = length l + 1 := by simp [inits_eq_tails] @[simp] lemma nth_le_tails (l : list α) (n : ℕ) (hn : n < length (tails l)) : nth_le (tails l) n hn = l.drop n := begin induction l with x l IH generalizing n, { simp }, { cases n, { simp }, { simpa using IH n _ } } end @[simp] lemma nth_le_inits (l : list α) (n : ℕ) (hn : n < length (inits l)) : nth_le (inits l) n hn = l.take n := begin induction l with x l IH generalizing n, { simp }, { cases n, { simp }, { simpa using IH n _ } } end instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a :: l₁) [] := is_false $ λ ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λ h, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λ t, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λ t, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ end inits_tails /-! ### insert -/ section insert variable [decidable_eq α] @[simp] lemma insert_nil (a : α) : insert a nil = [a] := rfl lemma insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] lemma insert_of_mem (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] lemma insert_of_not_mem (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] lemma mem_insert_iff : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, { simp only [insert_of_not_mem h', mem_cons_iff] } end @[simp] lemma suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] lemma infix_insert (a : α) (l : list α) : l <:+: insert a l := (suffix_insert a l).is_infix lemma sublist_insert (a : α) (l : list α) : l <+ l.insert a := (suffix_insert a l).sublist lemma subset_insert (a : α) (l : list α) : l ⊆ l.insert a := (sublist_insert a l).subset @[simp] lemma mem_insert_self (a : α) (l : list α) : a ∈ l.insert a := mem_insert_iff.2 $ or.inl rfl lemma mem_insert_of_mem (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) lemma eq_or_mem_of_mem_insert (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] lemma length_insert_of_mem (h : a ∈ l) : (insert a l).length = l.length := congr_arg _ $ insert_of_mem h @[simp] lemma length_insert_of_not_mem (h : a ∉ l) : (insert a l).length = l.length + 1 := congr_arg _ $ insert_of_not_mem h end insert end list
[STATEMENT] lemma finite_calM: "finite calM" [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite calM [PROOF STEP] unfolding calM_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. finite {s. s \<subseteq> carrier G \<and> card s = p ^ a} [PROOF STEP] by (rule finite_subset [where B = "Pow (carrier G)"]) auto
From Hammer Require Import Hammer. Require Import DecidableTypeEx. Require Export FSetInterface. Set Implicit Arguments. Unset Strict Implicit. Module WFacts_fun (Import E : DecidableType)(Import M : WSfun E). Notation eq_dec := E.eq_dec. Definition eqb x y := if eq_dec x y then true else false. Section IffSpec. Variable s s' s'' : t. Variable x y z : elt. Lemma In_eq_iff : E.eq x y -> (In x s <-> In y s). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.In_eq_iff". split; apply In_1; auto. Qed. Lemma mem_iff : In x s <-> mem x s = true. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.mem_iff". split; [apply mem_1|apply mem_2]. Qed. Lemma not_mem_iff : ~In x s <-> mem x s = false. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.not_mem_iff". rewrite mem_iff; destruct (mem x s); intuition. Qed. Lemma equal_iff : s[=]s' <-> equal s s' = true. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.equal_iff". split; [apply equal_1|apply equal_2]. Qed. Lemma subset_iff : s[<=]s' <-> subset s s' = true. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.subset_iff". split; [apply subset_1|apply subset_2]. Qed. Lemma empty_iff : In x empty <-> False. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.empty_iff". intuition; apply (empty_1 H). Qed. Lemma is_empty_iff : Empty s <-> is_empty s = true. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.is_empty_iff". split; [apply is_empty_1|apply is_empty_2]. Qed. Lemma singleton_iff : In y (singleton x) <-> E.eq x y. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.singleton_iff". split; [apply singleton_1|apply singleton_2]. Qed. Lemma add_iff : In y (add x s) <-> E.eq x y \/ In y s. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.add_iff". split; [ | destruct 1; [apply add_1|apply add_2]]; auto. destruct (eq_dec x y) as [E|E]; auto. intro H; right; exact (add_3 E H). Qed. Lemma add_neq_iff : ~ E.eq x y -> (In y (add x s) <-> In y s). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.add_neq_iff". split; [apply add_3|apply add_2]; auto. Qed. Lemma remove_iff : In y (remove x s) <-> In y s /\ ~E.eq x y. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.remove_iff". split; [split; [apply remove_3 with x |] | destruct 1; apply remove_2]; auto. intro. apply (remove_1 H0 H). Qed. Lemma remove_neq_iff : ~ E.eq x y -> (In y (remove x s) <-> In y s). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.remove_neq_iff". split; [apply remove_3|apply remove_2]; auto. Qed. Lemma union_iff : In x (union s s') <-> In x s \/ In x s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.union_iff". split; [apply union_1 | destruct 1; [apply union_2|apply union_3]]; auto. Qed. Lemma inter_iff : In x (inter s s') <-> In x s /\ In x s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.inter_iff". split; [split; [apply inter_1 with s' | apply inter_2 with s] | destruct 1; apply inter_3]; auto. Qed. Lemma diff_iff : In x (diff s s') <-> In x s /\ ~ In x s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.diff_iff". split; [split; [apply diff_1 with s' | apply diff_2 with s] | destruct 1; apply diff_3]; auto. Qed. Variable f : elt->bool. Lemma filter_iff : compat_bool E.eq f -> (In x (filter f s) <-> In x s /\ f x = true). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.filter_iff". split; [split; [apply filter_1 with f | apply filter_2 with s] | destruct 1; apply filter_3]; auto. Qed. Lemma for_all_iff : compat_bool E.eq f -> (For_all (fun x => f x = true) s <-> for_all f s = true). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.for_all_iff". split; [apply for_all_1 | apply for_all_2]; auto. Qed. Lemma exists_iff : compat_bool E.eq f -> (Exists (fun x => f x = true) s <-> exists_ f s = true). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.exists_iff". split; [apply exists_1 | apply exists_2]; auto. Qed. Lemma elements_iff : In x s <-> InA E.eq x (elements s). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.elements_iff". split; [apply elements_1 | apply elements_2]. Qed. End IffSpec. Ltac set_iff := repeat (progress ( rewrite add_iff || rewrite remove_iff || rewrite singleton_iff || rewrite union_iff || rewrite inter_iff || rewrite diff_iff || rewrite empty_iff)). Section BoolSpec. Variable s s' s'' : t. Variable x y z : elt. Lemma mem_b : E.eq x y -> mem x s = mem y s. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.mem_b". intros. generalize (mem_iff s x) (mem_iff s y)(In_eq_iff s H). destruct (mem x s); destruct (mem y s); intuition. Qed. Lemma empty_b : mem y empty = false. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.empty_b". generalize (empty_iff y)(mem_iff empty y). destruct (mem y empty); intuition. Qed. Lemma add_b : mem y (add x s) = eqb x y || mem y s. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.add_b". generalize (mem_iff (add x s) y)(mem_iff s y)(add_iff s x y); unfold eqb. destruct (eq_dec x y); destruct (mem y s); destruct (mem y (add x s)); intuition. Qed. Lemma add_neq_b : ~ E.eq x y -> mem y (add x s) = mem y s. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.add_neq_b". intros; generalize (mem_iff (add x s) y)(mem_iff s y)(add_neq_iff s H). destruct (mem y s); destruct (mem y (add x s)); intuition. Qed. Lemma remove_b : mem y (remove x s) = mem y s && negb (eqb x y). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.remove_b". generalize (mem_iff (remove x s) y)(mem_iff s y)(remove_iff s x y); unfold eqb. destruct (eq_dec x y); destruct (mem y s); destruct (mem y (remove x s)); simpl; intuition. Qed. Lemma remove_neq_b : ~ E.eq x y -> mem y (remove x s) = mem y s. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.remove_neq_b". intros; generalize (mem_iff (remove x s) y)(mem_iff s y)(remove_neq_iff s H). destruct (mem y s); destruct (mem y (remove x s)); intuition. Qed. Lemma singleton_b : mem y (singleton x) = eqb x y. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.singleton_b". generalize (mem_iff (singleton x) y)(singleton_iff x y); unfold eqb. destruct (eq_dec x y); destruct (mem y (singleton x)); intuition. Qed. Lemma union_b : mem x (union s s') = mem x s || mem x s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.union_b". generalize (mem_iff (union s s') x)(mem_iff s x)(mem_iff s' x)(union_iff s s' x). destruct (mem x s); destruct (mem x s'); destruct (mem x (union s s')); intuition. Qed. Lemma inter_b : mem x (inter s s') = mem x s && mem x s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.inter_b". generalize (mem_iff (inter s s') x)(mem_iff s x)(mem_iff s' x)(inter_iff s s' x). destruct (mem x s); destruct (mem x s'); destruct (mem x (inter s s')); intuition. Qed. Lemma diff_b : mem x (diff s s') = mem x s && negb (mem x s'). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.diff_b". generalize (mem_iff (diff s s') x)(mem_iff s x)(mem_iff s' x)(diff_iff s s' x). destruct (mem x s); destruct (mem x s'); destruct (mem x (diff s s')); simpl; intuition. Qed. Lemma elements_b : mem x s = existsb (eqb x) (elements s). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.elements_b". generalize (mem_iff s x)(elements_iff s x)(existsb_exists (eqb x) (elements s)). rewrite InA_alt. destruct (mem x s); destruct (existsb (eqb x) (elements s)); auto; intros. symmetry. rewrite H1. destruct H0 as (H0,_). destruct H0 as (a,(Ha1,Ha2)); [ intuition |]. exists a; intuition. unfold eqb; destruct (eq_dec x a); auto. rewrite <- H. rewrite H0. destruct H1 as (H1,_). destruct H1 as (a,(Ha1,Ha2)); [intuition|]. exists a; intuition. unfold eqb in *; destruct (eq_dec x a); auto; discriminate. Qed. Variable f : elt->bool. Lemma filter_b : compat_bool E.eq f -> mem x (filter f s) = mem x s && f x. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.filter_b". intros. generalize (mem_iff (filter f s) x)(mem_iff s x)(filter_iff s x H). destruct (mem x s); destruct (mem x (filter f s)); destruct (f x); simpl; intuition. Qed. Lemma for_all_b : compat_bool E.eq f -> for_all f s = forallb f (elements s). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.for_all_b". intros. generalize (forallb_forall f (elements s))(for_all_iff s H)(elements_iff s). unfold For_all. destruct (forallb f (elements s)); destruct (for_all f s); auto; intros. rewrite <- H1; intros. destruct H0 as (H0,_). rewrite (H2 x0) in H3. rewrite (InA_alt E.eq x0 (elements s)) in H3. destruct H3 as (a,(Ha1,Ha2)). rewrite (H _ _ Ha1). apply H0; auto. symmetry. rewrite H0; intros. destruct H1 as (_,H1). apply H1; auto. rewrite H2. rewrite InA_alt; eauto. Qed. Lemma exists_b : compat_bool E.eq f -> exists_ f s = existsb f (elements s). Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.exists_b". intros. generalize (existsb_exists f (elements s))(exists_iff s H)(elements_iff s). unfold Exists. destruct (existsb f (elements s)); destruct (exists_ f s); auto; intros. rewrite <- H1; intros. destruct H0 as (H0,_). destruct H0 as (a,(Ha1,Ha2)); auto. exists a; split; auto. rewrite H2; rewrite InA_alt; eauto. symmetry. rewrite H0. destruct H1 as (_,H1). destruct H1 as (a,(Ha1,Ha2)); auto. rewrite (H2 a) in Ha1. rewrite (InA_alt E.eq a (elements s)) in Ha1. destruct Ha1 as (b,(Hb1,Hb2)). exists b; auto. rewrite <- (H _ _ Hb1); auto. Qed. End BoolSpec. Instance E_ST : Equivalence E.eq. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.E_ST". constructor ; red; [apply E.eq_refl|apply E.eq_sym|apply E.eq_trans]. Qed. Instance Equal_ST : Equivalence Equal. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.Equal_ST". constructor ; red; [apply eq_refl | apply eq_sym | apply eq_trans]. Qed. Instance In_m : Proper (E.eq ==> Equal ==> iff) In. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.In_m". unfold Equal; intros x y H s s' H0. rewrite (In_eq_iff s H); auto. Qed. Instance is_empty_m : Proper (Equal==> Logic.eq) is_empty. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.is_empty_m". unfold Equal; intros s s' H. generalize (is_empty_iff s)(is_empty_iff s'). destruct (is_empty s); destruct (is_empty s'); unfold Empty; auto; intros. symmetry. rewrite <- H1; intros a Ha. rewrite <- (H a) in Ha. destruct H0 as (_,H0). exact (H0 Logic.eq_refl _ Ha). rewrite <- H0; intros a Ha. rewrite (H a) in Ha. destruct H1 as (_,H1). exact (H1 Logic.eq_refl _ Ha). Qed. Instance Empty_m : Proper (Equal ==> iff) Empty. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.Empty_m". repeat red; intros; do 2 rewrite is_empty_iff; rewrite H; intuition. Qed. Instance mem_m : Proper (E.eq ==> Equal ==> Logic.eq) mem. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.mem_m". unfold Equal; intros x y H s s' H0. generalize (H0 x); clear H0; rewrite (In_eq_iff s' H). generalize (mem_iff s x)(mem_iff s' y). destruct (mem x s); destruct (mem y s'); intuition. Qed. Instance singleton_m : Proper (E.eq ==> Equal) singleton. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.singleton_m". unfold Equal; intros x y H a. do 2 rewrite singleton_iff; split; intros. apply E.eq_trans with x; auto. apply E.eq_trans with y; auto. Qed. Instance add_m : Proper (E.eq==>Equal==>Equal) add. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.add_m". unfold Equal; intros x y H s s' H0 a. do 2 rewrite add_iff; rewrite H; rewrite H0; intuition. Qed. Instance remove_m : Proper (E.eq==>Equal==>Equal) remove. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.remove_m". unfold Equal; intros x y H s s' H0 a. do 2 rewrite remove_iff; rewrite H; rewrite H0; intuition. Qed. Instance union_m : Proper (Equal==>Equal==>Equal) union. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.union_m". unfold Equal; intros s s' H s'' s''' H0 a. do 2 rewrite union_iff; rewrite H; rewrite H0; intuition. Qed. Instance inter_m : Proper (Equal==>Equal==>Equal) inter. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.inter_m". unfold Equal; intros s s' H s'' s''' H0 a. do 2 rewrite inter_iff; rewrite H; rewrite H0; intuition. Qed. Instance diff_m : Proper (Equal==>Equal==>Equal) diff. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.diff_m". unfold Equal; intros s s' H s'' s''' H0 a. do 2 rewrite diff_iff; rewrite H; rewrite H0; intuition. Qed. Instance Subset_m : Proper (Equal==>Equal==>iff) Subset. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.Subset_m". unfold Equal, Subset; firstorder. Qed. Instance subset_m : Proper (Equal ==> Equal ==> Logic.eq) subset. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.subset_m". intros s s' H s'' s''' H0. generalize (subset_iff s s'') (subset_iff s' s'''). destruct (subset s s''); destruct (subset s' s'''); auto; intros. rewrite H in H1; rewrite H0 in H1; intuition. rewrite H in H1; rewrite H0 in H1; intuition. Qed. Instance equal_m : Proper (Equal ==> Equal ==> Logic.eq) equal. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.equal_m". intros s s' H s'' s''' H0. generalize (equal_iff s s'') (equal_iff s' s'''). destruct (equal s s''); destruct (equal s' s'''); auto; intros. rewrite H in H1; rewrite H0 in H1; intuition. rewrite H in H1; rewrite H0 in H1; intuition. Qed. Lemma Subset_refl : forall s, s[<=]s. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.Subset_refl". red; auto. Qed. Lemma Subset_trans : forall s s' s'', s[<=]s'->s'[<=]s''->s[<=]s''. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.Subset_trans". unfold Subset; eauto. Qed. Add Relation t Subset reflexivity proved by Subset_refl transitivity proved by Subset_trans as SubsetSetoid. Instance In_s_m : Morphisms.Proper (E.eq ==> Subset ++> Basics.impl) In | 1. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.In_s_m". simpl_relation. eauto with set. Qed. Add Morphism Empty with signature Subset --> Basics.impl as Empty_s_m. Proof. unfold Subset, Empty, Basics.impl; firstorder. Qed. Add Morphism add with signature E.eq ==> Subset ++> Subset as add_s_m. Proof. unfold Subset; intros x y H s s' H0 a. do 2 rewrite add_iff; rewrite H; intuition. Qed. Add Morphism remove with signature E.eq ==> Subset ++> Subset as remove_s_m. Proof. unfold Subset; intros x y H s s' H0 a. do 2 rewrite remove_iff; rewrite H; intuition. Qed. Add Morphism union with signature Subset ++> Subset ++> Subset as union_s_m. Proof. unfold Equal; intros s s' H s'' s''' H0 a. do 2 rewrite union_iff; intuition. Qed. Add Morphism inter with signature Subset ++> Subset ++> Subset as inter_s_m. Proof. unfold Equal; intros s s' H s'' s''' H0 a. do 2 rewrite inter_iff; intuition. Qed. Add Morphism diff with signature Subset ++> Subset --> Subset as diff_s_m. Proof. unfold Subset; intros s s' H s'' s''' H0 a. do 2 rewrite diff_iff; intuition. Qed. Lemma filter_equal : forall f, compat_bool E.eq f -> forall s s', s[=]s' -> filter f s [=] filter f s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.filter_equal". unfold Equal; intros; repeat rewrite filter_iff; auto; rewrite H0; tauto. Qed. Lemma filter_ext : forall f f', compat_bool E.eq f -> (forall x, f x = f' x) -> forall s s', s[=]s' -> filter f s [=] filter f' s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.filter_ext". intros f f' Hf Hff' s s' Hss' x. do 2 (rewrite filter_iff; auto). rewrite Hff', Hss'; intuition. repeat red; intros; rewrite <- 2 Hff'; auto. Qed. Lemma filter_subset : forall f, compat_bool E.eq f -> forall s s', s[<=]s' -> filter f s [<=] filter f s'. Proof. hammer_hook "FSetFacts" "FSetFacts.WFacts_fun.filter_subset". unfold Subset; intros; rewrite filter_iff in *; intuition. Qed. End WFacts_fun. Module WFacts (M:WS) := WFacts_fun M.E M. Module Facts := WFacts.
# mobrob - A4 Implementieren Sie eine Beacon-Navigation unter Verwendung des Kalman-Filter; benutzen Sie hierfür ebenfalls den differentiellen Roboter. Es wird ein "Kompass" benötigt. Der Kompass liefert einen Winkel relativ zur X-Achse des Welt-KS, die Messung ist verrauscht. Desweiteren muss ein Bildsensor implementiert werden, der Markierungen (Beacons) aus dem Bild detektiert. Die Beacons sind an bekannten Orten im Raum angebracht ($X_{Li}$, $Y_{Li}$). Gemessen wird jeweils der Winkel (Azimuth) relativ zum Rob.-KS für ein zufällig ausgewähltes Beacon, die Winkelmessung ist ebenfalls verrauscht! Da die Identität der Beacons nicht ermittelt werden kann, ist die Verwendung eines "innovation gates" notwendig. Sollte ein Match nicht eindeutig möglich sein, wird die Messung verworfen. ## Ablauf * Der Roboter bewegt sich, aktualisiert Positionsschätzung und deren Kovarianz anhand des Odometriemodells ($X_{k,k−1}$). * Gemessen wird jeweils der Winkel zu einem zufällig ausgewählten Beacon. Der Kalman-Filter aktualisiert die Schätzung ($X_{k,k}$,$C_{k,k}$). * Basisbreite (Abstand der Räder): $b$ * Geschwindigkeiten der Räder: $\mathbf{v} = \left( v_L , v_R\right)^{\text{T}}$ * Zustand (Pose im Weltkoordinatensystem): $\mathbf{X}_k = (x_k , y_k , \theta_k )^\text{T}$ * Zustandsschätzung: $\mathbf{X}_{k,k} \overset{\text{Korrektur(Kalman)}}{\longleftarrow} \mathbf{X}_{k,k-1} \overset{\text{Vorhersage(Odom.-Modell)}}{\longleftarrow} \mathbf{X}_{k-1,k-1}$ * Kovarianz der Positionsschätzung: $\mathbf{C}_{\text{P},k,k}$ ## Beacon-Peilung Messgleichung: Ausgewählt wird Beacon $i$ aus der Karte $\alpha_k^i=\arctan\left({\frac{Y_{Li}-Y_k}{X_{Li}-X_k}}\right)-\theta_k - v_k^\text{P} = h^{\text{P}i}(\mathbf{X}_k,v_k^\text{P})$ mit $v_k^\text{P} \sim \mathcal{N}(0,\sigma_\text{P}^2)$ ## Kompass Messgleichung: $\beta_k = \theta_k + v_k^\text{K} = h^\text{K} (\theta_k , v_k^\text{K})$ mit $v_k^\text{K} \sim \mathcal{N}(0,\sigma_\text{K}^2)$ # Lösung Dies sind die Lösungsschritte der Lokalisation anhand des Kalman-Filters mit Innovation-Gate. ## Odometriegleichung Verfahren nach Euler-Colaz für einen Roboter mit differentialer Lenkung: \begin{align} \mathbf{X}_{k+1} = \begin{pmatrix} X_k\\ Y_k\\ \theta_k \end{pmatrix} + \begin{pmatrix} \frac{s_{Lk} + s_{Rk} }{2} \cos \left( \theta_k + \frac{s_{Rk} -s_{Lk}}{2b}\right)\\ \frac{s_{Lk} + s_{Rk} }{2} \sin \left( \theta_k + \frac{s_{Rk} -s_{Lk}}{2b}\right)\\ \frac{s_{Rk} - s_{Lk} }{b} \end{pmatrix} \text{ mit } s_{Lk}=v_{Lk}\Delta t \text{ und } s_{Rk}=v_{Rk}\Delta t \end{align} Fehlerfortpflanzung der Odometrie: \begin{align} \mathbf{C}_{\text{P},k+1,k} = \mathbf{F}_{\text{P},k+1} \mathbf{C}_{\text{P},k,k} \mathbf{F}_{\text{P},k+1}^{\text{T}} + \underbrace{\mathbf{F}_{\text{S},k+1} \mathbf{C}_{\text{S},k+1} \mathbf{F}_{\text{S},k+1}^{\text{T}}}_{\mathbf{Q}_{k+1}} \end{align} <b>Notiz:</b> $\mathbf{F}_{\text{P},k+1}$ ist die Jacobi-Matrix nach der Position $\mathbf{X}$ im Arbeitspunkt $k+1$ mit $\mathbf{F}_{\text{P},k+1} = \frac{\partial\mathbf{X}_{k+1}}{\partial\mathbf{X}}$ $\mathbf{F}_{\text{S},k+1}$ ist die Jacobi-Matrix nach der Geschwindigkeit $\mathbf{v}$ im Arbeitspunkt $k+1$ mit $\mathbf{F}_{\text{S},k+1} = \frac{\partial\mathbf{X}_{k+1}}{\partial\mathbf{v}}$ $\mathbf{C}_{\text{S},k+1}$ ist die Unsicherheit der zurückgelegten Wegstrecke, welche mit der Geschwindigkeit $\mathbf{v}$ skaliert (Die Konstanten $(k_1,k_2)$ müssen messtechnisch ermittelt werden) mit $\mathbf{C}_{\text{S},k+1}=\text{diag}\left(k_1 \left| s_{Lk+1}\right|, k_2 \left| s_{Rk+1}\right| \right)$ $\mathbf{Q}_{k+1}$ wird als die verkürzte Schreibweise für die Unsicherheit der Wegänderung verwendet, mit $\mathbf{Q}_{k+1} = \mathbf{F}_{\text{S},k+1} \mathbf{C}_{\text{S},k,k} \mathbf{F}_{\text{S},k+1}^{\text{T}}$ ## Sensordaten Einlesen Diese Messgleichungen dienen der Simulation der Messungen zum Zeitpunkt $k+1$. Die Werte, die mit einem $'$ versehen sind, sind demnach <b>ground truth</b> Werte vom Simulator. ### Beacon Messung Sensormesswert wird von einem zufälligen Beacon $i$ unter dem Winkel $\alpha^i_{k+1}$ gemessen eingelesen: \begin{align} &\tilde{z}^\text{P}_{k+1} = \alpha^i_{k+1} = \arctan\left({\frac{Y'_{Li}-Y'_{k+1}}{X'_{Li}-X'_{k+1}}}\right)-\theta'_{k+1} - v_{k+1}^\text{P} = h^{\text{P}i}(\mathbf{X}'_{k+1},v_{k+1}^\text{P}) \end{align} mit $v_{k+1}^\text{P} \sim \mathcal{N}(0,\sigma_\text{P}^2)$. und $i \sim$ Menge aller Beacons. ### Kompass Messung Die Kompassmessung ist eine verrauschte Messung der <b>ground truth</b> Daten. \begin{align} &\tilde{z}^\text{K}_{k+1} = \beta_{k+1} = \theta'_{k+1} + v_{k+1}^\text{K} = h^{\text{K}i}(\mathbf{X}'_{k+1},v_{x+1}^\text{K}) \end{align} mit $v_{k+1}^\text{K} \sim \mathcal{N}(0,\sigma_\text{K}^2)$ ## Berechnung einer Messvorhersage für alle Beacons Hier müssen nun die Hypothesen $\hat{z}_{i,k+1}$ berechnet werden, unter welchem Winkel der Roboter an der Position $\mathbf{X}_{k+1}$ das Beacon $i$ messen kann. \begin{align} \hat{z}_{i,k+1} = \arctan\left({\frac{Y_{Li}-Y_{k+1}}{X_{Li}-X_{k+1}}}\right)-\theta_k = h^{i}(\mathbf{X}_{k+1},0)\\ \end{align} ## Kalman-Gain Der Kalman-Gain wird anhand eines Innovation-Gates berechnet. ### Berechnung der Jakobi-Matrix der Messgleichungen: \begin{align} \mathbf{H}^i_{k+1} = \left. \frac{\partial (h^{\text{P}i}, h^{\text{K}i})^{\text{T}}}{ \partial \mathbf{X} }\right|_{\mathbf{X}_{k+1}} = \left( \begin{matrix} \frac{ Y_{Li}-Y_{k+1} }{(X_{Li}-X_{k+1})^2 + (Y_{Li}-Y_{k+1})^2} & \frac{ X_{Li}-X_{k+1} }{(X_{Li}-X_{k+1})^2 + (Y_{Li}-Y_{k+1})^2} & -1\\ 0 & 0 & 1 \end{matrix} \right) \end{align} \begin{align} \mathbf{V}_{k+1} = \left. \frac{\partial (h^{\text{P}i}, h^{\text{K}i})^{\text{T}}}{ \partial \left( v^{\text{P}}, v^{\text{K}} \right)^{\text{T}} }\right|_{\mathbf{X}_{k+1}} = \left( \begin{matrix} -1 & 0\\ 0 & 1 \end{matrix} \right) \end{align} ### Berechnung der Fehlerfortpflanzung der Messgleichung Angabe der Unsicherheitsmatrix $\mathbf{N}_{k+1}$, welche vom System vorgegeben ist: \begin{align} \mathbf{N}_{k+1} = \mathbf{N} = \left( \begin{matrix} \sigma_{\text{P}}^2 & 0\\ 0 & \sigma_{\text{K}}^2 \end{matrix} \right) = \text{const.} \forall k \end{align} Fehlerfortpflanzung: \begin{align} \mathbf{R}_{k+1} = \mathbf{V}_{k+1} \mathbf{N} \mathbf{V}_{k+1}^{\text{T}} = \left( \begin{matrix} \sigma_{\text{P}}^2 & 0\\ 0 & \sigma_{\text{K}}^2 \end{matrix} \right) = \text{const.} \forall k \end{align} <b>Notiz:</b> Die Unsicherheiten des Rauschens gehen additiv in die Messterme ein. Somit bleibt auch das Rauschen zwischen dem Kompass und der Beacon-Peilung zum einen immer unkorreliert, und zum anderen konstant über die Zeit. ### Innovation Gate Definition der Innovation: \begin{align} \nu_{i,k+1} = \left( \begin{matrix} \nu^{\text{P}}_{i,k+1}\\ \nu^{\text{K}}_{i,k+1} \end{matrix} \right) = \left( \begin{matrix} \tilde{z}^{\text{P}}_{k+1} - \hat{z}_{i,k+1}\\ \tilde{z}^{\text{K}}_{k+1} - \theta_{k+1} \end{matrix} \right) \end{align} Berechnung der Kovarianz der Innovation für das Beacon $i$: \begin{align} \mathbf{C}_{\nu_{i,k+1}} = \mathbf{H}^i_{k+1} \mathbf{C}_{\text{P},k+1,k} \mathbf{H}^{i\text{T}}_{k+1} + \mathbf{R}_{k+1} \end{align} Vergleich der Innovation einer Messgleichung vom Beacon $i$ zu einem festen, definierten Gate-Wert $g$: \begin{align} \nu_{i,k+1}^{\text{T}} \mathbf{C}_{\nu_{i,k+1}}^{-1} \nu_{i,k+1} \le g^2 \end{align} Falls die Gleichung für einen Beacon $i$ wahr ist, so wird dieser der Menge $\mathcal{M}_{k+1}$ hinzugefügt ### Kalman-Gain Falls anhand des Innovation-Gates <b>ein einziger</b> Match $\mathcal{M}_{k+1}$ gefunden wurde, wird der Kalman-Gain berechnet. Wird <b>kein</b> oder <b>mehrer</b> Matches $\mathcal{M}_{k+1}$ gefunden, wird der Kalman-Gain verworfen. \begin{align} \mathbf{K}_{k+1} = \left\lbrace \begin{matrix} \mathbf{C}_{\text{P},k+1,k} \mathbf{H}^{i\text{T}}_{k+1} \mathbf{C}_{\nu_{i,k+1}}^{-1} & \text{falls }|\mathcal{M}_{k+1}| = 1\\ \mathbf{0} & \text{falls }|\mathcal{M}_{k+1}| \neq 1 \end{matrix} \right. \end{align} ## Aktualisierung der Position und Unsicherheit Falls das Matching eines Beacons $i$ anhand des Innovation-Gates erfolgreich war, so wird die Sensormessung beim Update berücksichtigt. Falls es jedoch nicht erfolgreich war, so wird die Messung verworfen und lediglich die Odometrie verwendet. ### Update: Position \begin{align} \mathbf{X}_{k+1,k+1} = \mathbf{X}_{k+1,k} + \mathbf{K}_{k+1} \nu_{i,k+1} \end{align} ### Update: Kovarianz \begin{align} \mathbf{C}_{\text{P},k+1,k+1} = \mathbf{C}_{\text{P},k+1,k} - \mathbf{K}_{k+1} \mathbf{C}_{\nu_{i,k+1}} \mathbf{K}_{k+1}^{\text{T}} \end{align} ## Iteration Setze nun $k+1 \rightarrow k$ und beginne wieder im Odometrieschritt.
State Before: R : Type u_1 A : Type u_2 B : Type ?u.694032 S : Type ?u.694035 inst✝⁵ : CommRing R inst✝⁴ : CommRing A inst✝³ : CommRing B inst✝² : CommRing S inst✝¹ : Algebra R A inst✝ : Algebra R B f : R →+* S x : A hx : IsIntegral R x ⊢ Algebra.adjoin R {x} ≤ integralClosure R A State After: R : Type u_1 A : Type u_2 B : Type ?u.694032 S : Type ?u.694035 inst✝⁵ : CommRing R inst✝⁴ : CommRing A inst✝³ : CommRing B inst✝² : CommRing S inst✝¹ : Algebra R A inst✝ : Algebra R B f : R →+* S x : A hx : IsIntegral R x ⊢ {x} ⊆ ↑(integralClosure R A) Tactic: rw [Algebra.adjoin_le_iff] State Before: R : Type u_1 A : Type u_2 B : Type ?u.694032 S : Type ?u.694035 inst✝⁵ : CommRing R inst✝⁴ : CommRing A inst✝³ : CommRing B inst✝² : CommRing S inst✝¹ : Algebra R A inst✝ : Algebra R B f : R →+* S x : A hx : IsIntegral R x ⊢ {x} ⊆ ↑(integralClosure R A) State After: R : Type u_1 A : Type u_2 B : Type ?u.694032 S : Type ?u.694035 inst✝⁵ : CommRing R inst✝⁴ : CommRing A inst✝³ : CommRing B inst✝² : CommRing S inst✝¹ : Algebra R A inst✝ : Algebra R B f : R →+* S x : A hx : IsIntegral R x ⊢ x ∈ integralClosure R A Tactic: simp only [SetLike.mem_coe, Set.singleton_subset_iff] State Before: R : Type u_1 A : Type u_2 B : Type ?u.694032 S : Type ?u.694035 inst✝⁵ : CommRing R inst✝⁴ : CommRing A inst✝³ : CommRing B inst✝² : CommRing S inst✝¹ : Algebra R A inst✝ : Algebra R B f : R →+* S x : A hx : IsIntegral R x ⊢ x ∈ integralClosure R A State After: no goals Tactic: exact hx
Joy Clark Freda recently became an interpreter, or tour guide, at Stan Hywet, a 65 room Tudor revival manor. The house has been featured on "America's Castles" and most of its furnishings are original. A visit to Stan Hywet is a popular field trip for school groups. Paula Slimak and Sylvia Tennis McCombs recently had dinner with Kurt Schultz. He and his wife just moved to AZ from Las Vegas. Kurt looks great and drives a motorcycle for play. Jim Birney, who lives in Texas was also at the dinner.
from numpy import asarray, arange, meshgrid import numpy as np from matplotlib import pyplot from space_3d import objective def plot2d(bounds:np.array, function, solutions:list=list()): '''A partire da un array che definisce lo spazio, e la funzione da usare, plotta lo spazio 2d''' #campiono lo spazio dato dal range accettato xaxis=arange(bounds[0, 0], bounds[0, 1], 0.1) yaxis=arange(bounds[1, 0], bounds[1, 1], 0.1) #creo il reticolo x, y = meshgrid(xaxis, yaxis) #target results = function(x, y) #plot in 2d, con 50 livelli e jet color pyplot.contourf(x, y, results, levels=50, cmap='jet') if solutions: solutions = asarray(solutions) pyplot.plot(solutions[:, 0], solutions[:, 1], '.-', color='w') pyplot.show() if __name__ == '__main__': #bounds bounds = asarray([[-1.0, 1.0], [-1.0, 1.0]]) print("Bounds e': ", bounds) plot2d(bounds, objective)
module JS.VarArg %default total -- TODO: How to handle vararg functions export data VarArg : Type -> Type where [external]
lemma closure_mono: "S \<subseteq> T \<Longrightarrow> closure S \<subseteq> closure T"
r=358.79 https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7sg6b/media/images/d7sg6b-002/svc:tesseract/full/full/358.79/default.jpg Accept:application/hocr+xml
(* Title: HOL/HOLCF/Library/Bool_Discrete.thy Author: Brian Huffman *) section \<open>Discrete cpo instance for booleans\<close> theory Bool_Discrete imports HOLCF begin text \<open>Discrete cpo instance for \<^typ>\<open>bool\<close>.\<close> instantiation bool :: discrete_cpo begin definition below_bool_def: "(x::bool) \<sqsubseteq> y \<longleftrightarrow> x = y" instance proof qed (rule below_bool_def) end text \<open> TODO: implement a command to automate discrete predomain instances. \<close> instantiation bool :: predomain begin definition "(liftemb :: bool u \<rightarrow> udom u) \<equiv> liftemb oo u_map\<cdot>(\<Lambda> x. Discr x)" definition "(liftprj :: udom u \<rightarrow> bool u) \<equiv> u_map\<cdot>(\<Lambda> y. undiscr y) oo liftprj" definition "liftdefl \<equiv> (\<lambda>(t::bool itself). LIFTDEFL(bool discr))" instance proof show "ep_pair liftemb (liftprj :: udom u \<rightarrow> bool u)" unfolding liftemb_bool_def liftprj_bool_def apply (rule ep_pair_comp) apply (rule ep_pair_u_map) apply (simp add: ep_pair.intro) apply (rule predomain_ep) done show "cast\<cdot>LIFTDEFL(bool) = liftemb oo (liftprj :: udom u \<rightarrow> bool u)" unfolding liftemb_bool_def liftprj_bool_def liftdefl_bool_def apply (simp add: cast_liftdefl cfcomp1 u_map_map) apply (simp add: ID_def [symmetric] u_map_ID) done qed end lemma cont2cont_if [simp, cont2cont]: assumes b: "cont b" and f: "cont f" and g: "cont g" shows "cont (\<lambda>x. if b x then f x else g x)" by (rule cont_apply [OF b cont_discrete_cpo], simp add: f g) lemma cont2cont_eq [simp, cont2cont]: fixes f g :: "'a::cpo \<Rightarrow> 'b::discrete_cpo" assumes f: "cont f" and g: "cont g" shows "cont (\<lambda>x. f x = g x)" apply (rule cont_apply [OF f cont_discrete_cpo]) apply (rule cont_apply [OF g cont_discrete_cpo]) apply (rule cont_const) done end
import Data.List import Data.Strings import Erlang.System.File -- Copied from `System.File`. Testing the indiviudual functions -- like `fGetLine`. This function is not total. -- `readLine` is tested in `erlang/erlang003`. idrisReadFile : HasIO io => String -> io (Either FileError String) idrisReadFile file = do Right h <- openFile file Read | Left err => pure (Left err) Right content <- read [] h | Left err => do closeFile h pure (Left err) closeFile h pure (Right (fastAppend content)) where read : List String -> File -> io (Either FileError (List String)) read acc h = do eof <- fEOF h if eof then pure (Right (reverse acc)) else do Right str <- fGetLine h | Left err => pure (Left err) read (str :: acc) h main : IO () main = do Right ok <- idrisReadFile "test.txt" | Left err => printLn err putStr ok writeFile "testout.txt" "abc\ndef\n" Right ok <- idrisReadFile "testout.txt" | Left err => printLn err putStr ok Right ok <- idrisReadFile "notfound" | Left err => printLn err putStr ok
%\input{head.tex} %\begin{document} \section{Basic Concepts} Most of the following concepts apply to arbitrary groups. \subsection{Groups and Subgroups} \defn{ group, Abelian, conjugate, power, finite, cyclic, subgroup, generate, order, complex product, coset, coset, transversal, p-group. } \prop{ bijective mappings, cyclic groups, subgroup, set-generate, complex product, order of c.p., Lagrange Thm, order of g and G, transversal, complement, Dedekind Identity. } \subsection{Homomorphisms and Normal Subgroups} \defn{ homomorphism, im, ker, epi/mono/endo/iso/automorphism, normal, simple, factor group, subnormal, section. } \prop{ inverse homo, ker is normal, normal iff, natural homo, Homo Thm, Iso Thm*2, subnormal. } \subsection{Automorphisms} \defn{ AutG, InnG, Z(G), characteristic, X-inv, X-homo. } \prop{ cyclic G/Z(G) implies Abelian G, char is trans. } \subsection{Cyclic Groups} \defn{$C_n$} \prop{ subgroups of $\Z$, finite cyclic groups and their subgroups, char, cyclic p-groups, Abelian simple groups. } \subsection{Commutators} \defn{ commutator subgroup, perfect. } \prop{ comu with homo, smallest s.t. Abelian factor, perfect factor, $[x,yz]=[x,z][x,y]^z$, [X,Y] is normal in $<X,Y>$, Three-subgroups Lem. } \subsection{Products of Groups} \defn{ internal/external direct product, central product, internal/external semidirect product, involutions, dihedral group. } \prop{ in/ex iso, on Z(G) G' G/N, on normal N, internal structures $G/\bigcap_i N_i \cong G/N_1\times\cdots\times G/N_n$, prod of normal subgs of relative prime order is direct, on elements, central product on G/Z[G], factorization and product of elements in a semiderict product, dihedral groups are semidirect products. } \subsection{Minimal Normal Subgroups} \defn{ minimal normal subgroups. } \prop{ properties of a min-normal subg, product of min-normal subgs, factorization(structure for Abelian versus uniqueness for non-Abelian). } \subsection{Composition Series} \defn{ refine normal(rep. subnormal)series to chief(esp. composition) series, solvable group, X-section, X-composition series, X-simple. } \prop{ Jordan-Holder Thm. } %%%%%%%%%% below are solutions of exercises %%%%%%%% \begin{exerlist} \exer{hahaha}{jajaja} \end{exerlist} %\end{document}
function dataSize = getSize(MRSIStruct) dataSize = MRSIStruct.sz; end
#################################################################### #################### Project 1: the Bank Marketing Data Set #################### Robert Carausu & Marc Vila, CSI - MEI 2017-2018 #################################################################### set.seed (6046) library(reshape2) library(ggplot2) ## Direct marketing campaigns (phone calls) of a Portuguese banking institution. ## The classification goal is to predict if the client will subscribe a term deposit ## Getting the dataset deposit <- read.table(file="./data/bank.csv", header=TRUE, stringsAsFactors=TRUE, sep=";") # We rename the target variable colnames(deposit)[ncol(deposit)] <- "subscribed" original_data = deposit # We make a copy to compare it later with our pre-processed data # 45211 observations and 17 different variables # (9 categorical: job, marital, education, default, housing, loan, contact, month, poutcome and y) dim(deposit) summary(deposit) # 11.70% of subscribed, so our model sholdn't have a higher error than this # Data is very unbalanced so some models will adjust worse than others sum(deposit$subscribed=="yes")/sum(length(deposit$subscribed))*100 ## Let's have a visual inspection of the continuous variables before pre-processing # Age seems ok # The other variables are highly skewed so we will try to scale and apply log where we can # We can do it for duration, not for balance since it has negative values and we don't want to lose data # pdays can be converted to categorical: "not_contacted" (in previous campaign) and "contacted" d.cont <- melt(deposit[, c("age", "balance", "duration", "campaign", "pdays", "previous")]) ggplot(d.cont, aes(x = value)) + facet_wrap(~variable, scales = "free") + geom_histogram() + theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5)) ## Let's have a visual inspection of the factor variables before pre-processing # They seem ok so we won't be touching these variables d.categ <- melt(deposit, measure.vars=c("job", "marital", "education", "housing", "loan", "contact", "default", "poutcome")) ggplot(d.categ, aes(x = value)) + facet_wrap(~variable, scales = "free") + geom_bar() + theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5)) # This dataset needs a lot of pre-processing ... also it displays a good mixture of categorical and numeric variables # In conclusion LDA/QDA may not the best choice, a good choice may be Logistic Regression. We will test also Naive Bayes and Random Forest and # choose the best model that fits our problem #### PRE-PROCESSING #### #### Fixing skewness and scaling continuous variables # The balance has negative values, so we can only scale it hist(deposit$balance, col='lightskyblue', border='lightskyblue4', xlab='balance', main='balance histogram', density=50) # There are 3766 for negative balance # The only way to fix it is to delete this observations so we choose to leave it as it is since we don't want to lose data sum(deposit$balance<0) deposit$balance = scale(deposit$balance) # Scaled balance hist(scale(deposit$balance), col='lightskyblue', border='lightskyblue4', xlab='balance', main='balance histogram', density=50) # duration, campaign and previous are all skewed, so we apply log and scale hist(deposit$duration, col='lightskyblue', border='lightskyblue4', xlab='duration', main='duration histogram', density=50) deposit$duration = log(deposit$duration+0.001) # +0.001 to avoid -Inf hist(deposit$duration, col='lightskyblue', border='lightskyblue4', xlab='duration', main='duration histogram', density=50) deposit$duration = scale(deposit$duration) hist(deposit$duration, col='lightskyblue', border='lightskyblue4', xlab='duration', main='duration histogram', density=50) # Applying log and scale to campaign and previous has some undesired effects, so we will leave them as they are hist(scale(log(deposit$campaign + 0.001)), col='lightskyblue', border='lightskyblue4', xlab='campaign', main='scale(log(campaign)) histogram', density=50) hist(scale(log(deposit$previous + 0.001)), col='lightskyblue', border='lightskyblue4', xlab='previous', main='scale(log(previous)) histogram', density=50) # pdays has most of values -1 (not contacted previously). # We make a categorical value with "contacted" for pdays!=-1 and "not contacted" previously for pdays=-1 hist(deposit$pdays, col='lightskyblue', border='lightskyblue4', xlab='pdays', main='pdays histogram', density=50) deposit$pdays = cut(deposit$pdays, breaks=c(-Inf, 0.0, Inf), labels=c("not_contacted", "contacted")) table(deposit$pdays) plot(deposit$pdays) #### Fixing "unknown" values # There are 288 subscriptions for unknown job, we leave it as it is since we don't want to delete this data summary(deposit[deposit$job=="unknown",]) # We could change the unknown values to NA (as well as the 0 previous contacts variables), this is useful if we use a Random Forest algorythm, # but since it is not the case we leave it as it is # We plot again after pre-processing d.cont <- melt(deposit[, c("age", "balance", "duration", "campaign", "previous")]) ggplot(d.cont, aes(x = value)) + facet_wrap(~variable, scales = "free") + geom_histogram() + theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5)) # Now pdays is categorical d.categ <- melt(deposit, measure.vars=c("job", "marital", "education", "housing", "loan", "contact", "default", "poutcome", "pdays")) ggplot(d.categ, aes(x = value)) + facet_wrap(~variable, scales = "free") + geom_bar() + theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5)) library(caret) library(MASS) library(e1071) library(randomForest) # PREPARING THE TRAINING AND TEST DATA ## Since we want to use different methods, we need CV and a separate test set: N <- nrow(deposit) all.indexes <- 1:N learn.indexes <- sample(1:N, round(2*N/3)) test.indexes <- all.indexes[-learn.indexes] learn.data <- deposit[learn.indexes,] original.learn.data <- original_data[learn.indexes,] test.data <- deposit[test.indexes,] original.test.data <- original_data[test.indexes,] nlearn <- length(learn.indexes) ntest <- N - nlearn #### MODELLING #### ############ LOGISTIC REGRESSION ########## # We use Logistic Regression as recommended since it doesn't need a lot of preprocessing of the data and we also have a lot of categorical variables # ORIGINAL DATA # First aproximation with the original unchanged data & all variables glm.fit = glm(subscribed~., data=original.learn.data, family="binomial") # Observing the p-values, we can have an idea of the variables that have more importance in predicting our model, # a low p-value indicates that we can reject the null hipotesis, thus that variable has an importance on our model, # a higher p-value means that we can discard that variable # so we can fit the mode again with just the variable that actually have an influence on our model # We can discard the following since they affect our model less: age, job, marital, default, balance, pdays and previous summary(glm.fit) # We calculate the prediction with and without the discarded variables and compare the errors glm.probs = predict(glm.fit, original.test.data, type="response") glm.pred = rep("no", length(glm.probs)) glm.pred[glm.probs>.5] = "yes" # We choose 3 values to represent our model performance: accuracy, error and precision, the last one is important # because the bank wants to contact only those clients that are more probable to subscribe to the loan # We can see that accuracy is high (90.07 %), but precission is low (34.15%), to solve this we lower the threshold # for which a client may subscribe a loan (the probability) compare the values again, since for the bank clients # with 30% probability of subscribing is probably worth to spend it's ressources contacting them res.performance = table(glm.pred, original.test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 # Accuracy is slightly lower (90.03%) but precission has almost doubled (53.78%) glm.pred[glm.probs>.3] = "yes" res.performance = table(glm.pred, original.test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 # Now we fit the model without the variables that had less of an impact glm.fit = glm(subscribed~.-age-job-marital-default-balance-pdays-previous, data=original.learn.data, family="binomial") glm.probs = predict(glm.fit, original.test.data, type="response") glm.pred = rep("no", length(glm.probs)) # The total accuracy decreases to 89.93% and precission to 53.32%, so using less variables makes our model a bit less accurate # but the difference is really small so it's not really important to discard those variables # If we have too many variables and computation time is important, # we can also see that removing the ones we selected won't affect so much our model prediction glm.pred[glm.probs>.3] = "yes" res.performance = table(glm.pred, original.test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 # PREPROCESSED DATA # We will fit with all the variables and also removing the ones that we mentioned before glm.fit = glm(subscribed~., data=learn.data, family="binomial") glm.probs = predict(glm.fit, test.data, type="response") glm.pred = rep("no", length(glm.probs)) # Accuracy is 89.40% and precission is 57.95%, so our model is much more precise detecting clients # that will probably buy the finantial product of the bank with the preprocessed data glm.pred[glm.probs>.3] = "yes" res.performance = table(glm.pred, original.test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 # Now we fit the model without the variables that had less of an impact glm.fit = glm(subscribed~.-age-job-marital-default-balance-pdays-previous, data=learn.data, family="binomial") glm.probs = predict(glm.fit, test.data, type="response") glm.pred = rep("no", length(glm.probs)) # Accuracy: 89.47%, precision: 57.44% # As before, there is a small reduction in accuracy and precision but the results with preprocessed data are better glm.pred[glm.probs>.3] = "yes" res.performance = table(glm.pred, original.test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 #### To get a better grasp at the performance of our model, we do k-fold cross validation precision <- NULL accuracy <- NULL error <- NULL k <- 100 # It may take a while to compute for (i in 1:k) { N <- nrow(deposit) all.indexes <- 1:N # we choose 9/10s of the data as training data and the rest as test data learn.indexes <- sample(1:N, round(9*N/10)) test.indexes <- all.indexes[-learn.indexes] learn.data <- deposit[learn.indexes,] test.data <- deposit[test.indexes,] nlearn <- length(learn.indexes) ntest <- N - nlearn glm.fit = glm(subscribed ~ ., data=learn.data, family="binomial") #glm.fit = glm(subscribed ~ .-age-job-marital-default-balance-pdays-previous, data=learn.data, family="binomial") glm.probs = predict(glm.fit, test.data, type="response") glm.pred = rep("no", length(glm.probs)) glm.pred[glm.probs>.3] = "yes" res.performance = table(glm.pred, test.data$subscribed) accuracy[i] <- (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 error[i] <- 100 - accuracy[i] precision[i] <- (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 } # We can see that our model performs pretty well, even though the data is highly unbalanced # Mean values with all the variables # accuracy: 89.69% # error: 10.31% # precision: 58.80 % # Mean values without the variables that influence less our model (swap the commented code in the previous bucle) # accuracy: 89.74% # error: 10.26% # precision: 58.37 % mean(accuracy) mean(error) mean(precision) par(mfrow=c(1,3)) hist(accuracy, col='lightskyblue', border='lightskyblue4', xlab='Acuracy', main='Acuracy for CV', density=50) hist(error, col='lightskyblue', border='lightskyblue4', xlab='Error', main='Error for CV', density=50) hist(precision, col='lightskyblue', border='lightskyblue4', xlab='Precision', main='Precision for CV', density=50) boxplot(accuracy, horizontal=T, col='lightskyblue', border='lightskyblue4', xlab='Acuracy', main='Acuracy for CV') boxplot(error, horizontal=T, col='lightskyblue', border='lightskyblue4', xlab='Error', main='Error for CV') boxplot(precision, horizontal=T, col='lightskyblue', border='lightskyblue4', xlab='Precision', main='Precision for CV') dev.off() # To compare the performance of our model we will also model with LDA and QDA and analyze their performances. # Also we will test NaiveBayes and RandomForest N <- nrow(deposit) all.indexes <- 1:N learn.indexes <- sample(1:N, round(2*N/3)) test.indexes <- all.indexes[-learn.indexes] learn.data <- deposit[learn.indexes,] test.data <- deposit[test.indexes,] nlearn <- length(learn.indexes) ntest <- N - nlearn #################### LDA ################## # With LDA the precision is much lower, so we won't be using this model # 10.73% error, 89.27% accuracy, 28.51% precision lda.fit = lda(subscribed ~ ., data=learn.data) lda.pred = predict(lda.fit, test.data) lda.class = lda.pred$class res.performance = table(lda.class, test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 #################### QDA ################## # Performs worse than LDA, but the precision is a bit higher so it detects better the subscriptions # We confirm that both LDA and QDA are not suitable models to fit our problem # 13.43% error, 86.57% accuracy, 37.99% precision qda.fit <- qda(subscribed ~ ., data=learn.data) qda.pred = predict(qda.fit, test.data) qda.class = qda.pred$class res.performance = table(qda.class, test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 ################# NAIVE BAYES ################## # It performs better than LDA and QDA, but worse than logistic regression # 12.57% error, 87.43% accuracy, 43.89% precision bayes.fit <- naiveBayes(subscribed ~ ., data = learn.data) bayes.pred <- predict(bayes.fit, test.data) res.performance = table(bayes.pred, test.data$subscribed) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 #################### Random Forest ################## # 9.30% error, 90.70% accuracy, 64.66% precision, so far the best method rf <- randomForest(subscribed ~ ., data = original_data[learn.indexes,], ntree=300, proximity=FALSE) rf.pred <- predict(rf, newdata=original_data[-learn.indexes,]) res.performance = table(Truth=original_data[-learn.indexes,]$subscribe,Pred=rf.pred) res.accuracy = (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 res.error = 100 - res.accuracy res.precision = (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 #### As with logistic regresion we do k-fold CV to confirm our model accuracy and precision # We choose k=10 since randomForest has a high computation time precision <- NULL accuracy <- NULL error <- NULL k <- 10 # It may take quite a while to compute for (i in 1:k) { N <- nrow(deposit) all.indexes <- 1:N # we choose 9/10s of the data as training data and the rest as test data learn.indexes <- sample(1:N, round(9*N/10)) test.indexes <- all.indexes[-learn.indexes] nlearn <- length(learn.indexes) ntest <- N - nlearn #glm.fit = glm(subscribed ~ ., data=learn.data, family="binomial") rf <- randomForest(subscribed ~ ., data = original_data[learn.indexes,], ntree=300, proximity=FALSE) rf.pred <- predict(rf, newdata=original_data[-learn.indexes,]) res.performance = table(Truth=original_data[-learn.indexes,]$subscribe,Pred=rf.pred) accuracy[i] <- (res.performance[2,2] + res.performance[1,1])/sum(res.performance)*100 error[i] <- 100 - accuracy[i] precision[i] <- (res.performance[2,2])/(res.performance[2,2] + res.performance[1,2])*100 } # Mean values # accuracy: 90.83% # error: 9.17 % # precision: 64.66% mean(accuracy) mean(error) mean(precision) par(mfrow=c(1,3)) hist(accuracy, col='lightskyblue', border='lightskyblue4', xlab='Acuracy', main='Acuracy for CV', density=50) hist(error, col='lightskyblue', border='lightskyblue4', xlab='Error', main='Error for CV', density=50) hist(precision, col='lightskyblue', border='lightskyblue4', xlab='Precision', main='Precision for CV', density=50) boxplot(accuracy, horizontal=T, col='lightskyblue', border='lightskyblue4', xlab='Acuracy', main='Acuracy for CV') boxplot(error, horizontal=T, col='lightskyblue', border='lightskyblue4', xlab='Error', main='Error for CV') boxplot(precision, horizontal=T, col='lightskyblue', border='lightskyblue4', xlab='Precision', main='Precision for CV') dev.off() # To conclude, random forest is the best method, followed by logistic regression, according to the results
module Kan import Control.Monad.Identity import Data.Morphisms data Ran : (f : Type -> Type) -> (g : Type -> Type) -> (a : Type) -> Type where R : ({b : Type} -> (a -> f b) -> g b) -> Ran f g a data Lan : (f : Type -> Type) -> (g : Type -> Type) -> (a : Type) -> Type where L : (f b -> a) -> g b -> Lan f g a Functor (Ran f g) where map f ran = R (\k => let (R f') = ran in f' (k . f)) Functor (Lan f g) where map f (L g h) = L (f . g) h Yoneda : (Type -> Type) -> Type -> Type Yoneda f a = Ran Identity f a CoYoneda : (Type -> Type) -> Type -> Type CoYoneda f a = Lan Identity f a Codensity : (Type -> Type) -> Type -> Type Codensity m a = Ran m m a Reducer : Type -> Type Reducer a = Ran Endomorphism Endomorphism a
%hint mycong : (f : a -> b) -> x = y -> f x = f y mycong f Refl = Refl plusZ : (n : Nat) -> plus n Z = n plusS : (n : Nat) -> (m : Nat) -> plus n (S m) = S (plus n m)
C ********************************************************* C * * C * TEST NUMBER: 04.02.03.03/06 * C * TEST TITLE : Appearance of text extent rectangle * C * * C * PHIGS Validation Tests, produced by NIST * C * * C ********************************************************* COMMON /GLOBNU/ CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT, DUMRL INTEGER CTLHND, ERRSIG, ERRFIL, IERRCT, UNERR, 1 TESTCT, IFLERR, PASSSW, ERRSW, MAXLIN, 2 CONID, MEMUN, WKID, WTYPE, GLBLUN, INDLUN, 3 DUMINT(20), ERRIND REAL DUMRL(20) COMMON /GLOBCH/ PIDENT, GLBERR, TSTMSG, FUNCID, 1 DUMCH CHARACTER PIDENT*40, GLBERR*60, TSTMSG*900, FUNCID*80, 1 DUMCH(20)*20 COMMON /DIALOG/ DOUTYP, DINTYP, DSTDNR, DSTRID, PSTRID, DTCLIM, 1 SCRMOD, DTXCI, SPECWT, 2 DSIZE, EFRAC, DYXRAT, SYXRAT, MTRPDC, WCPDC, QVIS INTEGER DOUTYP, DINTYP, DSTDNR, DSTRID, PSTRID, DTCLIM, 1 SCRMOD, DTXCI, SPECWT REAL DSIZE, EFRAC, DYXRAT, SYXRAT, MTRPDC, WCPDC, QVIS C aspect source C bundled individual INTEGER PBUNDL, PINDIV PARAMETER (PBUNDL = 0, PINDIV = 1) C composition type C preconcatenate postconcatenate replace INTEGER PCPRE, PCPOST, PCREPL PARAMETER (PCPRE = 0, PCPOST = 1, PCREPL = 2) C linetype INTEGER PLSOLI, PLDASH, PLDOT, PLDASD PARAMETER (PLSOLI = 1, PLDASH = 2, PLDOT = 3, PLDASD = 4) C text alignment horizontal INTEGER PAHNOR, PALEFT, PACENT, PARITE PARAMETER (PAHNOR = 0, PALEFT = 1, PACENT = 2, PARITE = 3) C text alignment vertical INTEGER PAVNOR, PATOP, PACAP, PAHALF, 1 PABASE, PABOTT PARAMETER (PAVNOR = 0, PATOP = 1, PACAP = 2, PAHALF = 3, 1 PABASE = 4, PABOTT = 5) C text path INTEGER PRIGHT, PLEFT, PUP, PDOWN PARAMETER (PRIGHT = 0, PLEFT = 1, PUP = 2, PDOWN = 3) C text precision INTEGER PSTRP, PCHARP, PSTRKP PARAMETER (PSTRP = 0, PCHARP = 1, PSTRKP = 2) INTEGER PICSTR, TXCI, IX, FONT, TXP, TXALH,TXALV INTEGER TXPLEN, NUMREC, RNDINT, NGREC, DTXALH,DTXALV INTEGER LNALGN(PACAP:PABASE), SLEN,SHALF REAL RNDRL, CHHT,CHXP,CHSP, TX(2),TY(2), CCPX,CCPY, XF(3,3) REAL XL,XH,XC, YL,YH,YC, VALOC(PACAP:PABASE), XA(5),YA(5) REAL NPCX,NPCY,NPCPWC, Z,U, XYINCR, YTOP, XLEFT, DSTORT PARAMETER (Z = 0.0, U = 1.0, DSTORT = 0.15) REAL RDUM1,RDUM2, HDST,VDST CHARACTER TESTR*14, TESTV*10, TESTC*12 CHARACTER NAMTXP*5, LBL*2 LOGICAL HORIZ C linetypes for various vertical alignments DATA LNALGN / PLDOT, PLDASD, PLDASH / CALL INITGL ('04.02.03.03/06') C open PHIGS CALL XPOPPH (ERRFIL, MEMUN) C set-up of workstation and dialogue area PICSTR = 101 TXCI = 1 C Establish specwt = specific primary workstation type CALL SETDLG (PICSTR, 801,TXCI) CALL WCNPC (0.0, 0.0, NPCX,NPCY, NPCPWC) CALL POPST (PICSTR) C by convention, view #1 is for picture CALL PSVWI (1) C use individual attributes CALL SETASF (PINDIV) C Message to operator CALL OPMSGW ('The tests in this program require careful ' // 1 'visual inspection. If you are not familiar ' // 1 'with the requirements for text extent and ' // 1 'alignment, please see the OPERATOR SCRIPT in ' // 1 'the documentation for this program.') TESTR = 'Phigs...rules!' TESTV = 'UPPER CASE' TESTC = 'HXHXHXHXHXHX' C global attributes C font (ASCII, possibly non-monospaced) FONT = 2 CALL PSTXFN (FONT) CALL PSTXPR (PSTRKP) C default alignment DTXALH = PACENT DTXALV = PATOP CALL PSTXAL (DTXALH,DTXALV) CALL PSPLCI (2) CALL PSTXCI (1) CALL PSLWSC (0.0) CALL PSATAL (PACENT,PAHALF) CALL PSATCH (0.035 * NPCPWC) CALL PEXST (102) CALL PCLST CALL POPST (102) C numrec = number of text extent rectangles per screen NUMREC = 6 XYINCR = 1.0 / (NUMREC+1) YTOP = 1 - XYINCR XLEFT = XYINCR C for all text paths, txp = RIGHT,LEFT,UP,DOWN DO 100 TXP = PRIGHT,PDOWN IF (TXP.EQ.PRIGHT) THEN HORIZ = .TRUE. NAMTXP = 'RIGHT' TXPLEN = 5 ELSEIF (TXP.EQ.PLEFT) THEN HORIZ = .TRUE. NAMTXP = 'LEFT' TXPLEN = 4 ELSEIF (TXP.EQ.PUP) THEN HORIZ = .FALSE. NAMTXP = 'UP' TXPLEN = 2 ELSE HORIZ = .FALSE. NAMTXP = 'DOWN' TXPLEN = 4 ENDIF XL = 0.2 XH = 0.9 YL = 0.1 YH = 0.8 XC = 0.1 YC = 0.9 C *** *** *** *** *** text extent rectangle *** *** *** *** *** C incorrect entry NGREC = RNDINT(1,NUMREC) C set text path CALL PSTXP (TXP) IF (HORIZ) THEN SLEN = 14 ELSE SLEN = 5 ENDIF C draw and label text extent rectangles, with text DO 200 IX = 1,NUMREC C chht,chxp,chsp = some random values for character height, C expansion factor, and spacing CHHT = 10.0 ** RNDRL(-2.0, 2.0) CHXP = 10.0 ** RNDRL(-1.0, 1.0) IF (IX .LE. 2) THEN CHSP = RNDRL(-3.0, -2.0) ELSE CHSP = RNDRL(-0.2, 3.0) ENDIF IF (HORIZ) THEN YC = YTOP - (IX-1)*XYINCR YL = YC - 0.25*XYINCR YH = YC + 0.25*XYINCR CHSP = CHSP*CHXP ELSE XC = XLEFT + (IX-1)*XYINCR XL = XC - 0.25*XYINCR XH = XC + 0.25*XYINCR ENDIF CALL DRWREC (XL,XH, YL,YH) WRITE (LBL, '(I1,A)') IX, ':' CALL PSCHXP (0.8) CALL PSCHSP (0.0) CALL PATR (XC,YC, Z,Z, LBL) CALL PSCHH (CHHT) CALL PSCHXP (CHXP) CALL PSCHSP (CHSP) C determine actual rectangle: CALL PQTXX (SPECWT,FONT, CHXP,CHSP,CHHT, TXP, DTXALH,DTXALV, 1 TESTR(:SLEN), ERRIND, TX,TY, CCPX,CCPY) CALL CHKINQ ('pqtxx',ERRIND) C apply scale and shift transformation to put testr in next C text extent rectangle CALL PBLTM (TX(1),TY(1), XL-TX(1),YL-TY(1), Z, 1 (XH-XL)/(TX(2)-TX(1)), (YH-YL)/(TY(2)-TY(1)), 2 ERRIND, XF) CALL CHKINQ ('pbltm', ERRIND) CALL PSLMT (XF, PCREPL) IF (IX .EQ. NGREC) THEN C apply additional distorting transformation CALL PTR (DSTORT*XYINCR, -DSTORT*XYINCR, ERRIND, XF) CALL CHKINQ ('ptr', ERRIND) CALL PSLMT (XF, PCPOST) ENDIF CALL PTX (Z,Z, TESTR(:SLEN)) C restore identity local transformation CALL IDMAT (3, XF) CALL PSLMT (XF, PCREPL) 200 CONTINUE CALL SETMSG ('2 6 7 8 10 15 16', '<Inquire text extent> ' // 1 'should accurately report the size and ' // 2 'position of text primitives when text path = ' // 3 NAMTXP(:TXPLEN) // '.') CALL DCHPFV ('ACCURACY OF TEXT EXTENT: Which rectangle ' // 1 'does NOT properly enclose a text primitive?', 2 NUMREC, NGREC) CALL PEMST (102) C *** *** *** *** *** vertical alignment *** *** *** *** *** C incorrect entry NGREC = RNDINT(1,NUMREC) C set text path CALL PSTXP (TXP) IF (HORIZ) THEN SLEN = 10 ELSE SLEN = 5 ENDIF C draw and label vertical alignments with text DO 300 IX = 1,NUMREC C chht,chxp,chsp = some random values for character height, C expansion factor, and spacing CHHT = 10.0 ** RNDRL(-2.0, 2.0) CHXP = 10.0 ** RNDRL(-1.0, 1.0) CHSP = RNDRL(-0.2, 2.0) IF (HORIZ) THEN YC = YTOP - (IX-1)*XYINCR YL = YC - 0.35*XYINCR YH = YC + 0.35*XYINCR CHSP = CHSP*CHXP ELSE XC = XLEFT + (IX-1)*XYINCR XL = XC - 0.25*XYINCR XH = XC + 0.25*XYINCR ENDIF WRITE (LBL, '(I1,A)') IX, ':' CALL PSCHXP (0.8) CALL PSCHSP (0.0) CALL PATR (XC,YC, Z,Z, LBL) CALL PSCHH (CHHT) CALL PSCHXP (CHXP) CALL PSCHSP (CHSP) C for txalv = TOP,CAP,HALF,BASE DO 350 TXALV = PATOP,PABASE CALL PQTXX (SPECWT,FONT, CHXP,CHSP,CHHT, TXP, 1 DTXALH,TXALV, TESTV(:SLEN), 2 ERRIND, TX,TY,CCPX,CCPY) CALL CHKINQ ('pqtxx',ERRIND) IF (TXALV .EQ. PATOP) THEN C apply scale and shift transformation to put testv in next C text extent rectangle CALL PBLTM (TX(1),TY(1), XL-TX(1),YL-TY(1), Z, 1 (XH-XL)/(TX(2)-TX(1)), (YH-YL)/(TY(2)-TY(1)), 2 ERRIND, XF) CALL CHKINQ ('pbltm', ERRIND) CALL PSLMT (XF, PCREPL) XA(1) = TX(1) XA(2) = TX(2) ELSE C determine location of capline,halfline,baseline VALOC(TXALV) = TY(2) ENDIF C next txalv 350 CONTINUE C draw expected capline,halfline,baseline DO 380 TXALV = PACAP,PABASE YA(1) = -VALOC(TXALV) YA(2) = YA(1) CALL PSLN (LNALGN(TXALV)) CALL PPL (2, XA,YA) 380 CONTINUE IF (IX .EQ. NGREC) THEN C apply additional distorting transformation CALL PTR (Z, (RNDINT(0,1)*2-1) * DSTORT*XYINCR, 1 ERRIND, XF) CALL CHKINQ ('ptr', ERRIND) CALL PSLMT (XF, PCPOST) ENDIF CALL PTX (Z,Z, TESTV(:SLEN)) C restore identity local transformation CALL IDMAT (3, XF) CALL PSLMT (XF, PCREPL) 300 CONTINUE CALL SETMSG ('2 6 7 8 10 11', '<Inquire text extent> ' // 1 'should accurately report the vertical ' // 2 'alignment values for text primitives when ' // 3 'text path = ' // NAMTXP(:TXPLEN) // '.') CALL DCHPFV ('ACCURACY OF VERTICAL ALIGNMENTS: Which ' // 1 'text primitive does NOT have a properly ' // 1 'aligned capline (dotted), halfline ' // 1 '(dashed-dotted), or baseline (dashed)?', 1 NUMREC, NGREC) CALL PEMST (102) C *** *** *** *** *** concatenation point *** *** *** *** *** C incorrect entry NGREC = RNDINT(1,NUMREC) C set text path CALL PSTXP (TXP) TXALH = PAHNOR TXALV = PAVNOR HDST = Z VDST = Z IF (HORIZ) THEN SLEN = 12 TXALV = PAHALF HDST = (RNDINT(0,1) - 0.5) * 3 ELSE SLEN = 6 TXALH = PARITE VDST = (RNDINT(0,1) - 0.5) * 4 ENDIF CALL PSTXAL (TXALH,TXALV) C draw and label concatenated text DO 400 IX = 1,NUMREC C chht,chxp,chsp = some random values for character height, C expansion factor, and spacing CHHT = 10.0 ** RNDRL(-2.0, 2.0) CHXP = 10.0 ** RNDRL(-1.0, 1.0) CHSP = RNDRL(0.8, 1.5) IF (HORIZ) THEN YC = YTOP - (IX-1)*XYINCR YL = YC - 0.35*XYINCR YH = YC + 0.35*XYINCR SHALF = RNDINT(3,9) IF (IX.GT.3) CHSP = RNDRL(-0.3, -0.1) CHSP = CHSP*CHXP ELSE XC = XLEFT + (IX-1)*XYINCR XL = XC - 0.25*XYINCR XH = XC + 0.25*XYINCR SHALF = RNDINT(2,4) IF (IX.GT.3) CHSP = RNDRL(-0.8, -0.3) ENDIF WRITE (LBL, '(I1,A)') IX, ':' CALL PSCHXP (0.8) CALL PSCHSP (0.0) CALL PATR (XC,YC, Z,Z, LBL) CALL PSCHH (CHHT) CALL PSCHXP (CHXP) CALL PSCHSP (CHSP) C determine text extent rectangle CALL PQTXX (SPECWT,FONT, CHXP,CHSP,CHHT, TXP, TXALH,TXALV, 1 TESTC(:SLEN), ERRIND, TX,TY, RDUM1,RDUM2) CALL CHKINQ ('pqtxx',ERRIND) C apply scale and shift transformation to put testr1 in next C labelled location CALL PBLTM (TX(1),TY(1), XL-TX(1),YL-TY(1), Z, 1 (XH-XL)/(TX(2)-TX(1)), (YH-YL)/(TY(2)-TY(1)), 2 ERRIND, XF) CALL CHKINQ ('pbltm', ERRIND) CALL PSLMT (XF, PCREPL) CALL PTX (Z,Z, TESTC(:SHALF)) IF (IX .EQ. NGREC) THEN C apply additional distorting transformation CALL PTR (HDST*DSTORT*XYINCR, VDST*DSTORT*XYINCR, 1 ERRIND, XF) CALL CHKINQ ('ptr', ERRIND) CALL PSLMT (XF, PCPOST) ENDIF C determine concatenation point = ccpx,ccpy CALL PQTXX (SPECWT,FONT, CHXP,CHSP,CHHT, TXP, TXALH,TXALV, 1 TESTC(:SHALF), ERRIND, TX,TY,CCPX,CCPY) CALL CHKINQ ('pqtxx',ERRIND) C display text primitive = testr2 at ccpx,ccpy CALL PTX (CCPX,CCPY, TESTC(SHALF+1:SLEN)) C restore identity local transformation CALL IDMAT (3, XF) CALL PSLMT (XF, PCREPL) 400 CONTINUE CALL SETMSG ('2 6 7 8 10 11 12 17 18', '<Inquire text ' // 1 'extent> should accurately report the ' // 2 'concatenation point when text path = ' // 3 NAMTXP(:TXPLEN) //'.') CALL DCHPFV ('ACCURACY OF CONCATENATION POINT: In which ' // 1 'text primitive are the characters NOT ' // 1 'aligned and evenly separated?', NUMREC, NGREC) CALL PEMST (102) C next text path 100 CONTINUE 666 CONTINUE C wrap it up. CALL ENDIT END
The Burroughs Wellcome Fund is accepting pre-proposals for their Career Awards at the Scientific Interface (CASI) program to foster the early career development of researchers who have transitioned from graduate work in the physical/mathematical/computational sciences or engineering into postdoctoral work in the biological sciences. The five-year award is intended to bridge two years of advanced postdoctoral training and the first three years of faculty service. Proposals that include experimental validation of theoretical models are particularly encouraged. Women and underrepresented minorities strongly encouraged to apply. Several eligibility requirements apply: see RFP or program page for full details. Award of $500,000 over five years delineated as $70,000 in each of Years 1 and 2 (Postdoctoral portion), and $120,000 in each of the subsequent three years (Faculty portion). Funds are intended to cover salary, fringe benefits, administrative fee and research costs. Pre-Proposal requirements: applicant information completed online, a pre-proposal form with a lay abstract and required signatures, and a confidential letter of recommendation from the primary postdoctoral mentor. Deadline: pre-proposal due September 6, 2019 at 4:00 p.m. EDT; full proposal due January 10, 2020 at 4:00 p.m. EST. The Damon Runyon Cancer Research Foundation welcomes applications for its 2019-20 Postdoctoral Fellowship program. Recent PhD, MD, and MD/PhD graduates conducting theoretical and experimental research on cancer and the search for causes, treatments, prevention, therapies, etc. are eligible; those currently in postdoctoral positions are ineligible. Up to four years of funding possible; institutional overhead or indirect costs not allowed. Refer to program announcement for full details.
import MPDA_decode as md import os,sys import numpy as np import random from scipy.optimize import differential_evolution def mpda_decode(x,*args): arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2)) arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1])) # print('ssss = ',*args) print('ins = ',md.MPDA_DE_decode._ins) return random.random() if __name__ == '__main__': insName = '14_14_ECCENTRIC_RANDOMCLUSTERED_SVLCV_LVLCV_thre0.1MPDAins.dat' mpda_de_decode = md.MPDA_DE_decode() ins = md.Instance('.\\benchmark\\' + insName) # md.Instance() bounds = [(0,2)] * ins.robNum *3 print(bounds) # decode = MPDA_DE_decode() md.MPDA_DE_decode._ins = ins # MPDA_DE_decode ''' 增加args 和无args ''' result = differential_evolution(mpda_decode, bounds, args=(mpda_de_decode,3), disp = True) # result = differential_evolution(mpda_decode, bounds,disp = True) print(md.Instance) if type(md.MPDA_DE_decode._ins) == md.Instance: print(type(md.MPDA_DE_decode._ins))
using PSCOPF using Test using Dates @testset "test_check_timesteps" begin @testset "definition_example" begin TS = [DateTime("2015-01-01T11:00:00"), DateTime("2015-01-01T11:15:00"), DateTime("2015-01-01T11:30:00"), DateTime("2015-01-01T11:45:00")] @test PSCOPF.check_target_timepoints(TS) end @testset "not_sorted" begin TS = [DateTime("2015-01-01T11:15:00"), DateTime("2015-01-01T11:00:00"), DateTime("2015-01-01T11:30:00"), DateTime("2015-01-01T11:45:00")] @test !PSCOPF.check_target_timepoints(TS) end @testset "duplicate_value" begin TS = [DateTime("2015-01-01T11:00:00"), DateTime("2015-01-01T11:00:00"), DateTime("2015-01-01T11:30:00"), DateTime("2015-01-01T11:45:00")] @test !PSCOPF.check_target_timepoints(TS) end #= # FIXME Do we assume it is 1 hour with 4 equally spaced Timesteps ? # not for now, to allow simple test cases # i.e.: # length(TS) == 4 # TS[i] - TS[i-1] == 15 mins @testset "duplicate_value" begin TS = [DateTime("2015-01-01T11:00:00"), DateTime("2015-01-01T11:00:00"), DateTime("2015-01-01T11:30:00"), DateTime("2015-01-01T11:45:00")] @test !PSCOPF.check_target_timepoints(TS) end =# end
/- Lecture 3.3: Programming Semantics — Denotational Semantics -/ import .x33_library -- enables β-reduced output set_option pp.beta true /- Complete lattices -/ class complete_lattice (α : Type) extends partial_order α := (Inf : set α → α) (Inf_le : ∀{s a}, a ∈ s → Inf s ≤ a) (le_Inf : ∀{s a}, (∀a', a' ∈ s → a ≤ a') → a ≤ Inf s) notation `⨅` := complete_lattice.Inf /- Instance for complete lattices: `set α` -/ namespace set lemma ext {α : Type} {s t : set α} (h : ∀a, a ∈ s ↔ a ∈ t) : s = t := begin funext a, apply propext, exact (h a) end instance (α : Type) : complete_lattice (set α) := { le := (⊆), le_refl := assume s a, id, le_trans := assume s t u hst htu a has, htu $ hst $ has, le_antisymm := assume s t hst hts, begin apply ext, intro a, apply iff.intro, exact assume h, hst h, exact assume h, hts h end, Inf := assume f, {a | ∀s, s ∈ f → a ∈ s}, Inf_le := assume f s hsf a h, begin simp at h, exact h s hsf end, le_Inf := assume f s h a has t htf, h t htf has } end set /- Monotonicity of functions -/ def monotone {α β} [partial_order α] [partial_order β] (f : α → β) := ∀a₁ a₂, a₁ ≤ a₂ → f a₁ ≤ f a₂ namespace monotone lemma id {α : Type} [partial_order α] : monotone (λa : α, a) := assume a₁ a₂ ha, ha lemma const {α β : Type} [partial_order α] [partial_order β] (b : β) : monotone (λa : α, b) := begin intros a b c, apply le_refl end lemma union {α β : Type} [partial_order α] (f g : α → set β) (hf : monotone f) (hg : monotone g) : monotone (λa, f a ∪ g a) := begin intros a₁ a₂ ha b hb, cases hb, { exact or.intro_left _ (hf a₁ a₂ ha hb) }, { exact or.intro_right _ (hg a₁ a₂ ha hb) }, end end monotone /- Least fixpoint -/ namespace complete_lattice variables {α : Type} [complete_lattice α] def lfp (f : α → α) : α := ⨅ {x | f x ≤ x} lemma lfp_le (f : α → α) (a : α) (h : f a ≤ a) : lfp f ≤ a := Inf_le h lemma le_lfp (f : α → α) (a : α) (h : ∀a', f a' ≤ a' → a ≤ a') : a ≤ lfp f := le_Inf h lemma lfp_eq (f : α → α) (hf : monotone f) : lfp f = f (lfp f) := begin have h : f (lfp f) ≤ lfp f := begin apply le_lfp, intros a' ha', apply @le_trans _ _ _ (f a'), { apply hf, apply lfp_le, assumption }, { assumption } end, apply le_antisymm, { apply lfp_le, apply hf, assumption }, { assumption } end end complete_lattice /- Relations -/ namespace lecture open complete_lattice def Id (α : Type) : set (α × α) := { x | x.2 = x.1 } @[simp] lemma mem_Id {α : Type} (a b : α) : (a, b) ∈ Id α ↔ b = a := iff.rfl def comp {α : Type} (r₁ r₂ : set (α × α)) : set (α × α) := { x | ∃m, (x.1, m) ∈ r₁ ∧ (m, x.2) ∈ r₂ } infixl ` ◯ ` : 90 := comp @[simp] lemma mem_comp {α : Type} (r₁ r₂ : set (α × α)) (a b : α) : (a, b) ∈ r₁ ◯ r₂ ↔ (∃c, (a, c) ∈ r₁ ∧ (c, b) ∈ r₂) := iff.rfl def restrict {α : Type} (r : set (α × α)) (p : α → Prop) : set (α × α) := { x | p x.1 ∧ x ∈ r } infixl ` ⇃ ` : 90 := restrict @[simp] lemma mem_restrict {α : Type} (r : set (α × α)) (p : α → Prop) (a b : α) : (a, b) ∈ r ⇃ p ↔ p a ∧ (a, b) ∈ r := by refl /- We will prove the following two lemmas in the exercise. -/ lemma monotone_comp {α β : Type} [partial_order α] (f g : α → set (β × β)) (hf : monotone f) (hg : monotone g) : monotone (λa, f a ◯ g a) := begin intros a1 a2 asmallerequal, intro b, intros fa1, cases fa1, simp[comp], apply exists.intro fa1_w, apply and.intro, cases fa1_h, apply hf a1, assumption, assumption, cases fa1_h, apply hg a1, assumption, assumption end lemma monotone_restrict {α β : Type} [partial_order α] (f : α → set (β × β)) (p : β → Prop) (hf : monotone f) : monotone (λa, f a ⇃ p) := begin intros a1 a2, intro a1smallera2, intro b, intro f1, cases f1, simp[restrict], apply and.intro, assumption, apply hf a1, assumption, assumption end /- Denotational semantics -/ open program variables {c : state → Prop} {f : state → ℕ} {p p₀ p₁ p₂ : program} def den : program → set (state × state) | skip := Id state | (assign n f) := {x | x.2 = x.1.update n (f x.1)} | (seq p₁ p₂) := den p₁ ◯ den p₂ | (ite c p₁ p₂) := (den p₁ ⇃ c) ∪ (den p₂ ⇃ (λs, ¬ c s)) | (while c p) := lfp (λW, ((den p ◯ W) ⇃ c) ∪ (Id state ⇃ λs, ¬ c s)) notation `⟦` p `⟧`:= den p lemma den_while (p : program) (c : state → Prop) : ⟦ while c p ⟧ = ⟦ ite c (p ;; while c p) skip ⟧ := begin apply lfp_eq, apply monotone.union, { apply monotone_restrict, apply monotone_comp, { exact monotone.const _ }, { exact monotone.id } }, { exact monotone.const _ } end /- Equivalence of denotational and big-step semantics -/ lemma den_of_big_step (p : program) (s t : state) : (p, s) ⟹ t → (s, t) ∈ ⟦ p ⟧ := begin generalize eq : (p, s) = ps, intro h, induction h generalizing eq p s; cases eq; -- simplify only if the simplifier solves the goal completely try { simp [den, *], done }, { exact ⟨h_t, h_ih_h₁ _ _ rfl, h_ih_h₂ _ _ rfl⟩ }, { rw [den_while, den], simp [*], exact ⟨h_t, h_ih_hp _ _ rfl, h_ih_hw _ _ rfl⟩ }, { rw [den_while], simp [den, *] } end lemma big_step_of_den : ∀(p : program) (s t : state), (s, t) ∈ ⟦ p ⟧ → (p, s) ⟹ t | skip s t := by simp [den] {contextual := tt}; exact _ | (assign n f) s t := by simp [den] {contextual := tt} | (seq p₁ p₂) s t := begin assume h, cases h with u hu, exact big_step.seq u (big_step_of_den p₁ _ _ hu.left) (big_step_of_den p₂ _ _ hu.right) end | (ite c p₁ p₂) s t := assume h, match h with | or.intro_left _ ⟨hs, hst⟩ := big_step.ite_true hs (big_step_of_den p₁ _ _ hst) | or.intro_right _ ⟨hs, hst⟩ := big_step.ite_false hs (big_step_of_den p₂ _ _ hst) end | (while c p) s t := begin have hw : ⟦while c p⟧ ≤ {x | (while c p, x.1) ⟹ x.2}, { apply lfp_le _ _ _, intros x hx, cases x with s t, simp at hx, cases hx, { cases hx with hs hst, cases hst with u hu, apply big_step.while_true u hs, { exact big_step_of_den p _ _ hu.left }, { exact hu.right } }, { cases hx, cases hx_right, apply big_step.while_false hx_left } }, exact assume h, hw h end lemma den_eq_bigstep (p : program) (s t : state ) : (s, t) ∈ ⟦ p ⟧ ↔ (p, s) ⟹ t := iff.intro (big_step_of_den p s t) (den_of_big_step p s t) end lecture
Formal statement is: lemma setdist_le_sing: "x \<in> S ==> setdist S T \<le> setdist {x} T" Informal statement is: If $x \in S$, then the distance between $S$ and $T$ is less than or equal to the distance between $\{x\}$ and $T$.
#pragma once #include <Babylon/JsRuntime.h> #include <napi/env.h> #include <gsl/gsl> #include <cassert> namespace Babylon { class NativeDataStream final : public Napi::ObjectWrap<NativeDataStream> { static constexpr auto JS_CLASS_NAME = "_NativeDataStream"; static constexpr auto JS_ENGINE_CONSTRUCTOR_NAME = "NativeDataStream"; static constexpr auto VALIDATION_ENABLED = false; enum class ValidationType : uint32_t { Uint32, Int32, Float32, Uint32Array, Int32Array, Float32Array, NativeData, Boolean, }; template<ValidationType T, typename ReaderT> static inline void Validate(ReaderT& reader) { if constexpr (VALIDATION_ENABLED) { uint32_t value{reader.template Read<uint32_t>()}; if (value != static_cast<uint32_t>(T)) { throw std::runtime_error{"Data stream validation error: data type mismatch."}; } } } public: class Reader final { public: Reader(const Reader&) = delete; Reader(Reader&&) = delete; Reader operator=(const Reader&) = delete; Reader operator=(const Reader&&) = delete; bool CanRead() const { assert(m_position <= static_cast<size_t>(m_buffer.size())); return m_position < static_cast<size_t>(m_buffer.size()); } uint32_t ReadUint32() { Validate<ValidationType::Uint32>(*this); return Read<uint32_t>(); } int32_t ReadInt32() { Validate<ValidationType::Int32>(*this); return Read<int32_t>(); } float ReadFloat32() { Validate<ValidationType::Float32>(*this); return Read<float>(); } gsl::span<uint32_t> ReadUint32Array() { Validate<ValidationType::Uint32Array>(*this); return ReadArray<uint32_t>(); } gsl::span<int32_t> ReadInt32Array() { Validate<ValidationType::Int32Array>(*this); return ReadArray<int32_t>(); } gsl::span<float> ReadFloat32Array() { Validate<ValidationType::Float32Array>(*this); return ReadArray<float>(); } template<typename T> T ReadNativeData() { Validate<ValidationType::NativeData>(*this); static_assert(sizeof(T) % 4 == 0); auto span = gsl::make_span(reinterpret_cast<uint32_t*>(m_buffer.data() + m_position), sizeof(T) / 4); m_position += sizeof(T) / 4; return *reinterpret_cast<T*>(span.data()); } template<typename T, class = typename std::enable_if<!std::is_pointer<T>::value>::type> auto ReadPointer() { return ReadNativeData<typename std::conditional<std::is_member_pointer<T>::value, T, T*>::type>(); } private: gsl::span<uint32_t> m_buffer{}; size_t m_position{0}; const gsl::final_action<std::function<void()>> m_scopeGuard; friend class NativeDataStream; template<typename CallableT> Reader(gsl::span<uint32_t> buffer, CallableT&& callable) : m_buffer{buffer} , m_scopeGuard{std::forward<CallableT>(callable)} { } template<typename T> T Read() { static_assert(sizeof(T) % 4 == 0); T t{*reinterpret_cast<T*>(m_buffer.data() + m_position)}; m_position += sizeof(T) / 4; return t; } template<typename T> gsl::span<T> ReadArray() { static_assert(sizeof(T) % 4 == 0); // The first 32 bit number is a length uint32_t length = Read<uint32_t>(); auto span = gsl::make_span<T>(reinterpret_cast<T*>(m_buffer.data() + m_position), length * (sizeof(T) / 4)); m_position += length; return span; } }; static void Initialize(Napi::Env env) { Napi::HandleScope scope{env}; if constexpr (VALIDATION_ENABLED) { Napi::Function func = DefineClass( env, JS_CLASS_NAME, { InstanceMethod("writeBuffer", &NativeDataStream::WriteBuffer), StaticValue("VALIDATION_ENABLED", Napi::Boolean::From(env, VALIDATION_ENABLED)), StaticValue("VALIDATION_UINT_32", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Uint32))), StaticValue("VALIDATION_INT_32", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Int32))), StaticValue("VALIDATION_FLOAT_32", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Float32))), StaticValue("VALIDATION_UINT_32_ARRAY", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Uint32Array))), StaticValue("VALIDATION_INT_32_ARRAY", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Int32Array))), StaticValue("VALIDATION_FLOAT_32_ARRAY", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Float32Array))), StaticValue("VALIDATION_NATIVE_DATA", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::NativeData))), StaticValue("VALIDATION_BOOLEAN", Napi::Number::From(env, static_cast<uint32_t>(ValidationType::Boolean))), }); JsRuntime::NativeObject::GetFromJavaScript(env).Set(JS_ENGINE_CONSTRUCTOR_NAME, func); } else { Napi::Function func = DefineClass( env, JS_CLASS_NAME, { InstanceMethod("writeBuffer", &NativeDataStream::WriteBuffer) }); JsRuntime::NativeObject::GetFromJavaScript(env).Set(JS_ENGINE_CONSTRUCTOR_NAME, func); } } NativeDataStream(const Napi::CallbackInfo& info) : Napi::ObjectWrap<NativeDataStream>(info) , m_requestFlushCallback{Napi::Persistent(info[0].As<Napi::Function>())} { } void WriteBuffer(const Napi::CallbackInfo& info) { assert(!m_locked); // Cannot write bytes while the stream is locked for reading. const auto& buffer = info[0].As<Napi::ArrayBuffer>(); const auto& length = info[1].ToNumber().Uint32Value(); auto span = gsl::make_span(reinterpret_cast<uint32_t*>(buffer.Data()), static_cast<ptrdiff_t>(length)); m_buffer.insert(m_buffer.end(), span.begin(), span.end()); } Reader GetReader() { assert(!m_locked); m_requestFlushCallback.Call({}); m_locked = true; return {m_buffer, [this]() { m_buffer.clear(); m_locked = false; }}; } private: std::vector<uint32_t> m_buffer{}; Napi::FunctionReference m_requestFlushCallback{}; bool m_locked{false}; }; }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: [email protected] * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef applicationwin32_3971e4cb_1be6_4066_b7ea_da679d40c987_h #define applicationwin32_3971e4cb_1be6_4066_b7ea_da679d40c987_h #include <gslib/string.h> #include <gslib/std.h> #include <ariel/application.h> #include <windows.h> #undef min #undef max __ariel_begin__ typedef LRESULT(__stdcall *fnwndproc)(HWND, UINT, WPARAM, LPARAM); typedef list<string> arg_list; extern void set_execute_path_as_directory(); extern void init_application_environment(app_env& env); extern void init_application_environment(app_env& env, HINSTANCE hinst, HINSTANCE hprevinst, const gchar* argv[], int argc); struct app_data { HINSTANCE hinst = nullptr; HWND hwnd = nullptr; fnwndproc wndproc = nullptr; arg_list arglist; public: bool install(const app_config& cfg, const app_env& env); int run(); }; struct app_env { HINSTANCE hinst = nullptr; HINSTANCE hprevinst = nullptr; arg_list arglist; public: void init(HINSTANCE hinst, HINSTANCE hprevinst, const gchar* argv[], int argc) { init_application_environment(*this, hinst, hprevinst, argv, argc); } }; __ariel_end__ #endif
{-# OPTIONS --universe-polymorphism #-} open import Common.Prelude open import Common.Level open import Common.Reflect module UnquoteSetOmega where `Level : Term `Level = def (quote Level) [] ``Level : Type ``Level = el (lit 0) `Level -- while building the syntax of ∀ ℓ → Set ℓ (of type Setω) is harmless `∀ℓ→Setℓ : Term `∀ℓ→Setℓ = pi (arg (arginfo visible relevant) ``Level) (el (lit 0) (sort (set (var 0 [])))) -- unquoting it is harmfull ∀ℓ→Setℓ = unquote `∀ℓ→Setℓ
The intersection of two sets $a$ and $b$ is the set of all elements that are in both $a$ and $b$.
# rand import Base.rand typealias RandTypes{T,C} Union{AbstractRGB{T}, TransparentRGB{C,T}, AbstractGray{T}, TransparentGray{C,T}} typealias RandTypesFloat{C,T<:AbstractFloat} RandTypes{T,C} rand{G<:AbstractGray}(::Type{G}) = G(rand()) rand{G<:TransparentGray}(::Type{G}) = G(rand(), rand()) rand{C<:AbstractRGB}(::Type{C}) = C(rand(), rand(), rand()) rand{C<:TransparentRGB}(::Type{C}) = C(rand(), rand(), rand(), rand()) function rand{C<:RandTypesFloat}(::Type{C}, sz::Dims) reinterpret(C, rand(eltype(C), (sizeof(C)÷sizeof(eltype(C)), sz...)), sz) end function rand{C<:RandTypes{U8}}(::Type{C}, sz::Dims) reinterpret(C, rand(UInt8, (sizeof(C), sz...)), sz) end function rand{C<:RandTypes{U16}}(::Type{C}, sz::Dims) reinterpret(C, rand(UInt16, (sizeof(C)>>1, sz...)), sz) end # Mapping a function over color channels """ mapc(f, rgb) -> rgbf mapc(f, rgb1, rgb2) -> rgbf `mapc` applies the function `f` to each color channel of the input color(s), returning an output color in the same colorspace. # Examples: julia> mapc(x->clamp(x,0,1), RGB(-0.2,0.3,1.2)) RGB{Float64}(0.0,0.3,1.0) julia> mapc(max, RGB(0.1,0.8,0.3), RGB(0.5,0.5,0.5)) RGB{Float64}(0.5,0.8,0.5) julia> mapc(+, RGB(0.1,0.8,0.3), RGB(0.5,0.5,0.5)) RGB{Float64}(0.6,1.3,0.8) """ mapc{C<:AbstractGray}(f, c::C) = base_color_type(C)(f(gray(c))) mapc{C<:TransparentGray}(f, c::C) = base_colorant_type(C)(f(gray(c)), f(alpha(c))) mapc{C<:Color3}(f, c::C) = base_color_type(C)(f(comp1(c)), f(comp2(c)), f(comp3(c))) mapc{C<:Transparent3}(f, c::C) = base_colorant_type(C)(f(comp1(c)), f(comp2(c)), f(comp3(c)), f(alpha(c))) mapc(f, x, y) = _mapc(_same_colorspace(x,y), f, x, y) _mapc{C<:AbstractGray}(::Type{C}, f, x, y) = C(f(gray(x), gray(y))) _mapc{C<:TransparentGray}(::Type{C}, f, x, y) = C(f(gray(x), gray(y)), f(alpha(x), alpha(y))) _mapc{C<:Color3}(::Type{C}, f, x, y) = C(f(comp1(x), comp1(y)), f(comp2(x), comp2(y)), f(comp3(x), comp3(y))) _mapc{C<:TransparentRGB }(::Type{C}, f, x, y) = C(f(red(x), red(y)), f(comp2(x), comp2(y)), f(comp3(x), comp3(y)), f(alpha(x), alpha(y))) _same_colorspace(x::Colorant, y::Colorant) = _same_colorspace(base_colorant_type(x), base_colorant_type(y)) _same_colorspace{C<:Colorant}(::Type{C}, ::Type{C}) = C @noinline _same_colorspace{C1<:Colorant,C2<:Colorant}(::Type{C1}, ::Type{C2}) = throw(ArgumentError("$C1 and $C2 are from different colorspaces"))
[STATEMENT] lemma dlverts_merge_eq[simp]: assumes "\<forall>t \<in> fst ` fset (sucs t). max_deg t \<le> 1" shows "dlverts (merge t) = dlverts t" [PROOF STATE] proof (prove) goal (1 subgoal): 1. dlverts (merge t) = dlverts t [PROOF STEP] using dverts_merge_eq[OF assms] [PROOF STATE] proof (prove) using this: dverts (merge t) = dverts t goal (1 subgoal): 1. dlverts (merge t) = dlverts t [PROOF STEP] by (simp add: dlverts_eq_dverts_union)
GEORGIA is consistently ranked as the TOP performer in country policy and institutional assessments (CPIA) complied by international financial institutions like World Bank and ADB among many others. According to the Transparency International Glob­al Corruption Barometer Georgia is perceived as a corruption free destination. According to Tax Misery & Reform Index, released by Forbes Business & Financial News, Georgia is the fourth least tax burden country after Qatar, UAE and Hong Kong. Located at the crossroads of Europe, Central Asia, Middle East and Africa Georgia is a key link in the shortest transit route between Western Europe and Central Asia for trans­portation of oil and gas as well as dry cargo. In recent years, Georgian GDP has high growth tendency, while average inflation rate de­creased . The Govern­ment of Georgia implemented reforms in tariff policy as well as in technical regulations sphere. As a result, nowadays Georgia has one of the most liberal foreign trade policies in the world, which implies the facilitated foreign trade regimes and customs proce­dures, low import tariffs and minimal non-tariff regulations. One of the top priorities for the Gov­ernment of Georgia is coordinated functioning of transport fields, modernization-construction of transport infrastructure in accor­dance with international standards. The Government of Georgia is being implementing important infrastructure projects, which shall facilitate new cargo volumes through Georgia and increase effec­tiveness of functioning of transport systems. Agreement incorporates elements which will encourage improvements in the rule of law and in effective gover­nance, as well as further moves towards a well-functioning market economy through the removal of tariff and non-tariff barriers.
function cluoverl(var1) %cluoverl option to display equivalent events or biggest events or clear cluster events % A.Allmann % global bgevent plot1_h plot2_h global equi %[IN] global cluscat backequi newclcat a global dplo1_h dplo2_h dplo3_h dep1 dep2 dep3 global file1 clu h5 global ty stri2 strib global after_h fore_h main_h after_button fore_button global foresh aftersh mainsh calll66 global mainfault main faults clus_button coastline global SizMenu TypMenu new ZG=ZmapGlobal.Data; if var1==1 %hide biggest events set(plot1_h,'Visible','off') elseif var1==2 %plot biggest evens if isempty(plot1_h) %first time plot1_h=plot(bgevent(:,1),bgevent(:,2),'xm'); set(plot1_h,'MarkerSize',5) set(plot1_h,'LineWidth',2) else set(plot1_h,'Visible','on') %show plot that already exists(biggest events) end elseif var1==3 %plot equivalent events if isempty(plot2_h) plot2_h=plot(equi(:,1),equi(:,2),'xg'); set(plot2_h,'MarkerSize',5) set(plot2_h,'LineWidth',2) else set(plot2_h,'Visible','on') end elseif var1==4 %hide equivalent events set(plot2_h,'Visible','off') elseif var1==5 %hide clustered events set(dplo1_h,'Visible','off') set(dplo2_h,'Visible','off') set(dplo3_h,'Visible','off') elseif var1==6 %show clustered events set(dplo1_h,'Visible','on') set(dplo2_h,'Visible','on') set(dplo3_h,'Visible','on') elseif var1==7 %plot clusters and faults for the first time set(clus_button,'Value',1) if isempty(newclcat) replaceMainCatalog(cluscat); else replaceMainCatalog(newclcat); end cla set(gca,'Visible','off') set(gca,'NextPlot','replace') minde = 0.; maxde = max(ZG.primeCatalog.Depth); dep1 = round(0.333*maxde); dep2 = round(0.666*maxde); dep3 = maxde; stri1 = [file1]; % find min and Maximum axes points s1_east = max(ZG.primeCatalog.Longitude); s2_west = min(ZG.primeCatalog.Longitude); s3_north = max(ZG.primeCatalog.Latitude); s4_south = min(ZG.primeCatalog.Latitude); ni = ZG.ni; orient landscape rect = [0.15, 0.12, 0.75, 0.75]; axes('position',rect) % % find start and end time of catalogue "primeCatalog" % [t0b, teb] = bounds(ZG.primeCatalog.Date) ; n = ZG.primeCatalog.Count; tdiff = round(teb - t0b)/days(ZG.bin_dur); n = ZG.primeCatalog.Count; % plot earthquakes (differnt colors for varous depth layers) as % defined in "startzmap" % set(gca,'NextPlot','add') dplo1_h =plot(... ZG.primeCatalog.Longitude(ZG.primeCatalog.Depth<=dep1),... ZG.primeCatalog.Latitude(ZG.primeCatalog.Depth<=dep1),'.b'); set(dplo1_h,'MarkerSize',ZG.ms6,'Marker',ty) dplo2_h =plot(... ZG.primeCatalog.Longitude(ZG.primeCatalog.Depth<=dep2&ZG.primeCatalog.Depth>dep1),... ZG.primeCatalog.Latitude(ZG.primeCatalog.Depth<=dep2&ZG.primeCatalog.Depth>dep1),'.y'); set(dplo2_h,'MarkerSize',ZG.ms6,'Marker',ty); dplo3_h =plot(... ZG.primeCatalog.Longitude(ZG.primeCatalog.Depth<=dep3&ZG.primeCatalog.Depth>dep2),... ZG.primeCatalog.Latitude(ZG.primeCatalog.Depth<=dep3&ZG.primeCatalog.Depth>dep2),'.r'); set(dplo3_h,'MarkerSize',ZG.ms6,'Marker',ty) axis([ s2_west s1_east s4_south s3_north]) xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m) ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m) if isempty(backequi) strib = [ ' Map of ' file1 ]; %ti2 = title(strib,'FontWeight','bold',... % 'FontSize',ZmapGlobal.Data.fontsz.l,'Color','r') else delete ti2; end %make depth legend % s = sprintf('Depth < %3.1f km',dep1); text('Color','b','units','normalized', 'Position',[0.05 0.15 0 ],... 'FontSize',ZmapGlobal.Data.fontsz.m,'String',s); s = sprintf('Depth < %3.1f km',dep2); text('Color','y','units','normalized', 'Position',[0.05 0.10 0 ],... 'FontSize',ZmapGlobal.Data.fontsz.m,'String',s); s = sprintf('Depth < %3.1f km',dep3); text('Color','r','units','normalized', 'Position',[0.05 0.05 0 ],... 'FontSize',ZmapGlobal.Data.fontsz.m,'String',s); % h5 is the graphic handle to the main figure in window 1 % h5 = gca; set(gca,'box','on',... 'SortMethod','childorder','TickDir','out','FontWeight',... 'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2) % % Plots epicenters and faults overlay % Make the figure visible % elseif var1==8 replaceMainCatalog(ZG.ttcat); cla set(gca,'visible','off') set(gca,'NextPlot','replace') s1_east = max(ZG.primeCatalog.Longitude); %limits for area plot s2_west = min(ZG.primeCatalog.Longitude); s3_north = max(ZG.primeCatalog.Latitude); s4_south = min(ZG.primeCatalog.Latitude); if s1_east==s2_west %to avoid error when all earthquakes have s1_east=s1_east+0.05; %same longitude and/or latitude s2_west=s2_west-0.05; end if s3_north==s4_south s3_north=s3_north+0.05; s4_south=s4_south-0.05; end orient landscape rect = [0.15, 0.12, 0.75, 0.75]; axes('position',rect) % % find start and end time of catalogue "primeCatalog" % [t0b, teb] = bounds(ZG.primeCatalog.Date) ; n = ZG.primeCatalog.Count; tdiff = round(teb - t0b)/days(ZG.bin_dur); %define fore and aftershocks % tmp = find(ZG.primeCatalog.Magnitude==max(ZG.primeCatalog.Magnitude)); %index in a of first mainshock if length(tmp)>1 tmp=tmp(1,1); end overlay; %plot fore and aftershocks in different colors % set(gca,'NextPlot','add') if tmp-1>=1 fore_h=plot(ZG.primeCatalogLongitude(1:tmp-1),ZG.primeCatalog.Latitude(1:tmp-1),'.b'); if isempty(aftersh) %only at first call foresh=aZG.primeCatalog.subset(1:tmp-1); end else if exist('fore_h') fore_h=[]; end end main_h=plot(ZG.primeCatalog.Longitude(tmp),ZG.primeCatalog.Latitude(tmp),'xm'); mainsh=ZG.primeCatalog.subset(tmp); set(main_h,'MarkerSize',10); set(main_h,'LineWidth',2); if tmp+1<=n after_h=plot(ZG.primeCatalog.Longitude(tmp+1:n),ZG.primeCatalog.Latitude(tmp+1:n),'.r'); if isempty(aftersh) aftersh=ZG.primeCatalog.subset(tmp+1:n); end else if exist('after_h') after_h=[]; end end set(after_button,'value',1); set(fore_button,'value',1); axis([ s2_west s1_east s4_south s3_north]) xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m) ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m) strib = [ ' Map of ' file1 ' #' num2str(new(10))]; title(strib,'FontWeight','bold',... 'FontSize',ZmapGlobal.Data.fontsz.l,'Color','r') set(gca,'box','on',... 'SortMethod','childorder','TickDir','out','FontWeight',... 'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2) set(gca,'visible','on') end
An outoftown property management property management company that manages property in Davis, other areas in California, and also Hawaii. According to their website, EAH is one of the largest and most respected nonprofit housing development corporations in the State of California. Originally named the Ecumenical Association for Housing, they manage: Primero Grove University Court Apartments (As of August 18th, 2005, they no longer manage this property)
The SPOT sensor placement solvers are launched with the \doxyref{sp}{p.}{spExecutable} command. The {\ttfamily sp} command reads in one or more IMPACT files, and computes a sensor placement. Command-\/line options for {\ttfamily sp} can specify any of a set of performance or cost goals as the objective to be optimized, as well as constraints on performance and cost goals. The {\ttfamily sp} command currently interfaces with three different sensor placement optimizers: \begin{itemize} \item {\bfseries MIP solvers} -\/ Several different MIP solvers can be used by the {\ttfamily sp} command: the commercial CPLEX solver and the open-\/source PICO solver. These optimizers use the MIP formulations to find globally optimal solutions. However, this may be a computationally expensive process (especially for large problems), and the size of the MIP formulation can become prohibitively large in some cases. Two different MIP solvers can be used: the public-\/domain glpk solver and the commercial solver. PICO is included in distributions of SPOT. \item {\bfseries GRASP heuristic} -\/ The GRASP heuristic performs sensor placement optimization without explicitly creating a MIP formulation. Thus, this solver uses much less memory, and it usually runs very quickly. Although the GRASP heuristic does not guarantee that a globally optimal solution is found, it has proven effective at finding optimal solutions to a variety of large-\/scale applications. Two different implementations of the GRASP solvers can be used: an ATT commercial solver (att\_\-grasp) and an open-\/source implementation of this solver (snl\_\-grasp). \item {\bfseries Lagrangian Heuristic} -\/ The Lagrangian heuristic uses the structure of the p-\/median MIP formulation (eSP) to find near-\/optimal solutions while computing a lower bound on the best possible solution. \end{itemize} The following sections provide examples that illustrate the use of the {\ttfamily sp} command. A description of {\ttfamily sp} command line options is available in the \doxyref{Appendix}{p.}{spExecutable}. The {\ttfamily sp} command has many different options. The following examples show how different sensor placement optimization problems can be solved with {\ttfamily sp}. Note that these examples can be run in the {\ttfamily C:$\backslash$spot$\backslash$examples$\backslash$simple} directory. The user needs to generate IMPACT files for these examples with the following commands: \lstinputlisting[firstline=11,lastline=12]{examples/simple/solver1.sh} % anchor=prelim \section{A Simple Example}\label{solvers_solvers2} The following simple example illustrates the way that SPOT has been most commonly used. In this example, SPOT minimizes the extent of contamination (ec) while limiting the number of sensors (ns) to no more than 5. This problem formulation (eSP) can be efficiently solved with all solvers for modest-\/size distribution networks, and heuristics can effectively perform sensor placement on very large networks. We begin by using the PICO solver to solve this problem, with the following command line: \lstinputlisting[firstline=23,lastline=23]{examples/simple/solver1.sh} % anchor=sp This specifies that network {\ttfamily Net3} is analyzed. The objective is to minimize {\ttfamily ec}, the extent of contamination, and an upper-\/bound of 5 is placed on {\ttfamily ns}, the number of sensors. The solver selected is {\ttfamily pico}, the PICO MIP solver. This execution of the {\ttfamily sp} command uses the {\ttfamily Net3\_\-ec.impact} file and creates the following files: {\ttfamily Net3.log}, a logfile for the optimization solver, and Net3.sensors, a file with the sensor placement locations. Also, {\ttfamily sp} generates the following output: \lstinputlisting[]{examples/simple/solver1.txt} The initial information up to the statement \char`\"{}... PICO done\char`\"{} is simply output about what solver is run and information from the solver output. The next information beginning with \char`\"{}Sensor placement id:\char`\"{} is generated by \doxyref{evalsensor}{p.}{evalsensorExecutable}. This is a summary that describes the sensor placement and the performance of this sensor placement with respect to the impact measure that was minimized. This includes the following data: \begin{itemize} \item {\bfseries Sensor placement id} -\/ an integer ID used to distinguish this sensor placement \item {\bfseries Number of sensors} -\/ the number of sensors in the sensor placement \item {\bfseries Total cost:} -\/ the cost of the sensor placement, which may be nonzero if cost data is provided \item {\bfseries Sensor node IDs} -\/ the internal node indexes used by {\ttfamily sp} \item {\bfseries Sensor junctions} -\/ the EPANET junction labels for the sensor locations \end{itemize}The performance of the sensor placement is summarized for each IMPACT file used with {\ttfamily sp}. The impact statistics included are: \begin{itemize} \item {\bfseries min} -\/ The minimum impact over all contamination events. If we make the assumption that a sensor protects the node at which it is placed, then this measure will generally be zero. \item {\bfseries mean} -\/ The mean (or average) impact over all contamination events. \item {\bfseries lower quartile} -\/ 25\% of contamination events, weighted by their likelihood, have an impact value less than this quartile. \item {\bfseries median} -\/ 50\% of contamination events, weighted by their likelihood, have an impact value less than this quartile. \item {\bfseries upper quartile} -\/ 75\% of contamination events, weighted by their likelihood, have an impact value less than this quartile. \item {\bfseries VaR} -\/ The value at risk (VaR) uses a user-\/defined percentile. Given $ 0.0 < \beta < 1.0$, VaR is the minimum value for which $100*(1-\beta)$\% of contamination events have a smaller impact. \item {\bfseries TCE} -\/ The tailed-\/conditioned expectation (TCE) is the mean value of the impacts that are greater than or equal to VaR. \item {\bfseries worst} -\/ The value of the worst impact. \end{itemize} Finally, a greedy sensor placement is described by {\ttfamily evalsensor}, which takes the five sensor placements and places them one-\/at-\/a-\/time, minimizing the mean impact as each sensor is placed. This gives a sense of the relative priorities for these sensors. The {\ttfamily evalsensor} command can evaluate a sensor placement for a wide variety of different objectives. For example, the command \lstinputlisting[firstline=27,lastline=28]{examples/simple/solver2.sh} % anchor=evalsensor will summarize the solution in the {\ttfamily Net3.sensors} file for the {\ttfamily ec}, {\ttfamily mc} and {\ttfamily nfd} impact measures. The following example shows how to solve this same problem with the GRASP heuristic. This solver finds the same (optimal) solution as the MIP solver, though much more quickly. The command \lstinputlisting[firstline=23,lastline=23]{examples/simple/solver3.sh} % anchor=sp generates the following output: \lstinputlisting[]{examples/simple/solver3.txt} Finally, the following example shows how to solve this problem with the Lagrangian heuristic. This solver does not find as good a solution as the GRASP heuristic. The command \lstinputlisting[firstline=23,lastline=23]{examples/simple/solver4.sh} % anchor=sp generates the following output: \lstinputlisting[]{examples/simple/solver4.txt} \section{Computing a Bound on the Best Sensor Placement Value}\label{solvers_solvers2a} The following example shows how a lower bound can be computed on the best possible sensor placement. That is, any sensor placement would have an expected impact greater than this value. A bound is computed with the following syntax: \lstinputlisting[firstline=23,lastline=24]{examples/simple/solver5.sh} % anchor=sp This command generates the following output: \lstinputlisting[]{examples/simple/solver5.txt} \section{Minimizing the Number of Sensors}\label{solvers_solvers2b} The sensor placement problem can be inverted by minimizing the number of sensors subject to a constraint on the extent of contamination. Note that the following example finds a solution with a single sensor that meets our goal of 40000 mean extent of contamination. The command \lstinputlisting[firstline=23,lastline=24]{examples/simple/solver6.sh} % anchor=sp generates the following output: \lstinputlisting[]{examples/simple/solver6.txt} \section{Fixing Sensor Placement Locations}\label{solvers_solvers2c} Properties of the sensor locations can be specified with the {\ttfamily -\/-\/sensor-\/locations} option. This options specifies a \doxyref{Placement Locations File}{p.}{formats_locationsFile} that can control whether sensor locations are feasible or infeasible, and fixed or unfixed. For example, suppose the file {\ttfamily locations} contains \lstinputlisting[]{examples/simple/locations} The following example shows how these restrictions impact the solution. Compared to the first example above, we have a less-\/optimal solution, since the sensor locations above cannot be used and junction {\ttfamily 161} must be included. The command \lstinputlisting[firstline=23,lastline=24]{examples/simple/solver7.sh} % anchor=sp generates the following output: \lstinputlisting[]{examples/simple/solver7.txt} \section{Robust Optimization of Sensor Locations}\label{solvers_solvers4} The following example demonstrates the optimization of sensor placements using the TCE measure. TCE is the mean value of the worst incidents in the ensemble being evaluated. Given a confidence level $1-\beta$, TCE is the expectation of the worst impacts with probability $\beta$. Compared with our first example, this finds a better solution in terms of TCE, although the mean performance is slightly worse. The command \lstinputlisting[firstline=23,lastline=23]{examples/simple/solver8.sh} % anchor=sp generates the following output: \lstinputlisting[]{examples/simple/solver8.txt} Note that the greedy ordering of sensors is less useful in this case. Although we optimized to minimize TCE, the greedy ordering uses the mean value to select each sensor location. \section{Multi-\/Criteria Analysis}\label{solvers_solvers7} The {\ttfamily sp} command supports multi-\/objective analysis through an iterative process. SPOT does not have a general \char`\"{}pareto search\char`\"{} optimizer. Instead, users can specify constraints with {\ttfamily sp} that ensure that previously optimized objectives are \char`\"{}close\char`\"{} to their previous values. In this way, the user can explicitly search for trade-\/offs between one-\/or-\/more performance objectives. The examples above consider the extent-\/of-\/contamination objective. The sensor placements generated above can be assessed as to how they minimize other objectives like the expected mass of contaminant consumed using {\ttfamily evalsensor}. Consider the solution generated by the previous example (which minimized {\ttfamily ec\_\-tce}), which was copied into the file {\ttfamily Net3\_\-ec.sensors}. The command \lstinputlisting[firstline=29,lastline=29]{examples/simple/solver9.sh} % anchor=evalsensor generates the following output: \lstinputlisting[]{examples/simple/solver9.txt} The mean mass consumed is 70907, which is far from the optimal value of 21782 (which we computed separately). The robust optimization example in the previous section is revisited here; \char`\"{}extent of contamination -\/ tce\char`\"{} is still the primary objective, but now a \char`\"{}side constraint\char`\"{} is imposed that precludes any solution that admits an average mass consumed of worse than 30,000 units. The command \lstinputlisting[]{examples/simple/solver10.sh} % anchor=evalsensor generates the following output: \lstinputlisting[]{examples/simple/solver10.txt} Note that the primary objective, minimizing the TCE of the \char`\"{}extent of contamination\char`\"{} measure, has gotten worse: it is now 50267 rather than 26376. However, our side constraint has been honored, and the mean mass consumed value is now 29350 rather than 70907. \section{Sensor Placements without Penalties}\label{solvers_solvers9} A fundamental issue for sensor placement is how to handle the fact that a limited budget of sensors will not be able to cover all possible incidents. SPOT addresses this issue by providing impact measures that integrate an impact 'penalty' for incidents that are not detected by a CWS design. Thus, in the previous examples there was an implicit trade-\/off between impact reduction and reduction in the number of contamination incidents that are detected. SPOT also includes impact measures that do not contain these penalties, which allows a user to more directly assess the performance of a CWS design in the context where detections have occurred. For example, the time-\/to-\/detection measure (td) includes a penalty for undetected incidents, but the detected-\/time-\/to-\/detection measure (dtd) has no penalty (or, more precisely, a zero penalty). For example, consider the simple example above, which minimizes the extent of contamination. The {\ttfamily evalsensors} command is applied to the final solution to evaluate the {\bfseries ec}, {\bfseries dec} and {\bfseries nfd} impact measures: \lstinputlisting[firstline=22,lastline=23]{examples/simple/solver11.sh} % anchor=evalsensor This generates the following output: \lstinputlisting[]{examples/simple/solver11.txt} In this example, the final sensor placement fails to detect 25\% of the incidents. It is noteworthy that this does not impact the mean performance very much, since the impact penalty has led to a final solution that fails to detect few incidents with high penalties. Note that minimizing {\bfseries dtd} does not really make sense. With zero sensors, you detect no incidents, which means that the final impact measurement is zero! Thus, minimizing {\bfseries dtd} requires the additional constraint on the number of failed detections (nfd) as well as a limit on the number of sensors (or total sensor costs). Only the 'pico' SPOT solver currently supports optimization with 'detected' impact measures. For example: \lstinputlisting[firstline=16,lastline=17]{examples/simple/solver12.sh} generates the following output: \lstinputlisting[]{examples/simple/solver12.txt} \section{Limited-\/Memory Sensor Placement Techniques}\label{solvers_solvers5} Controlling memory usage is a critical issue for solving large sensor placement formulations. This is a particular challenge for MIP methods, but both the GRASP and Lagrangian heuristics can have difficultly solving very large problems on standard workstations. A variety of mechanisms have been integrated into {\ttfamily sp} to reduce the problem representation size while preserving the structure of the sensor placement problem. These techniques include: scenario aggregation and filtering, feasible locations, witness aggregation, skeletonization, and memory management. The \doxyref{scenarioAggr}{p.}{scenarioAggrExecutable} method described in the previous section is one possible strategy. This tool compresses the impact file while preserving the fundamental structure of the impact file and it is appropriate when optimizing for mean performance objectives. Similarly, the \doxyref{filter\_\-impacts}{p.}{filter_impactsExecutable} script can limit the sensor placement to only consider contamination incidents that are \char`\"{}sufficiently bad\char`\"{} in the worst-\/case. Another strategy is to limit the number of sensor placements, using the {\ttfamily -\/-\/sensor-\/locations} option described above. Eliminating feasible locations reduces the problem representation used by the {\ttfamily sp} solvers. The {\itshape witness aggregation\/} technique can be used to limit the size of the sensor placement formulation. This term refers to the variables in the MIP formulation that \char`\"{}witness\char`\"{} a contamination event. By default, variables that witness contamination events with the same impact are aggregated, and this typically reduces the MIP constraint matrix by a significant amount. Further reductions can be performed with more aggressive aggregations. To illustrate the use of witness aggregation, we generated impact files with the {\ttfamily C:$\backslash$spot$\backslash$etc$\backslash$tsg$\backslash$hourly.tsg} TSG file. The following table illustrates the use of the two witness aggregation options when optimizing the mean extent of contamination: {\ttfamily -\/-\/aggregation-\/percent} and {\ttfamily -\/-\/aggregation-\/ratio} (used with the {\ttfamily -\/-\/distinguish-\/detection} option, which helps this aggregation option). The second line of data in this table is the default aggregation, which has about half as many non-\/zero values in the MIP constraint matrix. Both the percent and ratio aggregation strategies effectively reduce the problem size while finding near-\/optimal solutions. \begin{center} \begin{TabularC}{5} \hline Aggr Type&Aggr Value&Binary Vars&MIP Nonzeros&Solution Value \\\cline{1-5} None&NA&97&220736&8525 \\\cline{1-5} Percent&0.0&97&119607&8525 \\\cline{1-5} Percent&0.125&97&49576&9513 \\\cline{1-5} Ratio&0.125&97&12437&10991 \\\cline{1-5} \end{TabularC} \end{center} Another option to reduce the memory requirement for sensor placement is to reduce the size of the network model through skeletonization. Skeletonization groups neighboring nodes based on the topology of the network and pipe attributes. The TEVA-SPOT Skeleton code, \doxyref{spotSkeleton} {p.}{skelExecutable}, provides techniques for branch trimming, series pipe merging, and parallel pipe merging. Skeletonization eliminates pipes and junctions that have little impact on the overall hydraulics of the system. This effectively contracts a connected piece of the network into a single node, called a supernode. Skeletonized networks can be used to define geographic proximity in a two-tiered sensor placement approach for large network models. Details on the two-tiered sensor placement approach can be found in \doxyref{Section 5.9}{p.}{solvers_solvers5a}. Additionally, the GRASP heuristic has several options for controlling how memory is managed. The {\ttfamily -\/-\/grasp-\/representation} option can be used to control how the local search steps are performed. By default, a dense matrix is precomputed to perform local search steps quickly, but a sparse matrix can be used to perform local search with less memory. Also, the GRASP heuristic can be configured to use the local disk to store this matrix. It should be noted that the Lagrangian heuristic requires less memory than the GRASP heuristic, and thus similar techniques have not been developed for it. \section{Two-\/tiered Sensor Placement Approach}\label{solvers_solvers5a} The two-tiered sensor placement approach uses geographic aggregation on the large impact files to select candidate locations for secondary optimization. While the approach uses detailed hydraulic calculations, it avoids solving sensor placement using the large impact file directly, a process that can exceed the memory available on a personal computer. Geographic aggregation combines witness locations over all scenarios based on their geographic proximity. To maintain hydraulic equivalence as much as possible, skeletonization is used to define geographic proximity. This process is similar to witness aggregation, where witness locations for a single scenario are combined based upon their witness quality. In both cases, the number of possible sensor locations is reduced. Geographic aggregation reduces the impact file by grouping nodes that are co-located in the skeletonization process. In essence, this reduces the impact file to include only skeletonized nodes (i.e. supernodes) defined in the skeletonized network. From the skeletonized viewpoint, the contaminant hits a supernode when it first crosses the curve defining the supernode. Depending upon the direction the contaminant approaches, it will hit the real nodes inside the supernodes in different orders. With geographic aggregation, the minimum, maximum, mean, or median could be used to group the time and impact for the real nodes in each supernode. For a sensor on a single real node in the supernode, the maximum statistic is pessimistic for incidents that the node detects. Similarly, using the minimum is always optimistic. For example, consider one supernode that represents four nodes in the original network. The impact values for those nodes are 100, 200, 250, and 300. After geographic aggregation, the impact value is 100 using the minimum, 300 using the maximum, 212.5 using the mean, and 225 using the median. The time associated with each of these impacts is grouped the same way. The new time and impact pair is the aggregated representation of the impact file for that node. For this supernode, four lines of the impact file are reduced to one. This aggregation is performed for each scenario and each supernode. While this greatly reduces the size of the impact file, the number of scenarios remains the same. This method is not influenced by the modified hydraulics of the skeletonized network; rather, the original impact file is modified to reflect geographic aggregation from the skeletonized network. In the first-tier (Tier 1), sensor placement filters candidate sensor locations based on a geographic aggregation of the impact file. Heuristically, sensor placement in this course search identifies supernodes that are promising regions for sensors. Only real nodes within these selected supernodes are considered candidate sensor locations. All other locations from the impact file generated from the original, most-refined network model are removed. The second-tier (Tier 2) sensor placement uses this refined impact file to place sensors in the original network. Since sensor placement in each tier runs on a smaller impact file than a direct placement on the original network, the two-tiered approach reduces the maximum memory requirement. The two-tiered sensor placement approach can be run using \doxyref{sp-2tier} {p.}{sp2tierExecutable}. The method calls \doxyref{spotSkeleton} {p.}{skelExecutable} to define geographic proximity from skeletonized networks. The two-tiered method has been shown to maintain solution quality while greatly reducing the memory footprint need for sensor placement. For additional details, see Klise, Phillips, and Janke \cite{KliPhiJan11review}. The {\bfseries sp-2tier} executable is run with the following command line: \lstinputlisting[firstline=16,lastline=17]{examples/simple/solver16.sh} This command generates aggregated and refined impact files, along with output files from {\bfseries sp} based on Tier 1 and Tier 2 sensor placement. \section{Evaluating a Sensor Placement}\label{solvers_solvers6} The \doxyref{evalsensor}{p.}{evalsensorExecutable} executable takes sensor placements in a \doxyref{Sensor Placement File}{p.}{formats_sensorPlacementFile} and evaluates them using data from an \doxyref{Impact File}{p.}{formats_impactFile} (or a list of impact files). This executable measures the performance of each sensor placement with respect to the set of possible contamination locations. This analysis assumes that probabilities have been assigned to these contamination locations, and if no probabilities are given then uniform probabilities are used by {\ttfamily evalsensor}. The following example illustrates the use of {\ttfamily evalsensor} after running the first sensor placement optimization example. The command \lstinputlisting[firstline=30,lastline=30]{examples/simple/solver13.sh} generates the following output: \lstinputlisting[]{examples/simple/solver13.txt} The {\ttfamily evalsensors} command can also evaluate a sensor placement in the case where sensors can fail, and there is some small number of different classes of sensors (grouped by false negative probability). This information is defined by a \doxyref{Sensor Class File}{p.}{formats_sensorClass} and a \doxyref{Junction Class File}{p.}{formats_junctionClass}. Consider the sensor class or sc file, {\ttfamily Net3.imperfectsc}, which defines different categories of sensor failures: \lstinputlisting[]{examples/Net3/Net3.imperfectsc} Sensors of class \char`\"{}1\char`\"{} give false negative readings 25\% of the time, sensors of class \char`\"{}2\char`\"{} give them 50\% of the time, etc. Once failure classes have been defined, the junctions of the network are assigned to classes. This is done with a junction class or jc file, like {\ttfamily Net3.imperfectjc} (here we show just the beginning of this file): \lstinputlisting[firstline=0,lastline=10]{examples/Net3/Net3.imperfectjc} Given the junction classes, we can run {\ttfamily evalsensor} to determine the expected impact of a sensor placement, given that sensors may fail. Again, using the solution from the original example: \lstinputlisting[firstline=30,lastline=31]{examples/simple/solver14.sh} generates the following output: \lstinputlisting[]{examples/simple/solver14.txt} Note that the mean impact of this \char`\"{}extent of contamination\char`\"{} changes dramatically if sensors are allowed to fail. The original solution, 8499 pipe feet, was misleading if sensors fail according to the probabilities we have assigned. With sensor failures, the expected impact is 17193 pipe feet -\/-\/ more than twice the \char`\"{}perfect sensor\char`\"{} impact. \section{Sensor Placement with Imperfect Sensors}\label{solvers_solvers3} The GRASP heuristics in SPOT can optimize sensor placements that take into account sensor failures. For example, we can perform sensor placement optimization with imperfect sensors using the {\ttfamily Net3.imperfectsc} and {\ttfamily Net3.imperfectjc} files defined in the previous section. The command \lstinputlisting[firstline=16,lastline=17]{examples/simple/solver15.sh} % anchor=sp generates the following output: \lstinputlisting[]{examples/simple/solver15.txt} After this optimization, the mean impact is 13469 pipe feet rather than the 17193 pipe feet value for the solution optimized with perfect sensors. Thus, it is clear that the GRASP heuristic makes different choices if the sensors are imperfect. \section{Summary of Solver Features}\label{solvers_solversSummary} The following table highlights the capabilities of the SPOT optimizers. The previous examples illustrate SPOT's capabilities, but the advanced features in SPOT are not available for all optimizers. \begin{TabularC}{4} \hline {\bfseries Solver Feature} &{\bfseries MIP} &{\bfseries GRASP} &{\bfseries Lagrangian} \\\cline{1-4} Minimize mean impact$^{1}$ &YES &YES &YES \\\cline{1-4} Minimize worst impact$^{2}$ &YES &YES &NO \\\cline{1-4} Minimize number of sensors$^{3}$ &YES &NO &NO \\\cline{1-4} Robust objectives$^{4}$ &YES &YES &NO \\\cline{1-4} Side-\/constraints$^{5}$ &YES &YES &YES \\\cline{1-4} Fixed/Invalid locations$^{6}$ &YES &YES &NO \\\cline{1-4} Witness aggregation$^{7}$ &YES &NO &YES \\\cline{1-4} Incident probabilities$^{8}$ &YES &NO &YES \\\cline{1-4} Incident aggregation$^{9}$ &YES &NO &YES \\\cline{1-4} Sparse data management$^{10}$ &NO &YES &NO \\\cline{1-4} Imperfect sensor model$^{11}$ &NO &YES &NO \\\cline{1-4} One imperfect witness$^{12}$ &YES &YES &NO \\\cline{1-4} Computes lower bound$^{13}$ &YES &NO &YES \\\cline{1-4} \end{TabularC} Footnotes:\\ 1. The mean sensor placement formulation has been tested on a wide range of network models. The GRASP heuristic reduces memory requirements for large problems with reliable solutions. The Lagrangian solver can be used to find a lower bound. The Langrangian solver solutions generally have larger errors than GRASP. MIP is provably optimal but can be slower and require more memory.\\ 2. Worst case is slow with GRASP. GRASP has much larger error ratios than for mean. The standard MIP formulation is difficult and may not solve. Improvements pending.\\ 3. MIP can be slow for a mean side-constraint. Improvements pending for worst-case side constraints. Other side constraints not tested.\\ 4. VAR and CVAR are slow with GRASP. GRASP has much larger error ratios than for mean. The standard MIP formulation is difficult and may not solve. \\ 5. Not extensively tested. MIP and GRASP side constraints are hard. Lagrangian is soft/heuristic. Side constraint may not be satisfied. Likely worse for main objective as well. Developers recognize the need to tune this.\\ 6. Fixed and invalid locations currently work with both MIP and GRASP solvers. Pending for Lagrangian.\\ 7. Witness aggregation significantly reduces solution quality for Lagrangian, though does reduce memory. No-error aggregation is on by default for MIP.\\ 8. Incident weightings are only implemented for mean or CVAR.\\ 9. Incident aggregation introduces no errors and can reduce space. In initial testing, the prefix property necessary for this aggregation is rare, so this is off by default given the cost of searching and implementing.\\ 10. This is not supported in the SNL GRASP implementation.\\ 11. This is a nonlinear formulation.\\ 12. This is a linear approximation for imperfect sensors implemented with the mean solvers. This is much faster than the GRASP solver for the nonlinear formulation and seems to give values close to the GRASP solution value.\\ 13. Lower bounds provably show how close a solution is to optimal. MIP solvers give gaps or give provably optimal solutions. A lower bound from the Lagrangian solver can validate the quality of a solution (upper bound) from GRASP.\\
check_checkpoint_freq = function(checkpoint_freq) { freq = as.integer(checkpoint_freq) if (is.na(freq) || length(freq) != 1L || freq < 1L) comm.stop("argument 'checkpoint_freq' must be a positive integer") freq }
=begin [((<index-ja|URL:index-ja.html>))] = 多項式環相互変換ユーティリティー Polynomial <-> MPolynomial の相互変換ユーティリティーです。 == ファイル名: * ((|polyomimial-converter.rb|)) == メソッド --- Algebra::Polynomial.convert_to(ring) ((<Algebra::MPolynomial|URL:m-polynomial-ja.html>)) である ((|ring|)) に変換します。 --- Algebra::Polynomial#value_on(ring) ((<Algebra::MPolynomial|URL:m-polynomial-ja.html>)) である ((|ring|)) における値を返します。 例: require "m-polynomial" require "polynomial" P = Algebra::Polynomial(Integer, "x", "y", "z") x, y, z = P.vars f = x**2 + y**2 + z**2 - x*y - y*z - z*x MP = P.convert_to(Algebra::MPolynomial) p f = f.value_on(MP) #=> z^2 - zy - zx + y^2 - yx + x^2 x, y, z = MP.vars p f == x**2 + y**2 + z**2 - x*y - y*z - z*x #=> true --- Algebra::MPolynomial.convert_to(ring) ((<Algebra::Polynomial|URL:m-polynomial-ja.html>)) である ((|ring|)) に変換します。 --- Algebra::MPolynomial#value_on(ring) ((<Algebra::Polynomial|URL:m-polynomial-ja.html>)) である ((|ring|)) における値を返します。 例: require "m-polynomial" require "polynomial" MP = Algebra::MPolynomial(Integer, "x", "y", "z") x, y, z = MP.vars f = x**2 + y**2 + z**2 - x*y - y*z - z*x P = MP.convert_to(Algebra::Polynomial) p f = f.value_on(P) #=> x^2 + (-y - z)x + y^2 - zy + z^2 x, y, z = P.vars p f == x**2 + y**2 + z**2 - x*y - y*z - z*x #=> ture =end
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/hms/hms_catalog.h" #include <map> #include <memory> #include <string> #include <type_traits> #include <utility> #include <vector> #include <boost/optional/optional.hpp> #include <gflags/gflags_declare.h> #include <gtest/gtest.h> #include "kudu/common/common.pb.h" #include "kudu/common/schema.h" #include "kudu/gutil/map-util.h" // IWYU pragma: keep #include "kudu/gutil/strings/substitute.h" #include "kudu/hms/hive_metastore_types.h" #include "kudu/hms/hms_client.h" #include "kudu/hms/mini_hms.h" #include "kudu/rpc/sasl_common.h" #include "kudu/security/test/mini_kdc.h" #include "kudu/thrift/client.h" #include "kudu/util/net/net_util.h" #include "kudu/util/status.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" DECLARE_string(hive_metastore_uris); DECLARE_bool(hive_metastore_sasl_enabled); using kudu::rpc::SaslProtection; using std::make_pair; using std::string; using std::unique_ptr; using std::vector; using strings::Substitute; namespace kudu { namespace hms { TEST(HmsCatalogStaticTest, TestNormalizeTableName) { string table = "foo.bar"; ASSERT_OK(HmsCatalog::NormalizeTableName(&table)); ASSERT_EQ("foo.bar", table); table = "fOo.BaR"; ASSERT_OK(HmsCatalog::NormalizeTableName(&table)); EXPECT_EQ("foo.bar", table); table = "A.B"; ASSERT_OK(HmsCatalog::NormalizeTableName(&table)); EXPECT_EQ("a.b", table); table = "__/A__.buzz"; ASSERT_OK(HmsCatalog::NormalizeTableName(&table)); EXPECT_EQ("__/a__.buzz", table); table = "THE/QUICK/BROWN/FOX/JUMPS/OVER/THE/LAZY/DOG." "the_quick_brown_fox_jumps_over_the_lazy_dog"; ASSERT_OK(HmsCatalog::NormalizeTableName(&table)); EXPECT_EQ("the/quick/brown/fox/jumps/over/the/lazy/dog." "the_quick_brown_fox_jumps_over_the_lazy_dog", table); table = "default.MyTable"; ASSERT_OK(HmsCatalog::NormalizeTableName(&table)); EXPECT_EQ("default.mytable", table); } TEST(HmsCatalogStaticTest, TestParseUris) { vector<HostPort> hostports; EXPECT_OK(HmsCatalog::ParseUris("", &hostports)); EXPECT_TRUE(hostports.empty()); EXPECT_OK(HmsCatalog::ParseUris(",,,", &hostports)); EXPECT_TRUE(hostports.empty()); EXPECT_OK(HmsCatalog::ParseUris("thrift://foo-bar-baz:1234", &hostports)); EXPECT_EQ(hostports, vector<HostPort>({ HostPort("foo-bar-baz", 1234) })); EXPECT_OK(HmsCatalog::ParseUris("thrift://hms-1:1234,thrift://hms-2", &hostports)); EXPECT_EQ(hostports, vector<HostPort>( { HostPort("hms-1", 1234), HostPort("hms-2", HmsClient::kDefaultHmsPort) })); Status s = HmsCatalog::ParseUris("://illegal-scheme:12", &hostports); EXPECT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "missing scheme"); s = HmsCatalog::ParseUris("missing-scheme", &hostports); EXPECT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "missing scheme"); s = HmsCatalog::ParseUris("thrift://foo,missing-scheme:1234,thrift://baz", &hostports); EXPECT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "missing scheme"); } // Base class for HmsCatalog tests. Parameterized by whether // SASL/GSSAPI/Kerberos should be enabled. class HmsCatalogTest : public KuduTest { public: const char* const kMasterAddrs = "master-addrs"; const char* const kTableId = "abc123"; virtual bool EnableKerberos() { return false; } void SetUp() override { KuduTest::SetUp(); bool enable_kerberos = EnableKerberos(); thrift::ClientOptions hms_client_opts; hms_.reset(new hms::MiniHms()); if (enable_kerberos) { kdc_.reset(new MiniKdc(MiniKdcOptions())); ASSERT_OK(kdc_->Start()); // Create a service principal for the HMS, and configure it to use it. string spn = "hive/127.0.0.1"; string ktpath; ASSERT_OK(kdc_->CreateServiceKeytab(spn, &ktpath)); hms_->EnableKerberos(kdc_->GetEnvVars()["KRB5_CONFIG"], spn, ktpath, SaslProtection::kPrivacy); // Create a principal for the HmsCatalog, and configure it to use it. ASSERT_OK(rpc::SaslInit()); ASSERT_OK(kdc_->CreateUserPrincipal("alice")); ASSERT_OK(kdc_->Kinit("alice")); ASSERT_OK(kdc_->SetKrb5Environment()); hms_client_opts.enable_kerberos = true; hms_client_opts.service_principal = "hive"; // Configure the HmsCatalog flags. FLAGS_hive_metastore_sasl_enabled = true; } ASSERT_OK(hms_->Start()); hms_client_.reset(new HmsClient(hms_->address(), hms_client_opts)); ASSERT_OK(hms_client_->Start()); FLAGS_hive_metastore_uris = hms_->uris(); hms_catalog_.reset(new HmsCatalog(kMasterAddrs)); ASSERT_OK(hms_catalog_->Start()); } void TearDown() override { if (hms_client_) { ASSERT_OK(hms_client_->Stop()); } ASSERT_OK(hms_->Stop()); KuduTest::TearDown(); } Status StopHms() { RETURN_NOT_OK(hms_client_->Stop()); RETURN_NOT_OK(hms_->Stop()); return Status::OK(); } Status StartHms() { RETURN_NOT_OK(hms_->Start()); RETURN_NOT_OK(hms_client_->Start()); return Status::OK(); } Schema AllTypesSchema() { SchemaBuilder b; b.AddKeyColumn("key", DataType::INT32); b.AddColumn("int8_val", DataType::INT8); b.AddColumn("int16_val", DataType::INT16); b.AddColumn("int32_val", DataType::INT32); b.AddColumn("int64_val", DataType::INT64); b.AddColumn("timestamp_val", DataType::UNIXTIME_MICROS); b.AddColumn("string_val", DataType::STRING); b.AddColumn("bool_val", DataType::BOOL); b.AddColumn("float_val", DataType::FLOAT); b.AddColumn("double_val", DataType::DOUBLE); b.AddColumn("binary_val", DataType::BINARY); b.AddColumn("decimal32_val", DataType::DECIMAL32); b.AddColumn("decimal64_val", DataType::DECIMAL64); b.AddColumn("decimal128_val", DataType::DECIMAL128); return b.Build(); } void CheckTable(const string& database_name, const string& table_name, const string& table_id, const boost::optional<const string&>& owner, const Schema& schema) { hive::Table table; ASSERT_OK(hms_client_->GetTable(database_name, table_name, &table)); if (owner) { EXPECT_EQ(table.owner, *owner); } else { EXPECT_TRUE(table.owner.empty()); } EXPECT_EQ(table.parameters[HmsClient::kKuduTableIdKey], table_id); EXPECT_EQ(table.parameters[HmsClient::kKuduMasterAddrsKey], kMasterAddrs); EXPECT_EQ(table.parameters[HmsClient::kStorageHandlerKey], HmsClient::kKuduStorageHandler); for (int column_idx = 0; column_idx < schema.num_columns(); column_idx++) { EXPECT_EQ(table.sd.cols[column_idx].name, schema.columns()[column_idx].name()); } } Status CreateLegacyTable(const string& database_name, const string& table_name, const string& table_type) { hive::Table table; string kudu_table_name(table_name); table.dbName = database_name; table.tableName = table_name; table.tableType = table_type; if (table_type == HmsClient::kManagedTable) { kudu_table_name = Substitute("$0$1.$2", HmsClient::kLegacyTablePrefix, database_name, table_name); } table.__set_parameters({ make_pair(HmsClient::kStorageHandlerKey, HmsClient::kLegacyKuduStorageHandler), make_pair(HmsClient::kLegacyKuduTableNameKey, kudu_table_name), make_pair(HmsClient::kKuduMasterAddrsKey, kMasterAddrs), }); // TODO(Hao): Remove this once HIVE-19253 is fixed. if (table_type == HmsClient::kExternalTable) { table.parameters[HmsClient::kExternalTableKey] = "TRUE"; } return hms_client_->CreateTable(table); } void CheckTableDoesNotExist(const string& database_name, const string& table_name) { hive::Table table; Status s = hms_client_->GetTable(database_name, table_name, &table); ASSERT_TRUE(s.IsNotFound()) << s.ToString(); } protected: unique_ptr<MiniKdc> kdc_; unique_ptr<MiniHms> hms_; unique_ptr<HmsClient> hms_client_; unique_ptr<HmsCatalog> hms_catalog_; }; // Subclass of HmsCatalogTest that allows running individual test cases with // Kerberos enabled and disabled. Most of the test cases are run only with // Kerberos disabled, but to get coverage against a Kerberized HMS we run select // cases in both modes. class HmsCatalogTestParameterized : public HmsCatalogTest, public ::testing::WithParamInterface<bool> { bool EnableKerberos() override { return GetParam(); } }; INSTANTIATE_TEST_CASE_P(HmsCatalogTests, HmsCatalogTestParameterized, ::testing::Values(false, true)); // Test creating, altering, and dropping a table with the HMS Catalog. TEST_P(HmsCatalogTestParameterized, TestTableLifecycle) { const string kTableId = "table-id"; const string kHmsDatabase = "default"; const string kHmsTableName = "table_name"; const string kTableName = Substitute("$0.$1", kHmsDatabase, kHmsTableName); const string kHmsAlteredTableName = "altered_table_name"; const string kAlteredTableName = Substitute("$0.$1", kHmsDatabase, kHmsAlteredTableName); const string kOwner = "alice"; Schema schema = AllTypesSchema(); // Create the table. ASSERT_OK(hms_catalog_->CreateTable(kTableId, kTableName, kOwner, schema)); NO_FATALS(CheckTable(kHmsDatabase, kHmsTableName, kTableId, kOwner, schema)); // Create the table again, and check that the expected failure occurs. Status s = hms_catalog_->CreateTable(kTableId, kTableName, kOwner, schema); ASSERT_TRUE(s.IsAlreadyPresent()) << s.ToString(); NO_FATALS(CheckTable(kHmsDatabase, kHmsTableName, kTableId, kOwner, schema)); // Alter the table. SchemaBuilder b(schema); b.AddColumn("new_column", DataType::INT32); Schema altered_schema = b.Build(); ASSERT_OK(hms_catalog_->AlterTable(kTableId, kTableName, kAlteredTableName, altered_schema)); NO_FATALS(CheckTableDoesNotExist(kHmsDatabase, kHmsTableName)); NO_FATALS(CheckTable(kHmsDatabase, kHmsAlteredTableName, kTableId, kOwner, altered_schema)); // Drop the table. ASSERT_OK(hms_catalog_->DropTable(kTableId, kAlteredTableName)); NO_FATALS(CheckTableDoesNotExist(kHmsDatabase, kHmsTableName)); NO_FATALS(CheckTableDoesNotExist(kHmsDatabase, kHmsAlteredTableName)); } // Checks that Kudu tables will not replace or modify existing HMS entries that // belong to external tables from other systems. TEST_F(HmsCatalogTest, TestExternalTable) { const string kTableId = "table-id"; // Create the external table (default.ext). hive::Table external_table; external_table.dbName = "default"; external_table.tableName = "ext"; external_table.tableType = HmsClient::kManagedTable; ASSERT_OK(hms_client_->CreateTable(external_table)); // Retrieve the full HMS table object so it can be compared later (the HMS // fills in some fields during creation). ASSERT_OK(hms_client_->GetTable("default", "ext", &external_table)); auto CheckExternalTable = [&] { hive::Table current_table; ASSERT_OK(hms_client_->GetTable("default", "ext", &current_table)); ASSERT_EQ(current_table, external_table); }; // Create the Kudu table (default.a). Schema schema = AllTypesSchema(); ASSERT_OK(hms_catalog_->CreateTable(kTableId, "default.a", boost::none, schema)); NO_FATALS(CheckTable("default", "a", kTableId, boost::none, schema)); // Try and create a Kudu table with the same name as the external table. Status s = hms_catalog_->CreateTable(kTableId, "default.ext", boost::none, schema); EXPECT_TRUE(s.IsAlreadyPresent()) << s.ToString(); NO_FATALS(CheckExternalTable()); // Try and rename the Kudu table to the external table name. s = hms_catalog_->AlterTable(kTableId, "default.a", "default.ext", schema); EXPECT_TRUE(s.IsIllegalState()) << s.ToString(); NO_FATALS(CheckExternalTable()); NO_FATALS(CheckTable("default", "a", kTableId, boost::none, schema)); // Try and rename the external table. This shouldn't succeed because the Table // ID doesn't match. s = hms_catalog_->AlterTable(kTableId, "default.ext", "default.b", schema); EXPECT_TRUE(s.IsNotFound()) << s.ToString(); NO_FATALS(CheckExternalTable()); NO_FATALS(CheckTable("default", "a", kTableId, boost::none, schema)); NO_FATALS(CheckTableDoesNotExist("default", "b")); // Try and drop the external table as if it were a Kudu table. s = hms_catalog_->DropTable(kTableId, "default.ext"); EXPECT_TRUE(s.IsRemoteError()) << s.ToString(); NO_FATALS(CheckExternalTable()); // Drop a Kudu table with no corresponding HMS entry. NO_FATALS(CheckTableDoesNotExist("default", "bogus_table_name")); s = hms_catalog_->DropTable(kTableId, "default.bogus_table_name"); ASSERT_TRUE(s.IsNotFound()) << s.ToString(); NO_FATALS(CheckTableDoesNotExist("default", "bogus_table_name")); } TEST_F(HmsCatalogTest, TestGetKuduTables) { const string kHmsDatabase = "db"; const string kManagedTableName = "managed_table"; const string kExternalTableName = "external_table"; const string kTableName = "external_table"; const string kNonKuduTableName = "non_kudu_table"; const string kOwner = "alice"; // Create a legacy Impala managed table, a legacy Impala external table, a // Kudu table, and a non Kudu table. hive::Database db; db.name = "db"; ASSERT_OK(hms_client_->CreateDatabase(db)); ASSERT_OK(CreateLegacyTable("db", "managed_table", HmsClient::kManagedTable)); hive::Table table; ASSERT_OK(hms_client_->GetTable(kHmsDatabase, "managed_table", &table)); ASSERT_OK(CreateLegacyTable("db", "external_table", HmsClient::kExternalTable)); ASSERT_OK(hms_client_->GetTable("db", "external_table", &table)); ASSERT_OK(hms_catalog_->CreateTable("fake-id", "db.table", kOwner, Schema())); hive::Table non_kudu_table; non_kudu_table.dbName = "db"; non_kudu_table.tableName = "non_kudu_table"; ASSERT_OK(hms_client_->CreateTable(non_kudu_table)); ASSERT_OK(hms_client_->GetTable("db", "non_kudu_table", &table)); // Retrieve all tables and ensure all entries are found. vector<hive::Table> kudu_tables; ASSERT_OK(hms_catalog_->GetKuduTables(&kudu_tables)); ASSERT_EQ(3, kudu_tables.size()); for (const auto& kudu_table : kudu_tables) { ASSERT_FALSE(kudu_table.tableName == "non_kudu_table") << kudu_table; } } // Checks that the HmsCatalog handles reconnecting to the metastore after a connection failure. TEST_F(HmsCatalogTest, TestReconnect) { // TODO(dan): Figure out a way to test failover among HA HMS instances. The // MiniHms does not support HA, since it relies on a single-process Derby database. const string kTableId = "table-id"; const string kHmsDatabase = "default"; const string kOwner = "alice"; Schema schema = AllTypesSchema(); ASSERT_OK(hms_catalog_->CreateTable(kTableId, "default.a", kOwner, schema)); NO_FATALS(CheckTable(kHmsDatabase, "a", kTableId, kOwner, schema)); // Shutdown the HMS and try a few operations. ASSERT_OK(StopHms()); // TODO(dan): once we have HMS catalog stats, assert that repeated attempts // while the HMS is unavailable results in a non-linear number of reconnect // attempts. Status s = hms_catalog_->CreateTable(kTableId, "default.b", kOwner, schema); EXPECT_TRUE(s.IsNetworkError()) << s.ToString(); s = hms_catalog_->AlterTable(kTableId, "default.a", "default.c", schema); EXPECT_TRUE(s.IsNetworkError()) << s.ToString(); // Start the HMS back up and ensure that the same operations succeed. ASSERT_OK(StartHms()); ASSERT_EVENTUALLY([&] { // HmsCatalog throttles reconnections, so it's necessary to wait out the backoff. ASSERT_OK(hms_catalog_->CreateTable(kTableId, "default.d", kOwner, schema)); }); NO_FATALS(CheckTable(kHmsDatabase, "a", kTableId, kOwner, schema)); NO_FATALS(CheckTable(kHmsDatabase, "d", kTableId, kOwner, schema)); EXPECT_OK(hms_catalog_->AlterTable(kTableId, "default.a", "default.c", schema)); NO_FATALS(CheckTable(kHmsDatabase, "c", kTableId, kOwner, schema)); NO_FATALS(CheckTableDoesNotExist(kHmsDatabase, "a")); } } // namespace hms } // namespace kudu
module Test.Main import Data.List import Language.CSV import Text.Token test : (Eq a, Show a) => a -> a -> IO () test a b = if a == b then putStrLn "ok" else putStrLn $ "Expected " ++ show a ++ " but found " ++ show b parsesTo : String -> Maybe CSV -> IO () parsesTo s e = test e $ parse s lexesTo : String -> Maybe (List CSVToken) -> IO () lexesTo s e = test e $ lexCSV s parsesLexTo : List CSVToken -> Maybe CSV -> IO () parsesLexTo ts e = test e $ parseCSV ts comma : CSVToken comma = Tok Comma "," crlf : CSVToken crlf = Tok CRLF "\r\n" dQuote : CSVToken dQuote = Tok DQuote "\"" textData : String -> CSVToken textData s = Tok TextData s makeTokens : CSV -> List CSVToken makeTokens = let makeRecord : List String -> List CSVToken makeRecord = intersperse comma . map (Tok TextData) in concat . intersperse [crlf] . map makeRecord runTriplet : String -> List CSVToken -> CSV -> IO () runTriplet s t c = do putStrLn $ "Testing " ++ s putStr " Lexer: " lexesTo s $ Just t putStr " Parsing Token: " parsesLexTo t $ Just c putStr " Parsing: " parsesTo s $ Just c runDuplet : String -> CSV -> IO () runDuplet s c = runTriplet s (makeTokens c) c tests : IO () tests = do runDuplet "Hello" [["Hello"]] runDuplet "Hello,World" [["Hello", "World"]] runTriplet "Hello,World\r\n" [textData "Hello", comma, textData "World", crlf] [["Hello", "World"]] runTriplet "a,b\r\nc,d" [textData "a", comma, textData "b", crlf, textData "c", comma, textData "d"] [["a", "b"],["c","d"]] runTriplet "a,\"b\r\nc\",d" [textData "a", comma, dQuote, textData "b", crlf, textData "c", dQuote, comma, textData "d"] [["a", "b\r\nc","d"]] runTriplet "a,\"b\"" [textData "a", comma, dQuote, textData "b", dQuote] [["a", "b"]] main : IO () main = tests
State Before: α : Type u_1 β : Type ?u.289553 E : Type u_2 F : Type u_3 G : Type ?u.289562 E' : Type ?u.289565 F' : Type ?u.289568 G' : Type ?u.289571 E'' : Type ?u.289574 F'' : Type ?u.289577 G'' : Type ?u.289580 R : Type ?u.289583 R' : Type ?u.289586 𝕜 : Type ?u.289589 𝕜' : Type ?u.289592 inst✝¹² : Norm E inst✝¹¹ : Norm F inst✝¹⁰ : Norm G inst✝⁹ : SeminormedAddCommGroup E' inst✝⁸ : SeminormedAddCommGroup F' inst✝⁷ : SeminormedAddCommGroup G' inst✝⁶ : NormedAddCommGroup E'' inst✝⁵ : NormedAddCommGroup F'' inst✝⁴ : NormedAddCommGroup G'' inst✝³ : SeminormedRing R inst✝² : SeminormedRing R' inst✝¹ : NormedField 𝕜 inst✝ : NormedField 𝕜' c c' c₁ c₂ : ℝ f : α → E g : α → F k : α → G f' : α → E' g' : α → F' k' : α → G' f'' : α → E'' g'' : α → F'' k'' : α → G'' l l' : Filter α s : Set α ⊢ IsBigOWith c (𝓟 s) f g ↔ ∀ (x : α), x ∈ s → ‖f x‖ ≤ c * ‖g x‖ State After: α : Type u_1 β : Type ?u.289553 E : Type u_2 F : Type u_3 G : Type ?u.289562 E' : Type ?u.289565 F' : Type ?u.289568 G' : Type ?u.289571 E'' : Type ?u.289574 F'' : Type ?u.289577 G'' : Type ?u.289580 R : Type ?u.289583 R' : Type ?u.289586 𝕜 : Type ?u.289589 𝕜' : Type ?u.289592 inst✝¹² : Norm E inst✝¹¹ : Norm F inst✝¹⁰ : Norm G inst✝⁹ : SeminormedAddCommGroup E' inst✝⁸ : SeminormedAddCommGroup F' inst✝⁷ : SeminormedAddCommGroup G' inst✝⁶ : NormedAddCommGroup E'' inst✝⁵ : NormedAddCommGroup F'' inst✝⁴ : NormedAddCommGroup G'' inst✝³ : SeminormedRing R inst✝² : SeminormedRing R' inst✝¹ : NormedField 𝕜 inst✝ : NormedField 𝕜' c c' c₁ c₂ : ℝ f : α → E g : α → F k : α → G f' : α → E' g' : α → F' k' : α → G' f'' : α → E'' g'' : α → F'' k'' : α → G'' l l' : Filter α s : Set α ⊢ (∀ᶠ (x : α) in 𝓟 s, ‖f x‖ ≤ c * ‖g x‖) ↔ ∀ (x : α), x ∈ s → ‖f x‖ ≤ c * ‖g x‖ Tactic: rw [IsBigOWith_def] State Before: α : Type u_1 β : Type ?u.289553 E : Type u_2 F : Type u_3 G : Type ?u.289562 E' : Type ?u.289565 F' : Type ?u.289568 G' : Type ?u.289571 E'' : Type ?u.289574 F'' : Type ?u.289577 G'' : Type ?u.289580 R : Type ?u.289583 R' : Type ?u.289586 𝕜 : Type ?u.289589 𝕜' : Type ?u.289592 inst✝¹² : Norm E inst✝¹¹ : Norm F inst✝¹⁰ : Norm G inst✝⁹ : SeminormedAddCommGroup E' inst✝⁸ : SeminormedAddCommGroup F' inst✝⁷ : SeminormedAddCommGroup G' inst✝⁶ : NormedAddCommGroup E'' inst✝⁵ : NormedAddCommGroup F'' inst✝⁴ : NormedAddCommGroup G'' inst✝³ : SeminormedRing R inst✝² : SeminormedRing R' inst✝¹ : NormedField 𝕜 inst✝ : NormedField 𝕜' c c' c₁ c₂ : ℝ f : α → E g : α → F k : α → G f' : α → E' g' : α → F' k' : α → G' f'' : α → E'' g'' : α → F'' k'' : α → G'' l l' : Filter α s : Set α ⊢ (∀ᶠ (x : α) in 𝓟 s, ‖f x‖ ≤ c * ‖g x‖) ↔ ∀ (x : α), x ∈ s → ‖f x‖ ≤ c * ‖g x‖ State After: no goals Tactic: rfl
library(e1071) library(randomForest) library(pROC) library(ggplot2) library(caret) setwd("/Users/Colin/Desktop/Teamwork") Attr = c("Existing_checking_account", "Duration", "Credit_history", "Purpose", "Credit_amount", "Savings_account", "Present_employment", "Installment_rate", "Personal_status", "Other_debtors", "Present_residence", "Property", "Age", "Other_installment_plans", "Housing", "Existing_credits", "Job", "Liable_to_provide_maintenance", "Telephone", "Foreign_worker", "Credit") data = read.csv(file = "GermanCreditData.csv", header = TRUE, col.names = Attr ) data$Credit = as.factor(data$Credit) #resampling for a balance balance <- function(data,yval) { y.vector <- with(data,get(yval)) index.0 <- which(y.vector==1) index.1 <- which(y.vector==2) index.1 <- sample(index.1, length(index.0), replace = TRUE) result <- data[sample(c(index.0,index.1)),] result } data <- balance(data, "Credit") set.seed(12345) train_RowIDs = sample(1:nrow(data), nrow(data)*0.7) train_Data = data[train_RowIDs,] test_Data = data[-train_RowIDs,] table(data$Credit) table(train_Data$Credit) table(test_Data$Credit) model = svm(Credit ~ ., data = train_Data, type = "C-classification", kernel = "radial", # kernel = "linear", cost = 10, gamma = 0.1) summary(model) ind_train_data = train_Data[,1:20] pred_Train = predict(model, ind_train_data) cm_Train = table(train_Data$Credit, pred_Train) print(cm_Train) ind_test_data = test_Data[,1:20] pred_Test = predict(model, ind_test_data) cm_Test = table(test_Data$Credit, pred_Test) print(cm_Test) accu_Test= sum(diag(cm_Test))/sum(cm_Test) rf = randomForest(Credit ~ ., data = train_Data, importance = TRUE) DrawL<-par() par(mfrow=c(2,1),mar=c(5,5,3,1)) plot(rf,main="Random Forest Error VS Number of Decision Trees") plot(margin(rf),type="h",main="Margin Detection", xlab="Observations",ylab="Ration") rf1 = randomForest(Credit ~ ., data = train_Data, importance = TRUE, ntree = 140) importance(rf1,type=1) varImpPlot(x=rf1, sort=TRUE, n.var=nrow(rf$importance),main="Importance of Variables") rm(list = ls()) setwd("/Users/Colin/Desktop/Teamwork") Attr = c("Existing_checking_account", "Duration", "Credit_history", "Purpose", "Credit_amount", "Savings_account", "Present_employment", "Installment_rate", "Personal_status", "Other_debtors", "Present_residence", "Property", "Age", "Other_installment_plans", "Existing_credits", "Job", "Telephone", "Credit") data = read.csv(file = "Credit.csv", header = TRUE, col.names = Attr ) data$Credit = as.factor(data$Credit) #resampling for a balance balance <- function(data,yval) { y.vector <- with(data,get(yval)) index.0 <- which(y.vector==1) index.1 <- which(y.vector==2) index.1 <- sample(index.1, length(index.0), replace = TRUE) result <- data[sample(c(index.0,index.1)),] result } data <- balance(data, "Credit") set.seed(12345) train_RowIDs = sample(1:nrow(data), nrow(data)*0.7) train_Data = data[train_RowIDs,] test_Data = data[-train_RowIDs,] table(data$Credit) table(train_Data$Credit) table(test_Data$Credit) model = svm(Credit ~ ., data = train_Data, type = "C-classification", kernel = "radial", # kernel = "linear", cost = 100, gamma = 0.01) summary(model) ind_train_data = train_Data[,1:17] pred_Train = predict(model, ind_train_data) cm_Train = table(train_Data$Credit, pred_Train) print(cm_Train) ind_test_data = test_Data[,1:17] pred_Test = predict(model, ind_test_data) cm_Test = table(test_Data$Credit, pred_Test) print(cm_Test) accu_Test= sum(diag(cm_Test))/sum(cm_Test)
"gallinas" <- structure(list(provincia = structure(c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9), .Label = c("Avila", "Burgos", "Leon", "Palencia", "Salamanca", "Segovia", "Soria", "Valladolid", "Zamora"), class = "factor"), agno = structure(c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2), .Label = c("1999", "2000"), class = c("ordered", "factor")), tipo = structure(c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), .Label = c("camperas", "selectas" ), class = "factor"), cabezas = c(125, 146, 1463, 1465, 109, 110, 282, 330, 163, 176, 564, 559, 65, 62, 3652, 3652, 48, 48, 55, 40, 85, 80, 296, 285, 1, 1, 40, 26.3, 40, 38, 7, 6.5, 28, 28, 158, 152.9), hue.ave = c(285, 285, 250, 250, 252, 255, 265, 270, 250, 285, 250, 250, 250, 250, 265, 265, 295, 295, 150, 150, 160, 160, 165, 170, 164, 165, 150, 160, 160, 160, 150, 150, 150, 150, 205, 200), docenas = c(2969, 3477, 30479, 30520, 2289, 2338, 6228, 7425, 3400, 4166, 11750, 11646, 1354, 1299, 80654, 80654, 1189, 1189, 688, 500, 1133, 1066, 4070, 4038, 16, 17, 500, 351, 533, 507, 88, 82, 350, 350, 2694, 2550)), .Names = c("provincia", "agno", "tipo", "cabezas", "hue.ave", "docenas"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36"), class = "data.frame")
[STATEMENT] lemma wp_Seq: assumes ent_a: "P \<tturnstile> wp a Q" and ent_b: "Q \<tturnstile> wp b R" and wa: "well_def a" and wb: "well_def b" and s_Q: "sound Q" and s_R: "sound R" shows "P \<tturnstile> wp (a ;; b) R" [PROOF STATE] proof (prove) goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] note ha = well_def_wp_healthy[OF wa] [PROOF STATE] proof (state) this: healthy (wp a) goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] note hb = well_def_wp_healthy[OF wb] [PROOF STATE] proof (state) this: healthy (wp b) goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] note ent_a [PROOF STATE] proof (state) this: P \<tturnstile> wp a Q goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] also [PROOF STATE] proof (state) this: P \<tturnstile> wp a Q goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] from ent_b ha hb s_Q s_R [PROOF STATE] proof (chain) picking this: Q \<tturnstile> wp b R healthy (wp a) healthy (wp b) sound Q sound R [PROOF STEP] have "wp a Q \<tturnstile> wp a (wp b R)" [PROOF STATE] proof (prove) using this: Q \<tturnstile> wp b R healthy (wp a) healthy (wp b) sound Q sound R goal (1 subgoal): 1. wp a Q \<tturnstile> wp a (wp b R) [PROOF STEP] by(blast intro:healthy_monoD2) [PROOF STATE] proof (state) this: wp a Q \<tturnstile> wp a (wp b R) goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: P \<tturnstile> wp a (wp b R) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: P \<tturnstile> wp a (wp b R) goal (1 subgoal): 1. P \<tturnstile> wp (a ;; b) R [PROOF STEP] by(simp add:wp_eval) [PROOF STATE] proof (state) this: P \<tturnstile> wp (a ;; b) R goal: No subgoals! [PROOF STEP] qed
c general three-body stability algorithm c c system is unstable if nstab=1 is returned c system is stable if nstab=0 is returned c c Rosemary Mardling c School of Mathematical Sciences, Monash University c c version as of 16-11-07 c email [email protected] to be added to updates email list c preprint on astro-ph by New Year :-) c c sigma=period ratio (outer/inner) **should be > 1** c ai=inner semi-major axis c a0=outer semi-major axis c ei0=initial inner eccentricity c eo=outer eccentricity c relinc=relative inclination (radians) c m1, m2, m3=masses (any units; m3=outer body) c c valid for all inclinations c c MASS RATIO CONDITIONS c valid for systems with at least one of m_2/m_1>0.05 OR m_3/m_1>0.05 c (so that one could have, for example, m_2/m_1=0 and m_3/m_1=0.1) c OR BOTH m2/m1>0.01 AND m3/m1>0.01 c **future version will include other resonances to cover smaller mass ratios c c assumes resonance angle phi=0 because resonance overlap criterion doesn't recognize c instability outside separatrix. c c system is unstable if nstab=1 is returned c system is stable if nstab=0 is returned integer function nstab(ai,a0,ei0,eo,relinc,m1,m2,m3) implicit real*8 (a-h,m,o-z) common/params2/mm1,mm2,mm3 common/savepi/pi save itime data itime/0/ c reject outer pericentre inside inner apocentre if(a0*(1.-eo).lt.ai*(1.+ei0))then nstab=1 return endif if(itime.eq.0)then pi=4.d0*datan(1.0d0) itime=1 endif mm1=m1 mm2=m2 mm3=m3 m12=m1+m2 m123=m12+m3 c set period ratio (outer/inner) a0ai=a0/ai sigma=sqrt(a0ai**3*m12/m123) c do not allow period ratio < 1 if(sigma.lt.1.0)then nstab=1 return endif Mi2=m3/m123 Mo2=(m1*m2/m12**2)*(m12/m123)**(2./3.) Mi3=(m3/m12)*(m12/m123)**(4./3.)*(m1-m2)/m12 Mo3=(m1*m2/m12**2)*(m12/m123)*(m1-m2)/m12 c22=3./8. c20=0.25 c31=sqrt(3.)/4. c33=-sqrt(5.)/4. e=eo c inclination coefficients win=0 A=sqrt(1-ei0**2)*cos(relinc) Z=(1-ei0**2)*(1+sin(relinc)**2)+5*ei0**2* & (sin(win)*sin(relinc))**2 Del=z**2+25+16*A**4-10*Z-20*A**2-8*A**2*Z eK=sqrt(abs((Z+1-4*A**2+sqrt(Del))/6.)) cosIK=A/sqrt(1-eK**2) sinIK=sqrt(1-cosIK**2) gam222=0.25*(1+cosIK)**2 gam22m2=0.25*(1-cosIK)**2 gam220=0.5*sqrt(1.5)*sinIK**2 gam200=0.5*(3*cosIK**2-1) c induced inner eccentricity ei=ein_induced(sigma,ei0,e,relinc) c octopole emax if(m1.ne.m2)then eoctmax=eoct(sigma,ei0,e) ei=max(eoctmax,ei) endif ei=max(eK,ei) ei=min(ei,1.0d0) n=sigma nstab=0 c [n:1](222) resonance s221=-3*ei+(13./8.)*ei**3+(5./192.)*ei**5 f22n=flmn(2,2,n,e)/(1-e)**3 An=abs(6*c22*s221*f22n*(Mi2+Mo2*sigma**0.666)*gam222) phi=0 En=0.5*(sigma-n)**2-An*(1+cos(phi)) c [n+1:1](222) resonance f22n=flmn(2,2,n+1,e)/(1-e)**3 An=abs(6*c22*s221*f22n*(Mi2+Mo2*sigma**0.666)*gam222) Enp1=0.5*(sigma-(n+1))**2-An*(1+cos(phi)) if(En.lt.0.and.Enp1.lt.0)nstab=1 c [n:1](22-2) resonance s22m1=-(ei**3*(4480 + 1880*ei**2 + 1091*ei**4))/15360. f22n=flmn(2,2,n,e)/(1-e)**3 An=abs(6*c22*s22m1*f22n*(Mi2+Mo2*sigma**0.666)*gam22m2) phi=0 En=0.5*(sigma-n)**2-An*(1+cos(phi)) c [n+1:1](22-2) resonance f22n=flmn(2,2,n+1,e)/(1-e)**3 An=abs(6*c22*s22m1*f22n*(Mi2+Mo2*sigma**0.666)*gam22m2) Enp1=0.5*(sigma-(n+1))**2-An*(1+cos(phi)) if(En.lt.0.and.Enp1.lt.0)nstab=1 c [n:1](202) resonance s201=(ei*(-9216 + 1152*ei**2 - 48*ei**4 + ei**6))/9216. f22n=flmn(2,2,n,e)/(1-e)**3 An=abs(6*sqrt(c20*c22)*s201*f22n*(Mi2+Mo2*sigma**0.666)*gam220) phi=0 En=0.5*(sigma-n)**2-An*(1+cos(phi)) c [n+1:1](202) resonance f22n=flmn(2,2,n+1,e)/(1-e)**3 An=abs(6*sqrt(c20*c22)*s201*f22n*(Mi2+Mo2*sigma**0.666)*gam220) Enp1=0.5*(sigma-(n+1))**2-An*(1+cos(phi)) if(En.lt.0.and.Enp1.lt.0)nstab=1 c [n:1](002) resonance s201=(ei*(-9216 + 1152*ei**2 - 48*ei**4 + ei**6))/9216. f20n=flmn(2,0,n,e)/(1-e)**3 An=abs(3*c20*s201*f20n*(Mi2+Mo2*sigma**0.666)*gam200) phi=0 En=0.5*(sigma-n)**2-An*(1+cos(phi)) c [n+1:1](002) resonance f20n=flmn(2,0,n+1,e)/(1-e)**3 An=abs(3*c20*s201*f20n*(Mi2+Mo2*sigma**0.666)*gam200) Enp1=0.5*(sigma-(n+1))**2-An*(1+cos(phi)) if(En.lt.0.and.Enp1.lt.0)nstab=1 end c -------------------------------------------------------------------------- c Asymptotic expression for f^(lm)_n(e) for all e<1 and n. c real*8 function flmn(l,m,n,e) implicit real*8 (a-h,o-z) common/savepi/pi if(e.lt.5.e-3)then if(m.eq.n)then flmn=1 else flmn=0 endif return endif rho=n*(1-e)**1.5 xi=(acosh(1/e)-sqrt(1-e**2))/(1-e)**1.5 flmn=(1/(2*pi*n))*2.0**m*(sqrt(2*pi)/facfac(l,m))* . ((1+e)**(real(3*m-l-1)/4.)/e**m)* . (rho**(real(l+m+1)/2.))* . exp(-rho*xi) end c --------------------------------------------------------------------------- real*8 function ein_induced(sigma,ei0,e,relinc) implicit real*8 (a-h,m,o-z) common/params2/m1,m2,m3 common/savepi/pi m123=m1+m2+m3 n=sigma gam222=0.25*(1+cos(relinc))**2 gam220=0.5*sqrt(1.5)*sin(relinc)**2 gam200=0.5*(3*cos(relinc)**2-1) f22n=flmn(2,2,n,e)/(1-e)**3 f20n=flmn(2,0,n,e)/(1-e)**3 prod222=f22n*gam222 prod220=f22n*gam220 prod200=f20n*gam200 prod=max(prod222,prod220,prod200) a=4.5*(m3/m123)*(2*pi*n)*prod/sigma**2 ein_induced=sqrt(ei0**2+a**2) end c ------------------------------------------------------------------------------ c eoct.f c c calculates maximum eccentricity for arbitrary coplanar system c using Mardling (2007) MNRAS in press c real*8 function eoct(sigma,ei0,eo) implicit real*8 (a-h,m,o-z) common/params2/m1,m2,m3 common/savepi/pi m12=m1+m2 m123=m12+m3 aoai=((m123/m12)*sigma**2)**0.3333 al=1/aoai epso=sqrt(1-eo**2) eeq=1.25*al*eo/epso**2/abs(1-sqrt(al)*(m2/m3)/epso) AA=abs(1-ei0/eeq) if(AA.lt.1)then eoct=(1+AA)*eeq else eoct=ei0+2*eeq endif end c --------------------------------------------------------------------------- real*8 function acosh(x) real*8 x acosh=dlog(x+dsqrt(x**2-1.d0)) end c --------------------------------------------------------------------------- real*8 function sgn(x) real*8 x if(x.lt.0)then sgn=-1 else sgn=1 endif end c --------------------------------------------------------------------------- real*8 function facfac(l,m) implicit real*8 (a-h,o-z) prod=1 n=l+m-1 do i=1,n,2 prod=prod*i enddo facfac=prod end
module NamedImplementations import Data.List %default total -- named implementations allow us to have multiple implementations for a particular interface -- for a particular type. {- [name] Interface Type where func and then use as: func @{name} instead of the normal func -} [myord] Ord Nat where compare Z (S k) = GT compare (S k) Z = LT compare Z Z = EQ compare (S k) (S j) = compare @{myord} k j testList : List Nat testList = [3, 4, 1, 2, 3, 5, 4, 4, 5] normalSort : List Nat -> List Nat normalSort = sort reverseSort : List Nat -> List Nat reverseSort = sort @{myord} -- use the custom interface implementation with the name `myord` -- this is something that Haskell cannot do - and the reason why it has to define wrapper classes -- like `Sum` and `Product` in the Data.Monoid module. Named Implementations provides an elegant way -- out of this boilerplate. {- interface Semigroup ty where (<+>) : ty -> ty -> ty interface Semigroup ty => Monoid ty where neutral : ty -} [PlusNatSemi] Semigroup Nat where (<+>) x y = x + y [MultNatSemi] Semigroup Nat where (<+>) x y = x * y [PlusNatMonoid] Monoid Nat using PlusNatSemi where -- note the `using` clause neutral = 0 [MultNatMonoid] Monoid Nat using MultNatSemi where neutral = 1
import StaticArrays.SVector import Colors: RGB, distinguishable_colors import GeometryBasics: Point export Layer, PenPlot """ Represents a layer of a plot. A "layer" is a full pass of one pen. A layer has an associated color which is used for previewing the plot in the SVG export, but the color is not used by the plotting software. """ struct Layer name::String paths::MultiPath color::RGB end mutable struct LayerMaker num_layers::Int default_colors::Array{RGB,1} current_index::Int function LayerMaker(num_layers::Int) default_colors = distinguishable_colors(num_layers, lchoices = 0:40) new(num_layers, default_colors, 1) end end function makelayer(layer_maker::LayerMaker, layer::Layer) layer_maker.current_index += 1 layer end function makelayer(layer_maker::LayerMaker, paths::MultiPath) name = "$(layer_maker.current_index)-layer" color = layer_maker.default_colors[layer_maker.current_index] layer_maker.current_index += 1 Layer(name, paths, color) end function makelayer(layer_maker::LayerMaker, name_paths_pair::Pair{String,MultiPath}) color = layer_maker.default_colors[layer_maker.current_index] layer_maker.current_index += 1 Layer(name_paths_pair.first, name_paths_pair.second, color) end function makenotch(corner::Point, prev::Point, next::Point; frac=0.05) p1 = prev * frac + corner * (1-frac) p2 = corner p3 = next * frac + corner * (1-frac) Path([p1, p2, p3]) end """ A plot, consisting of one or more layers. Constructed with: PenPlot(layers...) Construct a pen plot consisting of the given layers. Layers may be: - [`Layer`](@ref) objects - [`MultiPath`](@ref) objects - `Pair{String, MultiPath}` objects, where the string becomes the name of the layer. """ struct PenPlot layers::Array{Layer} function PenPlot(layers...; addoutline=false) new_layers = [] layer_maker = LayerMaker(length(layers) + (addoutline ? 1 : 0)) new_layers = map(collect(layers)) do layerdata makelayer(layer_maker, layerdata) end plot = new(new_layers) if addoutline plx = extent(plot) upperright = Point(plx.lowerright[1], plx.upperleft[2]) lowerleft = Point(plx.upperleft[1], plx.lowerright[2]) outline = [ makenotch(plx.upperleft, lowerleft, upperright), makenotch(upperright, plx.upperleft, plx.lowerright), makenotch(plx.lowerright, upperright, lowerleft), makenotch(lowerleft, plx.lowerright, plx.upperleft), ] push!(plot.layers, makelayer(layer_maker, outline)) end plot end end
function varargout = process_report_email( varargin ) % PROCESS_REPORT_EMAIL: Send current process report by email. % % For calling this function from a script, use directly bst_report.m: % bst_report('Email', ReportFile, to, subject, isFullReport=1) % @============================================================================= % This function is part of the Brainstorm software: % https://neuroimage.usc.edu/brainstorm % % Copyright (c) University of Southern California & McGill University % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPLv3 % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % % Authors: Francois Tadel, 2021 eval(macro_method); end %% ===== GET DESCRIPTION ===== function sProcess = GetDescription() %#ok<DEFNU> % Description the process sProcess.Comment = 'Send report by email'; sProcess.Category = 'Custom'; sProcess.SubGroup = 'File'; sProcess.Index = 983; sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Scripting#Send_report_by_email'; % Definition of the input accepted by this process sProcess.InputTypes = {'raw', 'data', 'results', 'timefreq', 'matrix', 'dipoles', 'pdata', 'presults', 'ptimefreq', 'pmatrix', 'import'}; sProcess.OutputTypes = {'raw', 'data', 'results', 'timefreq', 'matrix', 'dipoles', 'pdata', 'presults', 'ptimefreq', 'pmatrix', 'import'}; sProcess.nInputs = 1; sProcess.nMinFiles = 0; sProcess.isSeparator = 1; % Definition of the options % === USERNAME sProcess.options.username.Comment = 'Brainstorm username: '; sProcess.options.username.Type = 'text'; sProcess.options.username.Value = ''; % === TO sProcess.options.cc.Comment = 'Send copy to (email address): '; sProcess.options.cc.Type = 'text'; sProcess.options.cc.Value = ''; % === SUBJECT sProcess.options.subject.Comment = 'Subject: '; sProcess.options.subject.Type = 'text'; sProcess.options.subject.Value = 'Process completed'; % === REPORTFILE sProcess.options.reportfile.Comment = 'ReportFile: '; sProcess.options.reportfile.Type = 'text'; sProcess.options.reportfile.Value = 'current'; sProcess.options.reportfile.Hidden = 1; % === FULL REPORT sProcess.options.full.Comment = 'Send full report'; sProcess.options.full.Type = 'checkbox'; sProcess.options.full.Value = 1; end %% ===== FORMAT COMMENT ===== function Comment = FormatComment(sProcess) %#ok<DEFNU> Comment = sProcess.Comment; end %% ===== RUN ===== function OutputFiles = Run(sProcess, sInputs) %#ok<DEFNU> % Returned files: same as input OutputFiles = {sInputs.FileName}; % Brainstorm username username = sProcess.options.username.Value; if isempty(username) bst_report('error', sProcess, [], 'Invalid Brainstorm username.'); return; end % CC address cc = sProcess.options.cc.Value; if ~isempty(cc) && ~any(cc == '@') bst_report('error', sProcess, [], 'Invalid email address.'); return; end % Email subject subject = sProcess.options.subject.Value; if isempty(subject) subject = 'Brainstorm report'; end % Report file reportfile = sProcess.options.reportfile.Value; % Full report isFullReport = sProcess.options.full.Value; % Send email [isOk, resp] = bst_report('Email', reportfile, username, cc, subject, isFullReport); % Error handling if ~isOk bst_report('Error', sProcess, [], ['Email could not be sent: ' 10 resp]); end end
(* Authors: Jose Divasón Sebastiaan Joosten René Thiemann Akihisa Yamada *) subsection \<open>Karatsuba's Multiplication Algorithm for Polynomials\<close> theory Karatsuba_Multiplication imports Polynomial_Interpolation.Missing_Polynomial begin lemma karatsuba_main_step: fixes f :: "'a :: comm_ring_1 poly" assumes f: "f = monom_mult n f1 + f0" and g: "g = monom_mult n g1 + g0" shows "monom_mult (n + n) (f1 * g1) + (monom_mult n (f1 * g1 - (f1 - f0) * (g1 - g0) + f0 * g0) + f0 * g0) = f * g" unfolding assms by (auto simp: field_simps mult_monom monom_mult_def) lemma karatsuba_single_sided: fixes f :: "'a :: comm_ring_1 poly" assumes "f = monom_mult n f1 + f0" shows "monom_mult n (f1 * g) + f0 * g = f * g" unfolding assms by (auto simp: field_simps mult_monom monom_mult_def) definition split_at :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a list \<times> 'a list" where [code del]: "split_at n xs = (take n xs, drop n xs)" lemma split_at_code[code]: "split_at n [] = ([],[])" "split_at n (x # xs) = (if n = 0 then ([], x # xs) else case split_at (n-1) xs of (bef,aft) \<Rightarrow> (x # bef, aft))" unfolding split_at_def by (force, cases n, auto) fun coeffs_minus :: "'a :: ab_group_add list \<Rightarrow> 'a list \<Rightarrow> 'a list" where "coeffs_minus (x # xs) (y # ys) = ((x - y) # coeffs_minus xs ys)" | "coeffs_minus xs [] = xs" | "coeffs_minus [] ys = map uminus ys" text \<open>The following constant determines at which size we will switch to the standard multiplication algorithm.\<close> definition karatsuba_lower_bound where [termination_simp]: "karatsuba_lower_bound = (7 :: nat)" fun karatsuba_main :: "'a :: comm_ring_1 list \<Rightarrow> nat \<Rightarrow> 'a list \<Rightarrow> nat \<Rightarrow> 'a poly" where "karatsuba_main f n g m = (if n \<le> karatsuba_lower_bound \<or> m \<le> karatsuba_lower_bound then let ff = poly_of_list f in foldr (\<lambda>a p. smult a ff + pCons 0 p) g 0 else let n2 = n div 2 in if m > n2 then (case split_at n2 f of (f0,f1) \<Rightarrow> case split_at n2 g of (g0,g1) \<Rightarrow> let p1 = karatsuba_main f1 (n - n2) g1 (m - n2); p2 = karatsuba_main (coeffs_minus f1 f0) n2 (coeffs_minus g1 g0) n2; p3 = karatsuba_main f0 n2 g0 n2 in monom_mult (n2 + n2) p1 + (monom_mult n2 (p1 - p2 + p3) + p3)) else case split_at n2 f of (f0,f1) \<Rightarrow> let p1 = karatsuba_main f1 (n - n2) g m; p2 = karatsuba_main f0 n2 g m in monom_mult n2 p1 + p2)" declare karatsuba_main.simps[simp del] lemma poly_of_list_split_at: assumes "split_at n f = (f0,f1)" shows "poly_of_list f = monom_mult n (poly_of_list f1) + poly_of_list f0" proof - from assms have id: "f1 = drop n f" "f0 = take n f" unfolding split_at_def by auto show ?thesis unfolding id proof (rule poly_eqI) fix i show "coeff (poly_of_list f) i = coeff (monom_mult n (poly_of_list (drop n f)) + poly_of_list (take n f)) i" unfolding monom_mult_def coeff_monom_mult coeff_add poly_of_list_def coeff_Poly by (cases "n \<le> i"; cases "i \<ge> length f", auto simp: nth_default_nth nth_default_beyond) qed qed lemma coeffs_minus: "poly_of_list (coeffs_minus f1 f0) = poly_of_list f1 - poly_of_list f0" proof (rule poly_eqI, unfold poly_of_list_def coeff_diff coeff_Poly) fix i show "nth_default 0 (coeffs_minus f1 f0) i = nth_default 0 f1 i - nth_default 0 f0 i" proof (induct f1 f0 arbitrary: i rule: coeffs_minus.induct) case (1 x xs y ys) thus ?case by (cases i, auto) next case (3 x xs) thus ?case unfolding coeffs_minus.simps by (subst nth_default_map_eq[of uminus 0 0], auto) qed auto qed definition karatsuba_mult_poly :: "'a :: comm_ring_1 poly \<Rightarrow> 'a poly \<Rightarrow> 'a poly" where "karatsuba_mult_poly f g = (let ff = coeffs f; gg = coeffs g; n = length ff; m = length gg in (if n \<le> karatsuba_lower_bound \<or> m \<le> karatsuba_lower_bound then if n \<le> m then foldr (\<lambda>a p. smult a g + pCons 0 p) ff 0 else foldr (\<lambda>a p. smult a f + pCons 0 p) gg 0 else if n \<le> m then karatsuba_main gg m ff n else karatsuba_main ff n gg m))" lemma karatsuba_mult_poly: "karatsuba_mult_poly f g = f * g" proof - note d = karatsuba_mult_poly_def Let_def let ?len = "length (coeffs f) \<le> length (coeffs g)" show ?thesis (is "?lhs = ?rhs") proof (cases "length (coeffs f) \<le> karatsuba_lower_bound \<or> length (coeffs g) \<le> karatsuba_lower_bound") case True note outer = this show ?thesis proof (cases ?len) case True with outer have "?lhs = foldr (\<lambda>a p. smult a g + pCons 0 p) (coeffs f) 0" unfolding d by auto also have "\<dots> = ?rhs" unfolding times_poly_def fold_coeffs_def by auto finally show ?thesis . next case False with outer have "?lhs = foldr (\<lambda>a p. smult a f + pCons 0 p) (coeffs g) 0" unfolding d by auto also have "\<dots> = g * f" unfolding times_poly_def fold_coeffs_def by auto also have "\<dots> = ?rhs" by simp finally show ?thesis . qed next case False note outer = this show ?thesis proof (cases ?len) case True with outer have "?lhs = karatsuba_main (coeffs g) (length (coeffs g)) (coeffs f) (length (coeffs f))" unfolding d by auto also have "\<dots> = g * f" unfolding karatsuba_main by auto also have "\<dots> = ?rhs" by auto finally show ?thesis . next case False with outer have "?lhs = karatsuba_main (coeffs f) (length (coeffs f)) (coeffs g) (length (coeffs g))" unfolding d by auto also have "\<dots> = ?rhs" unfolding karatsuba_main by auto finally show ?thesis . qed qed qed lemma karatsuba_mult_poly_code_unfold[code_unfold]: "(*) = karatsuba_mult_poly" by (intro ext, unfold karatsuba_mult_poly, auto) text \<open>The following declaration will resolve a race-conflict between @{thm karatsuba_mult_poly_code_unfold} and @{thm monom_mult_unfold}.\<close> lemmas karatsuba_monom_mult_code_unfold[code_unfold] = monom_mult_unfold[where f = "f :: 'a :: comm_ring_1 poly" for f, unfolded karatsuba_mult_poly_code_unfold] end
library(methods) library(data.table) {{rimport}}('__init__.r', 'plot.r') infile1 = {{i.infile1 | quote}} infile2 = {{i.infile2 | quote}} outdir = {{o.outdir | quote}} outfile = {{o.outfile | quote}} dopval = {{args.pval | R}} dofdr = {{args.fdr | R}} inopts1 = {{args.inopts1 | R}} inopts2 = {{args.inopts2 | R}} doplot = {{args.plot | R}} method = {{args.method | quote}} outfmt = {{args.outfmt | quote}} params = {{args.params | R}} ggs = {{args.ggs | R}} devpars = {{args.devpars | R}} indata1 = read.table.inopts(infile1, inopts1) indata2 = read.table.inopts(infile2, inopts2) len1 = ncol(indata1) len2 = ncol(indata2) indata = merge(indata1, indata2) rnames1 = rownames(indata1) rnames2 = rownames(indata2) if (is.null(rnames1)) rnames1 = paste0('R1_', 1:nrow(indata1)) if (is.null(rnames2)) rnames2 = paste0('R2_', 1:nrow(indata2)) rm(indata1, indata2) saveResults = function (corr, rnames1, rnames2, outfmt, outfile) { if (outfmt == 'pairs') { rownames(corr) = apply(merge(rnames1, rnames2), 1, function(row) paste(row, collapse = "\t")) write.table(corr, outfile, col.names = F, row.names = T, quote = F, sep = "\t") } else { corr = cbind(merge(rnames1, rnames2), corr = corr) corr = dcast(corr, x ~ y, value.var = 'corr') rownames(corr) = corr[, 1] corr = corr[, -1, drop = F] write.table(corr, outfile, col.names = T, row.names = T, quote = F, sep = "\t") } } if (!dopval && dofdr == F) { corr = apply(indata, 1, function(row) cor( row[1:len1], row[len1+1:len2], method = method )) corr = data.frame(corr = corr) saveResults(corr, rnames1, rnames2, outfmt, outfile) } else { corr0 = apply(indata, 1, function(row) cor.test( row[1:len1], row[len1+1:len2], method = method )) corr = data.frame(corr = sapply(corr0, function(x) x$estimate)) saveResults(corr, rnames1, rnames2, outfmt, outfile) pvals = sapply(corr0, function(x) x$p.value) corrp = data.frame(pval = sapply(corr0, function(x) x$p.value)) saveResults(corrp, rnames1, rnames2, outfmt, paste0(tools::file_path_sans_ext(outfile), '_pval.txt')) if (dofdr != F) { if (dofdr == T) dofdr = 'BH' qvals = p.adjust(pvals, method = dofdr) corrq = data.frame(qval = qvals) saveResults(corrp, rnames1, rnames2, outfmt, paste0(tools::file_path_sans_ext(outfile), '_qval.txt')) } } if (doplot) { outplot = paste0(tools::file_path_sans_ext(outfile), '.png') if (is.null(params$dendro)) params$dendro = F corr = cbind(merge(rnames1, rnames2), corr = corr) corr = dcast(corr, x ~ y, value.var = 'corr') rownames(corr) = corr[, 1] corr = corr[, -1, drop = F] #corr[lower.tri(corr)] = 0 ggs = c(list( theme = list( legend.position = c(0.03, 0.97), legend.justification = c("left", "top"), legend.title = element_text(margin = margin(b = 5)), legend.box.just = "right" ), guides = list( fill = guide_legend(title = paste0(toupper(substring(method, 1, 1)), substring(method, 2)), reverse = T) ) ), ggs) plot.heatmap(corr, outplot, params, ggs, devpars) }
function test_ipopt auxdata = {} ; options.lb = [ -Inf, -Inf ] ; % Lower bound on the variables. options.ub = [ Inf, Inf ] ; % Upper bound on the variables. % The constraint functions are bounded to zero options.cl = [ 0, 0, -Inf ]; % constraints options.cu = [ Inf, Inf, 0]; % Set up the auxiliary data. options.auxdata = auxdata ; % Set the IPOPT options. options.ipopt.jac_d_constant = 'no'; options.ipopt.hessian_constant = 'no'; options.ipopt.mu_strategy = 'adaptive'; options.ipopt.max_iter = 400; options.ipopt.tol = 1e-10; options.ipopt.linear_solver = 'ma57'; % The callback functions. funcs.objective = @objective; funcs.constraints = @constraints; funcs.gradient = @gradient; funcs.jacobian = @jacobian; funcs.jacobianstructure = @jacobianstructure; if false options.ipopt.derivative_test = 'first-order'; funcs.hessian = @hessian; funcs.hessianstructure = @hessianstructure; else options.ipopt.hessian_approximation = 'limited-memory'; %options.ipopt.limited_memory_update_type = 'bfgs' ; % {bfgs}, sr1 = 6; % {6} %options.ipopt.limited_memory_update_type = 'sr1' ; options.ipopt.limited_memory_update_type = 'bfgs' ; % {bfgs}, sr1 = 6; % {6} end % Run IPOPT. x0 = [-2, 1] ; tic [x, info] = ipopt_auxdata(x0,funcs,options); elapsed = toc ; info; x end %% % map the indices with the corresponding index in the spase matrix function f = objective(x,auxdata) f = 100*(x(2)-x(1)^2)^2+(1-x(1))^2 ; end %% % map the indices with the corresponding index in the spase matrix function g = gradient(x,auxdata) g = [ 400*x(1)*(x(1)^2-x(2))+2*x(1)-2, ... 200*(x(2)-x(1)^2) ] ; end function f = constraints(x,auxdata) f = zeros(3,1) ; f(1) = x(1)*x(2)-1 ; % = 0 f(2) = x(1) + x(2)^2 ; % >= 0 f(3) = x(1) ; end function jac = jacobian(x,auxdata) jac = sparse([ x(2), x(1) ; ... 1, 2*x(2) ; ... 1, 0 ]) ; end function jac = jacobianstructure(auxdata) jac = sparse(ones(3,2)) ; end function H = hessian(x, sigma, lambda, auxdata) H = sigma * [ 1200*x(1)^2-400*x(2)+2, 0 ; ... -400*x(1) 200] ; H = H + lambda(1) * [ 0 0 ; 1 0 ] ; H = H + lambda(2) * [ 0 0 ; 0 2 ] ; H = sparse(H) ; end function H = hessianstructure(auxdata) H = sparse([ 1 0 ; 1 1]) ; end
State Before: ι : Sort ?u.74934 α : Type u β : Type v inst✝¹ : PseudoMetricSpace α inst✝ : PseudoMetricSpace β s t u : Set α x y : α Φ : α → β ⊢ hausdorffDist s ∅ = 0 State After: case inl ι : Sort ?u.74934 α : Type u β : Type v inst✝¹ : PseudoMetricSpace α inst✝ : PseudoMetricSpace β s t u : Set α x y : α Φ : α → β h : s = ∅ ⊢ hausdorffDist s ∅ = 0 case inr ι : Sort ?u.74934 α : Type u β : Type v inst✝¹ : PseudoMetricSpace α inst✝ : PseudoMetricSpace β s t u : Set α x y : α Φ : α → β h : Set.Nonempty s ⊢ hausdorffDist s ∅ = 0 Tactic: cases' s.eq_empty_or_nonempty with h h State Before: case inl ι : Sort ?u.74934 α : Type u β : Type v inst✝¹ : PseudoMetricSpace α inst✝ : PseudoMetricSpace β s t u : Set α x y : α Φ : α → β h : s = ∅ ⊢ hausdorffDist s ∅ = 0 State After: no goals Tactic: simp [h] State Before: case inr ι : Sort ?u.74934 α : Type u β : Type v inst✝¹ : PseudoMetricSpace α inst✝ : PseudoMetricSpace β s t u : Set α x y : α Φ : α → β h : Set.Nonempty s ⊢ hausdorffDist s ∅ = 0 State After: no goals Tactic: simp [hausdorffDist, hausdorffEdist_empty h]
[GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ ⊢ ↑n / ↑1 = ↑n [PROOFSTEP] rw [Nat.cast_one, div_one] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℕ ⊢ ↑↑n = ↑n [PROOFSTEP] rw [← Int.cast_ofNat, cast_coe_int, Int.cast_ofNat] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α r : ℚ a : α ⊢ Commute (↑r) a [PROOFSTEP] simpa only [cast_def] using (r.1.cast_commute a).div_left (r.2.cast_commute a) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 ⊢ ↑(a /. b) = ↑a / ↑b [PROOFSTEP] have b0' : b ≠ 0 := by refine' mt _ b0 simp (config := { contextual := true }) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 ⊢ b ≠ 0 [PROOFSTEP] refine' mt _ b0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 ⊢ b = 0 → ↑b = 0 [PROOFSTEP] simp (config := { contextual := true }) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 ⊢ ↑(a /. b) = ↑a / ↑b [PROOFSTEP] cases' e : a /. b with n d h c [GOAL] case mk' F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d ⊢ ↑(mk' n d) = ↑a / ↑b [PROOFSTEP] have d0 : (d : α) ≠ 0 := by intro d0 have dd := den_dvd a b cases' show (d : ℤ) ∣ b by rwa [e] at dd with k ke have : (b : α) = (d : α) * (k : α) := by rw [ke, Int.cast_mul, Int.cast_ofNat] rw [d0, zero_mul] at this contradiction [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d ⊢ ↑d ≠ 0 [PROOFSTEP] intro d0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d = 0 ⊢ False [PROOFSTEP] have dd := den_dvd a b [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d = 0 dd : ↑(a /. b).den ∣ b ⊢ False [PROOFSTEP] cases' show (d : ℤ) ∣ b by rwa [e] at dd with k ke [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d = 0 dd : ↑(a /. b).den ∣ b ⊢ ↑d ∣ b [PROOFSTEP] rwa [e] at dd [GOAL] case intro F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d = 0 dd : ↑(a /. b).den ∣ b k : ℤ ke : b = ↑d * k ⊢ False [PROOFSTEP] have : (b : α) = (d : α) * (k : α) := by rw [ke, Int.cast_mul, Int.cast_ofNat] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d = 0 dd : ↑(a /. b).den ∣ b k : ℤ ke : b = ↑d * k ⊢ ↑b = ↑d * ↑k [PROOFSTEP] rw [ke, Int.cast_mul, Int.cast_ofNat] [GOAL] case intro F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d = 0 dd : ↑(a /. b).den ∣ b k : ℤ ke : b = ↑d * k this : ↑b = ↑d * ↑k ⊢ False [PROOFSTEP] rw [d0, zero_mul] at this [GOAL] case intro F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d = 0 dd : ↑(a /. b).den ∣ b k : ℤ ke : b = ↑d * k this : ↑b = 0 ⊢ False [PROOFSTEP] contradiction [GOAL] case mk' F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = mk' n d d0 : ↑d ≠ 0 ⊢ ↑(mk' n d) = ↑a / ↑b [PROOFSTEP] rw [num_den'] at e [GOAL] case mk' F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = n /. ↑d d0 : ↑d ≠ 0 ⊢ ↑(mk' n d) = ↑a / ↑b [PROOFSTEP] have := congr_arg ((↑) : ℤ → α) ((divInt_eq_iff b0' <| ne_of_gt <| Int.coe_nat_pos.2 h.bot_lt).1 e) [GOAL] case mk' F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = n /. ↑d d0 : ↑d ≠ 0 this : ↑(a * ↑d) = ↑(n * b) ⊢ ↑(mk' n d) = ↑a / ↑b [PROOFSTEP] rw [Int.cast_mul, Int.cast_mul, Int.cast_ofNat] at this [GOAL] case mk' F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = n /. ↑d d0 : ↑d ≠ 0 this : ↑a * ↑d = ↑n * ↑b ⊢ ↑(mk' n d) = ↑a / ↑b [PROOFSTEP] apply Eq.symm [GOAL] case mk'.h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α a b : ℤ b0 : ↑b ≠ 0 b0' : b ≠ 0 n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d e : a /. b = n /. ↑d d0 : ↑d ≠ 0 this : ↑a * ↑d = ↑n * ↑b ⊢ ↑a / ↑b = ↑(mk' n d) [PROOFSTEP] rw [cast_def, div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 ⊢ ↑(mk' n₁ d₁ + mk' n₂ d₂) = ↑(mk' n₁ d₁) + ↑(mk' n₂ d₂) [PROOFSTEP] have d₁0' : (d₁ : ℤ) ≠ 0 := Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₁0 ; exact d₁0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 e : d₁ = 0 ⊢ False [PROOFSTEP] rw [e] at d₁0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑0 ≠ 0 d₂0 : ↑d₂ ≠ 0 e : d₁ = 0 ⊢ False [PROOFSTEP] exact d₁0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 ⊢ ↑(mk' n₁ d₁ + mk' n₂ d₂) = ↑(mk' n₁ d₁) + ↑(mk' n₂ d₂) [PROOFSTEP] have d₂0' : (d₂ : ℤ) ≠ 0 := Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₂0 ; exact d₂0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 e : d₂ = 0 ⊢ False [PROOFSTEP] rw [e] at d₂0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑0 ≠ 0 d₁0' : ↑d₁ ≠ 0 e : d₂ = 0 ⊢ False [PROOFSTEP] exact d₂0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 ⊢ ↑(mk' n₁ d₁ + mk' n₂ d₂) = ↑(mk' n₁ d₁) + ↑(mk' n₂ d₂) [PROOFSTEP] rw [num_den', num_den', add_def'' d₁0' d₂0'] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 ⊢ ↑((n₁ * ↑d₂ + n₂ * ↑d₁) /. (↑d₁ * ↑d₂)) = ↑(n₁ /. ↑d₁) + ↑(n₂ /. ↑d₂) [PROOFSTEP] suffices (n₁ * (d₂ * ((d₂ : α)⁻¹ * (d₁ : α)⁻¹)) + n₂ * (d₁ * (d₂ : α)⁻¹) * (d₁ : α)⁻¹ : α) = n₁ * (d₁ : α)⁻¹ + n₂ * (d₂ : α)⁻¹ by rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero] · simpa [division_def, left_distrib, right_distrib, mul_inv_rev, d₁0, d₂0, mul_assoc] all_goals simp [d₁0, d₂0] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑((n₁ * ↑d₂ + n₂ * ↑d₁) /. (↑d₁ * ↑d₂)) = ↑(n₁ /. ↑d₁) + ↑(n₂ /. ↑d₂) [PROOFSTEP] rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑(n₁ * ↑d₂ + n₂ * ↑d₁) / ↑(↑d₁ * ↑d₂) = ↑n₁ / ↑↑d₁ + ↑n₂ / ↑↑d₂ [PROOFSTEP] simpa [division_def, left_distrib, right_distrib, mul_inv_rev, d₁0, d₂0, mul_assoc] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑↑d₂ ≠ 0 case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑↑d₁ ≠ 0 case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑(↑d₁ * ↑d₂) ≠ 0 [PROOFSTEP] all_goals simp [d₁0, d₂0] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑↑d₂ ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑↑d₁ ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ ⊢ ↑(↑d₁ * ↑d₂) ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 ⊢ ↑n₁ * (↑d₂ * ((↑d₂)⁻¹ * (↑d₁)⁻¹)) + ↑n₂ * (↑d₁ * (↑d₂)⁻¹) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ [PROOFSTEP] rw [← mul_assoc (d₂ : α), mul_inv_cancel d₂0, one_mul, (Nat.cast_commute _ _).eq] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 ⊢ ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * ((↑d₂)⁻¹ * ↑d₁) * (↑d₁)⁻¹ = ↑n₁ * (↑d₁)⁻¹ + ↑n₂ * (↑d₂)⁻¹ [PROOFSTEP] simp [d₁0, mul_assoc] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d ⊢ ↑(-mk' n d) = -↑(mk' n d) [PROOFSTEP] simpa only [cast_def] using show (↑(-n) / d : α) = -(n / d) by rw [div_eq_mul_inv, div_eq_mul_inv, Int.cast_neg, neg_mul_eq_neg_mul] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d ⊢ ↑(-n) / ↑d = -(↑n / ↑d) [PROOFSTEP] rw [div_eq_mul_inv, div_eq_mul_inv, Int.cast_neg, neg_mul_eq_neg_mul] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ m0 : ↑m.den ≠ 0 n0 : ↑n.den ≠ 0 ⊢ ↑(m - n) = ↑m - ↑n [PROOFSTEP] have : ((-n).den : α) ≠ 0 := by cases n; exact n0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ m0 : ↑m.den ≠ 0 n0 : ↑n.den ≠ 0 ⊢ ↑(-n).den ≠ 0 [PROOFSTEP] cases n [GOAL] case mk' F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m : ℚ m0 : ↑m.den ≠ 0 num✝ : ℤ den✝ : ℕ den_nz✝ : den✝ ≠ 0 reduced✝ : Nat.coprime (Int.natAbs num✝) den✝ n0 : ↑(mk' num✝ den✝).den ≠ 0 ⊢ ↑(-mk' num✝ den✝).den ≠ 0 [PROOFSTEP] exact n0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ m0 : ↑m.den ≠ 0 n0 : ↑n.den ≠ 0 this : ↑(-n).den ≠ 0 ⊢ ↑(m - n) = ↑m - ↑n [PROOFSTEP] simp [sub_eq_add_neg, cast_add_of_ne_zero m0 this] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 ⊢ ↑(mk' n₁ d₁ * mk' n₂ d₂) = ↑(mk' n₁ d₁) * ↑(mk' n₂ d₂) [PROOFSTEP] have d₁0' : (d₁ : ℤ) ≠ 0 := Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₁0 ; exact d₁0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 e : d₁ = 0 ⊢ False [PROOFSTEP] rw [e] at d₁0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑0 ≠ 0 d₂0 : ↑d₂ ≠ 0 e : d₁ = 0 ⊢ False [PROOFSTEP] exact d₁0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 ⊢ ↑(mk' n₁ d₁ * mk' n₂ d₂) = ↑(mk' n₁ d₁) * ↑(mk' n₂ d₂) [PROOFSTEP] have d₂0' : (d₂ : ℤ) ≠ 0 := Int.coe_nat_ne_zero.2 fun e => by rw [e] at d₂0 ; exact d₂0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 e : d₂ = 0 ⊢ False [PROOFSTEP] rw [e] at d₂0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑0 ≠ 0 d₁0' : ↑d₁ ≠ 0 e : d₂ = 0 ⊢ False [PROOFSTEP] exact d₂0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 ⊢ ↑(mk' n₁ d₁ * mk' n₂ d₂) = ↑(mk' n₁ d₁) * ↑(mk' n₂ d₂) [PROOFSTEP] rw [num_den', num_den', mul_def' d₁0' d₂0'] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 ⊢ ↑(n₁ * n₂ /. (↑d₁ * ↑d₂)) = ↑(n₁ /. ↑d₁) * ↑(n₂ /. ↑d₂) [PROOFSTEP] suffices (n₁ * (n₂ * (d₂ : α)⁻¹ * (d₁ : α)⁻¹) : α) = n₁ * ((d₁ : α)⁻¹ * (n₂ * (d₂ : α)⁻¹)) by rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero] · simpa [division_def, mul_inv_rev, d₁0, d₂0, mul_assoc] all_goals simp [d₁0, d₂0] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑(n₁ * n₂ /. (↑d₁ * ↑d₂)) = ↑(n₁ /. ↑d₁) * ↑(n₂ /. ↑d₂) [PROOFSTEP] rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑(n₁ * n₂) / ↑(↑d₁ * ↑d₂) = ↑n₁ / ↑↑d₁ * (↑n₂ / ↑↑d₂) [PROOFSTEP] simpa [division_def, mul_inv_rev, d₁0, d₂0, mul_assoc] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑↑d₂ ≠ 0 case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑↑d₁ ≠ 0 case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑(↑d₁ * ↑d₂) ≠ 0 [PROOFSTEP] all_goals simp [d₁0, d₂0] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑↑d₂ ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑↑d₁ ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 this : ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) ⊢ ↑(↑d₁ * ↑d₂) ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n₁ : ℤ d₁ : ℕ h₁ : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ h₂ : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁0 : ↑d₁ ≠ 0 d₂0 : ↑d₂ ≠ 0 d₁0' : ↑d₁ ≠ 0 d₂0' : ↑d₂ ≠ 0 ⊢ ↑n₁ * (↑n₂ * (↑d₂)⁻¹ * (↑d₁)⁻¹) = ↑n₁ * ((↑d₁)⁻¹ * (↑n₂ * (↑d₂)⁻¹)) [PROOFSTEP] rw [(d₁.commute_cast (_ : α)).inv_right₀.eq] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℕ ⊢ ↑(↑n)⁻¹ = (↑n)⁻¹ [PROOFSTEP] cases' n with n [GOAL] case zero F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α ⊢ ↑(↑Nat.zero)⁻¹ = (↑Nat.zero)⁻¹ [PROOFSTEP] simp [GOAL] case succ F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℕ ⊢ ↑(↑(Nat.succ n))⁻¹ = (↑(Nat.succ n))⁻¹ [PROOFSTEP] rw [cast_def, inv_coe_nat_num, inv_coe_nat_den, if_neg n.succ_ne_zero, Int.sign_eq_one_of_pos (Nat.cast_pos.mpr n.succ_pos), Int.cast_one, one_div] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ ⊢ ↑(↑n)⁻¹ = (↑n)⁻¹ [PROOFSTEP] cases' n with n n [GOAL] case ofNat F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℕ ⊢ ↑(↑(Int.ofNat n))⁻¹ = (↑(Int.ofNat n))⁻¹ [PROOFSTEP] simp [ofInt_eq_cast, cast_inv_nat] [GOAL] case negSucc F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℕ ⊢ ↑(↑(Int.negSucc n))⁻¹ = (↑(Int.negSucc n))⁻¹ [PROOFSTEP] simp only [ofInt_eq_cast, Int.cast_negSucc, ← Nat.cast_succ, cast_neg, inv_neg, cast_inv_nat] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 ⊢ ↑(mk' n d)⁻¹ = (↑(mk' n d))⁻¹ [PROOFSTEP] have _ : (n : ℤ) ≠ 0 := fun e => by rw [e] at n0 ; exact n0 Int.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 e : n = 0 ⊢ False [PROOFSTEP] rw [e] at n0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑0 ≠ 0 d0 : ↑d ≠ 0 e : n = 0 ⊢ False [PROOFSTEP] exact n0 Int.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 x✝ : n ≠ 0 ⊢ ↑(mk' n d)⁻¹ = (↑(mk' n d))⁻¹ [PROOFSTEP] have _ : (d : ℤ) ≠ 0 := Int.coe_nat_ne_zero.2 fun e => by rw [e] at d0 ; exact d0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 x✝ : n ≠ 0 e : d = 0 ⊢ False [PROOFSTEP] rw [e] at d0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑0 ≠ 0 x✝ : n ≠ 0 e : d = 0 ⊢ False [PROOFSTEP] exact d0 Nat.cast_zero [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 x✝¹ : n ≠ 0 x✝ : ↑d ≠ 0 ⊢ ↑(mk' n d)⁻¹ = (↑(mk' n d))⁻¹ [PROOFSTEP] rw [num_den', inv_def'] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 x✝¹ : n ≠ 0 x✝ : ↑d ≠ 0 ⊢ ↑(↑d /. n) = (↑(n /. ↑d))⁻¹ [PROOFSTEP] rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 x✝¹ : n ≠ 0 x✝ : ↑d ≠ 0 ⊢ ↑↑d ≠ 0 [PROOFSTEP] simp [n0, d0] [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α n : ℤ d : ℕ h : d ≠ 0 c : Nat.coprime (Int.natAbs n) d n0 : ↑n ≠ 0 d0 : ↑d ≠ 0 x✝¹ : n ≠ 0 x✝ : ↑d ≠ 0 ⊢ ↑n ≠ 0 [PROOFSTEP] simp [n0, d0] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 ⊢ ↑(m / n) = ↑m / ↑n [PROOFSTEP] have : (n⁻¹.den : ℤ) ∣ n.num := by conv in n⁻¹.den => rw [← @num_den n, inv_def'] apply den_dvd [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 ⊢ ↑n⁻¹.den ∣ n.num [PROOFSTEP] conv in n⁻¹.den => rw [← @num_den n, inv_def'] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 | n⁻¹.den [PROOFSTEP] rw [← @num_den n, inv_def'] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 | n⁻¹.den [PROOFSTEP] rw [← @num_den n, inv_def'] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 | n⁻¹.den [PROOFSTEP] rw [← @num_den n, inv_def'] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 ⊢ ↑(↑n.den /. n.num).den ∣ n.num [PROOFSTEP] apply den_dvd [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 this : ↑n⁻¹.den ∣ n.num ⊢ ↑(m / n) = ↑m / ↑n [PROOFSTEP] have : (n⁻¹.den : α) = 0 → (n.num : α) = 0 := fun h => by let ⟨k, e⟩ := this have := congr_arg ((↑) : ℤ → α) e; rwa [Int.cast_mul, Int.cast_ofNat, h, zero_mul] at this [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 this : ↑n⁻¹.den ∣ n.num h : ↑n⁻¹.den = 0 ⊢ ↑n.num = 0 [PROOFSTEP] let ⟨k, e⟩ := this [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 this : ↑n⁻¹.den ∣ n.num h : ↑n⁻¹.den = 0 k : ℤ e : n.num = ↑n⁻¹.den * k ⊢ ↑n.num = 0 [PROOFSTEP] have := congr_arg ((↑) : ℤ → α) e [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 this✝ : ↑n⁻¹.den ∣ n.num h : ↑n⁻¹.den = 0 k : ℤ e : n.num = ↑n⁻¹.den * k this : ↑n.num = ↑(↑n⁻¹.den * k) ⊢ ↑n.num = 0 [PROOFSTEP] rwa [Int.cast_mul, Int.cast_ofNat, h, zero_mul] at this [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝ : DivisionRing α m n : ℚ md : ↑m.den ≠ 0 nn : ↑n.num ≠ 0 nd : ↑n.den ≠ 0 this✝ : ↑n⁻¹.den ∣ n.num this : ↑n⁻¹.den = 0 → ↑n.num = 0 ⊢ ↑(m / n) = ↑m / ↑n [PROOFSTEP] rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ ⊢ ↑(mk' n₁ d₁) = ↑(mk' n₂ d₂) ↔ mk' n₁ d₁ = mk' n₂ d₂ [PROOFSTEP] refine' ⟨fun h => _, congr_arg _⟩ [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ h : ↑(mk' n₁ d₁) = ↑(mk' n₂ d₂) ⊢ mk' n₁ d₁ = mk' n₂ d₂ [PROOFSTEP] have d₁a : (d₁ : α) ≠ 0 := Nat.cast_ne_zero.2 d₁0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ h : ↑(mk' n₁ d₁) = ↑(mk' n₂ d₂) d₁a : ↑d₁ ≠ 0 ⊢ mk' n₁ d₁ = mk' n₂ d₂ [PROOFSTEP] have d₂a : (d₂ : α) ≠ 0 := Nat.cast_ne_zero.2 d₂0 [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ h : ↑(mk' n₁ d₁) = ↑(mk' n₂ d₂) d₁a : ↑d₁ ≠ 0 d₂a : ↑d₂ ≠ 0 ⊢ mk' n₁ d₁ = mk' n₂ d₂ [PROOFSTEP] rw [num_den', num_den'] at h ⊢ [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ h : ↑(n₁ /. ↑d₁) = ↑(n₂ /. ↑d₂) d₁a : ↑d₁ ≠ 0 d₂a : ↑d₂ ≠ 0 ⊢ n₁ /. ↑d₁ = n₂ /. ↑d₂ [PROOFSTEP] rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ h : ↑n₁ / ↑↑d₁ = ↑n₂ / ↑↑d₂ d₁a : ↑d₁ ≠ 0 d₂a : ↑d₂ ≠ 0 ⊢ n₁ /. ↑d₁ = n₂ /. ↑d₂ [PROOFSTEP] simp [d₁0, d₂0] at h ⊢ [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ h : ↑n₁ / ↑↑d₁ = ↑(n₂ /. ↑d₂) d₁a : ↑d₁ ≠ 0 d₂a : ↑d₂ ≠ 0 ⊢ ↑↑d₂ ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] at h ⊢ [GOAL] case b0 F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ h : ↑(n₁ /. ↑d₁) = ↑(n₂ /. ↑d₂) d₁a : ↑d₁ ≠ 0 d₂a : ↑d₂ ≠ 0 ⊢ ↑↑d₁ ≠ 0 [PROOFSTEP] simp [d₁0, d₂0] at h ⊢ [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n₁ : ℤ d₁ : ℕ d₁0 : d₁ ≠ 0 c₁ : Nat.coprime (Int.natAbs n₁) d₁ n₂ : ℤ d₂ : ℕ d₂0 : d₂ ≠ 0 c₂ : Nat.coprime (Int.natAbs n₂) d₂ d₁a : ↑d₁ ≠ 0 d₂a : ↑d₂ ≠ 0 h : ↑n₁ / ↑d₁ = ↑n₂ / ↑d₂ ⊢ mkRat n₁ d₁ = mkRat n₂ d₂ [PROOFSTEP] rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂ : α)).inv_left₀.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm, ← Int.cast_ofNat d₁, ← Int.cast_mul, ← Int.cast_ofNat d₂, ← Int.cast_mul, Int.cast_inj, ← mkRat_eq_iff d₁0 d₂0] at h [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n : ℚ ⊢ ↑n = 0 ↔ n = 0 [PROOFSTEP] rw [← cast_zero, cast_inj] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n : ℚ ⊢ ↑(bit1 n) = bit1 ↑n [PROOFSTEP] rw [bit1, cast_add, cast_one, cast_bit0] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α n : ℚ ⊢ bit0 ↑n + 1 = bit1 ↑n [PROOFSTEP] rfl [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝¹ : DivisionRing α inst✝ : CharZero α a b : ℤ ⊢ ↑(a /. b) = ↑a / ↑b [PROOFSTEP] simp only [divInt_eq_div, cast_div, cast_coe_int] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K r : ℚ hr : 0 < r ⊢ 0 < ↑r [PROOFSTEP] rw [Rat.cast_def] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K r : ℚ hr : 0 < r ⊢ 0 < ↑r.num / ↑r.den [PROOFSTEP] exact div_pos (Int.cast_pos.2 <| num_pos_iff_pos.2 hr) (Nat.cast_pos.2 r.pos) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K m n : ℚ ⊢ m < n → ↑m < ↑n [PROOFSTEP] simpa only [sub_pos, cast_sub] using @cast_pos_of_pos K _ (n - m) [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K n : ℚ ⊢ 0 ≤ ↑n ↔ 0 ≤ n [PROOFSTEP] norm_cast [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K n : ℚ ⊢ ↑n ≤ 0 ↔ n ≤ 0 [PROOFSTEP] norm_cast [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K n : ℚ ⊢ 0 < ↑n ↔ 0 < n [PROOFSTEP] norm_cast [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K n : ℚ ⊢ ↑n < 0 ↔ n < 0 [PROOFSTEP] norm_cast [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K q : ℚ ⊢ ↑|q| = |↑q| [PROOFSTEP] simp [abs_eq_max_neg] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b : ℚ ⊢ Rat.cast ⁻¹' Icc ↑a ↑b = Icc a b [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Icc ↑a ↑b ↔ x ∈ Icc a b [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b : ℚ ⊢ Rat.cast ⁻¹' Ico ↑a ↑b = Ico a b [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Ico ↑a ↑b ↔ x ∈ Ico a b [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b : ℚ ⊢ Rat.cast ⁻¹' Ioc ↑a ↑b = Ioc a b [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Ioc ↑a ↑b ↔ x ∈ Ioc a b [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b : ℚ ⊢ Rat.cast ⁻¹' Ioo ↑a ↑b = Ioo a b [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a b x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Ioo ↑a ↑b ↔ x ∈ Ioo a b [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a : ℚ ⊢ Rat.cast ⁻¹' Ici ↑a = Ici a [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Ici ↑a ↔ x ∈ Ici a [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a : ℚ ⊢ Rat.cast ⁻¹' Iic ↑a = Iic a [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Iic ↑a ↔ x ∈ Iic a [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a : ℚ ⊢ Rat.cast ⁻¹' Ioi ↑a = Ioi a [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Ioi ↑a ↔ x ∈ Ioi a [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a : ℚ ⊢ Rat.cast ⁻¹' Iio ↑a = Iio a [PROOFSTEP] ext x [GOAL] case h F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : LinearOrderedField K a x : ℚ ⊢ x ∈ Rat.cast ⁻¹' Iio ↑a ↔ x ∈ Iio a [PROOFSTEP] simp [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 inst✝² : DivisionRing α inst✝¹ : DivisionRing β inst✝ : RingHomClass F α β f : F q : ℚ ⊢ ↑f ↑q = ↑q [PROOFSTEP] rw [cast_def, map_div₀, map_intCast, map_natCast, cast_def] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 k : Type u_5 inst✝¹ : DivisionRing k inst✝ : RingHomClass F ℚ k f : F r : ℚ ⊢ ↑f r = ↑r [PROOFSTEP] rw [← map_ratCast f, Rat.cast_id] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M₀ : Type u_5 inst✝¹ : MonoidWithZero M₀ inst✝ : MonoidWithZeroHomClass F ℚ M₀ f g : F h : ∀ (m : ℤ), ↑f ↑m = ↑g ↑m r : ℚ ⊢ ↑f r = ↑g r [PROOFSTEP] rw [← r.num_div_den, div_eq_mul_inv, map_mul, map_mul, h, ← Int.cast_ofNat, eq_on_inv₀ f g] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M₀ : Type u_5 inst✝¹ : MonoidWithZero M₀ inst✝ : MonoidWithZeroHomClass F ℚ M₀ f g : F h : ∀ (m : ℤ), ↑f ↑m = ↑g ↑m r : ℚ ⊢ ↑f ↑↑r.den = ↑g ↑↑r.den [PROOFSTEP] apply h [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M₀ : Type u_5 inst✝¹ : MonoidWithZero M₀ inst✝ : MonoidWithZeroHomClass F ℚ M₀ f g : F same_on_neg_one : ↑f (-1) = ↑g (-1) same_on_pnat : ∀ (n : ℕ), 0 < n → ↑f ↑n = ↑g ↑n ⊢ ↑(comp ↑f ↑(Int.castRingHom ℚ)) (-1) = ↑(comp ↑g ↑(Int.castRingHom ℚ)) (-1) [PROOFSTEP] simpa [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 M₀ : Type u_5 inst✝¹ : MonoidWithZero M₀ inst✝ : MonoidWithZeroHomClass F ℚ M₀ f g : F same_on_neg_one : ↑f (-1) = ↑g (-1) same_on_pnat : ∀ (n : ℕ), 0 < n → ↑f ↑n = ↑g ↑n ⊢ ∀ (n : ℕ), 0 < n → ↑(comp ↑f ↑(Int.castRingHom ℚ)) ↑n = ↑(comp ↑g ↑(Int.castRingHom ℚ)) ↑n [PROOFSTEP] simpa [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : DivisionRing K a : ℚ ⊢ a • 0 = 0 [PROOFSTEP] rw [smul_def, mul_zero] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : DivisionRing K a : ℚ x y : K ⊢ a • (x + y) = a • x + a • y [PROOFSTEP] rw [smul_def, smul_def, smul_def, mul_add] [GOAL] F : Type u_1 ι : Type u_2 α : Type u_3 β : Type u_4 K : Type u_5 inst✝ : DivisionRing K a : ℚ x y : K ⊢ (a • x) • y = a • x • y [PROOFSTEP] simp only [smul_def, smul_eq_mul, mul_assoc]
Logical is an old DOS falling blocks puzzle game developed by Rainbow Arts in 1991 from an original idea by Thomas Scholl. Logical can be enjoyed in single player mode. It's available for download. Tell others what you think about Logical: did you play it? Did you like it or hate it? If you have problems running Logical, please read the F.A.Q. first. Your e-mail will NEVER be used for spam.
[STATEMENT] lemma asymmetric_cong: assumes r: "\<And>a b. a \<in> A \<Longrightarrow> b \<in> A \<Longrightarrow> r a b \<longleftrightarrow> r' a b" shows "asymmetric A r \<longleftrightarrow> asymmetric A r'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. asymmetric A r = asymmetric A r' [PROOF STEP] by (simp add: asymmetric_iff_irreflexive_antisymmetric r cong: irreflexive_cong antisymmetric_cong)
(** ** Kripke Semantics *) Require Import Undecidability.FOL.Semantics.Tarski.FragmentFacts. Require Export Undecidability.FOL.Semantics.Tarski.FragmentCore. Require Export Undecidability.FOL.Syntax.Facts. From Undecidability Require Import Shared.ListAutomation. Import ListAutomationNotations. Local Set Implicit Arguments. Local Unset Strict Implicit. Local Notation vec := Vector.t. #[local] Ltac comp := repeat (progress (cbn in *; autounfold in *)). Section Kripke. Context {Σ_funcs : funcs_signature}. Context {Σ_preds : preds_signature}. Section Model. Variable domain : Type. Class kmodel := { nodes : Type ; reachable : nodes -> nodes -> Prop ; reach_refl u : reachable u u ; reach_tran u v w : reachable u v -> reachable v w -> reachable u w ; k_interp : interp domain ; k_P : nodes -> forall P : preds, Vector.t domain (ar_preds P) -> Prop ; (* k_Bot : nodes -> Prop ; *) mon_P : forall u v, reachable u v -> forall P (t : Vector.t domain (ar_preds P)), k_P u t -> k_P v t; }. Variable M : kmodel. Fixpoint ksat {ff : falsity_flag} u (rho : nat -> domain) (phi : form) : Prop := match phi with | atom P v => k_P u (Vector.map (@eval _ _ _ k_interp rho) v) | falsity => False | bin Impl phi psi => forall v, reachable u v -> ksat v rho phi -> ksat v rho psi | quant All phi => forall j : domain, ksat u (j .: rho) phi end. Lemma ksat_mon {ff : falsity_flag} (u : nodes) (rho : nat -> domain) (phi : form) : forall v (H : reachable u v), ksat u rho phi -> ksat v rho phi. Proof. revert rho. induction phi; intros rho v' H; cbn; try destruct b0; try destruct q; intuition; eauto using mon_P, reach_tran. Qed. Lemma ksat_iff {ff : falsity_flag} u rho phi : ksat u rho phi <-> forall v (H : reachable u v), ksat v rho phi. Proof. split. - intros H1 v H2. eapply ksat_mon; eauto. - intros H. apply H. eapply reach_refl. Qed. End Model. Notation "rho '⊩(' u ')' phi" := (ksat _ u rho phi) (at level 20). Notation "rho '⊩(' u , M ')' phi" := (@ksat _ M _ u rho phi) (at level 20). Arguments ksat {_ _ _} _ _ _, _ _ _ _ _ _. Hint Resolve reach_refl : core. Section Substs. Variable D : Type. Context {M : kmodel D}. Lemma ksat_ext {ff : falsity_flag} u rho xi phi : (forall x, rho x = xi x) -> rho ⊩(u,M) phi <-> xi ⊩(u,M) phi. Proof. induction phi as [ | b P v | | ] in rho, xi, u |-*; intros Hext; comp. - tauto. - erewrite Vector.map_ext. reflexivity. intros t. now apply eval_ext. - destruct b0; split; intros H v Hv Hv'; now apply (IHphi2 v rho xi Hext), (H _ Hv), (IHphi1 v rho xi Hext). - destruct q; split; intros H d; apply (IHphi _ (d .: rho) (d .: xi)). all: ((intros []; cbn; congruence) + auto). Qed. Lemma ksat_comp {ff : falsity_flag} u rho xi phi : rho ⊩(u,M) phi[xi] <-> (xi >> eval rho (I := @k_interp _ M)) ⊩(u,M) phi. Proof. induction phi as [ | b P v | | ] in rho, xi, u |-*; comp. - tauto. - erewrite Vector.map_map. erewrite Vector.map_ext. 2: apply eval_comp. reflexivity. - destruct b0. setoid_rewrite IHphi1. now setoid_rewrite IHphi2. - destruct q. setoid_rewrite IHphi. split; intros H d; eapply ksat_ext. 2, 4: apply (H d). all: intros []; cbn; trivial; unfold funcomp; now erewrite eval_comp. Qed. End Substs. Context {ff : falsity_flag}. Definition kvalid_theo (T : form -> Prop) phi := forall D (M : kmodel D) u rho, (forall psi, T psi -> ksat u rho psi) -> ksat u rho phi. Definition kvalid_ctx A phi := forall D (M : kmodel D) u rho, (forall psi, psi el A -> ksat u rho psi) -> ksat u rho phi. Definition kvalid phi := forall D (M : kmodel D) u rho, ksat u rho phi. Definition ksatis phi := exists D (M : kmodel D) u rho, ksat u rho phi. End Kripke. Notation "rho '⊩(' u ')' phi" := (ksat u rho phi) (at level 20). Notation "rho '⊩(' u , M ')' phi" := (@ksat _ _ _ M _ u rho phi) (at level 20). Arguments ksat {_ _ _ _ _} _ _ _, {_ _ _} _ {_} _ _ _. Section Bottom. Context {Σ_funcs : funcs_signature}. Context {Σ_preds : preds_signature}. Context {domain : Type}. Context {M : kmodel domain}. Program Definition kmodel_bot (F_P : @nodes _ _ _ M -> Prop) (mon_F : forall u v, reachable u v -> F_P u -> F_P v) : @kmodel Σ_funcs (@Σ_preds_bot Σ_preds) domain := {| nodes := @nodes _ _ _ M ; reachable := @reachable _ _ _ M ; k_interp := interp_bot False (@k_interp _ _ _ M) ; k_P := fun n P => match P with inl _ => fun _ => F_P n | inr P' => @k_P _ _ _ M n P' end |}. Next Obligation. apply reach_refl. Qed. Next Obligation. now apply reach_tran with v. Qed. Next Obligation. destruct P as [|P']. + now apply mon_F with u. + now apply mon_P with u. Qed. Definition ksat_bot {ff : falsity_flag} (F_P : @nodes _ _ _ M -> Prop) (mon_F : forall u v, reachable u v -> F_P u -> F_P v) u (rho : env domain) (phi : form) : Prop := @ksat _ Σ_preds_bot domain (kmodel_bot mon_F) falsity_off u rho (falsity_to_pred phi). Arguments ksat_bot {_} _ _ _ _. Lemma sat_bot_False {ff:falsity_flag} u rho phi (e : forall u v, reachable u v -> False -> False) : @ksat_bot ff (fun _ => False) e u rho phi <-> @ksat _ _ domain M ff u rho phi. Proof. induction phi in rho,u|-*. - easy. - easy. - destruct b0. unfold sat_bot, falsity_to_pred in *. cbn. split; intros H v Hreach H1 %IHphi1; apply IHphi2; now apply H, H1. - destruct q. unfold sat_bot, falsity_to_pred in *. cbn. split; intros H d; apply IHphi, H. Qed. End Bottom. Arguments ksat_bot {_} {_} {_} {_} {_} _ _ _ _. Section BottomDef. Context {Σ_funcs : funcs_signature}. Context {Σ_preds : preds_signature}. Context {ff : falsity_flag}. Definition kexploding D (M : kmodel D) F_P mon_F := forall v rho phi, ksat_bot F_P mon_F v rho (⊥ → phi). Arguments kexploding _ _ _ _ : clear implicits. Definition kvalid_exploding_ctx A phi := forall D (M : kmodel D) F_P mon_F u rho, kexploding D M F_P mon_F -> (forall psi, psi el A -> ksat_bot F_P mon_F u rho psi) -> ksat_bot F_P mon_F u rho phi. Definition kvalid_exploding phi := forall D (M : kmodel D) F_P mon_F u rho, kexploding D M F_P mon_F -> ksat_bot F_P mon_F u rho phi. Definition ksatis_exploding phi := exists D (M : kmodel D) F_P mon_F u rho, kexploding D M F_P mon_F /\ ksat_bot F_P mon_F u rho phi. End BottomDef.
{-# OPTIONS --without-K --rewriting #-} open import lib.Basics open import lib.types.Group open import lib.types.Pi open import lib.NType2 open import lib.types.Paths open import lib.types.EilenbergMacLane1.Core module lib.types.EilenbergMacLane1.FunElim where module _ {i} {G : Group i} where private module G = Group G module EM₁Level₁FunElim {j k} {B : EM₁ G → Type j} {C : EM₁ G → Type k} {{C-level : has-level 1 (C embase)}} (embase* : B embase → C embase) (emloop* : ∀ g b → transport C (emloop g) (embase* b) == embase* (transport B (emloop g) b)) (emloop-comp* : ∀ g₁ g₂ b → emloop* (G.comp g₁ g₂) b ◃∙ ap (λ p → embase* (transport B p b)) (emloop-comp g₁ g₂) ◃∙ ap embase* (transp-∙ (emloop g₁) (emloop g₂) b) ◃∎ =ₛ ap (λ p → transport C p (embase* b)) (emloop-comp g₁ g₂) ◃∙ transp-∙ (emloop g₁) (emloop g₂) (embase* b) ◃∙ ap (transport C (emloop g₂)) (emloop* g₁ b) ◃∙ emloop* g₂ (transport B (emloop g₁) b) ◃∎) where emloop** : ∀ g → embase* == embase* [ (λ x → B x → C x) ↓ emloop g ] emloop** g = ↓-→-from-transp (λ= (emloop* g)) private emloop-comp** : ∀ g₁ g₂ → emloop** (G.comp g₁ g₂) == emloop** g₁ ∙ᵈ emloop** g₂ [ (λ p → embase* == embase* [ (λ x → B x → C x) ↓ p ]) ↓ emloop-comp g₁ g₂ ] emloop-comp** g₁ g₂ = step₁ ▹ step₂ where intermediate' : ∀ b → transport C (emloop g₁ ∙ emloop g₂) (embase* b) == embase* (transport B (emloop g₁ ∙ emloop g₂) b) intermediate' = comp-transp {B = B} {C = C} {u = embase*} {u' = embase*} {u'' = embase*} (emloop g₁) (emloop g₂) (λ= (emloop* g₁)) (λ= (emloop* g₂)) intermediate : embase* == embase* [ (λ x → B x → C x) ↓ emloop g₁ ∙ emloop g₂ ] intermediate = ↓-→-from-transp (λ= intermediate') step₁'' : ∀ b → app= (λ= (emloop* (G.comp g₁ g₂))) b ◃∙ app= (ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂)) b ◃∎ =ₛ app= (ap (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂)) b ◃∙ app= (λ= intermediate') b ◃∎ step₁'' b = app= (λ= (emloop* (G.comp g₁ g₂))) b ◃∙ app= (ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂)) b ◃∎ =ₛ₁⟨ 0 & 1 & app=-β (emloop* (G.comp g₁ g₂)) b ⟩ emloop* (G.comp g₁ g₂) b ◃∙ app= (ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂)) b ◃∎ =ₛ₁⟨ 1 & 1 & ∘-ap (_$ b) (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂) ⟩ emloop* (G.comp g₁ g₂) b ◃∙ ap (λ p → embase* (transport B p b)) (emloop-comp g₁ g₂) ◃∎ =ₛ⟨ post-rotate-in {p = _ ◃∙ _ ◃∎} (emloop-comp* g₁ g₂ b) ⟩ ap (λ p → transport C p (embase* b)) (emloop-comp g₁ g₂) ◃∙ transp-∙ (emloop g₁) (emloop g₂) (embase* b) ◃∙ ap (transport C (emloop g₂)) (emloop* g₁ b) ◃∙ emloop* g₂ (transport B (emloop g₁) b) ◃∙ ! (ap embase* (transp-∙ (emloop g₁) (emloop g₂) b)) ◃∎ =ₛ₁⟨ 2 & 1 & ap (ap (transport C (emloop g₂))) (! (app=-β (emloop* g₁) b)) ⟩ ap (λ p → transport C p (embase* b)) (emloop-comp g₁ g₂) ◃∙ transp-∙ (emloop g₁) (emloop g₂) (embase* b) ◃∙ ap (transport C (emloop g₂)) (app= (λ= (emloop* g₁)) b) ◃∙ emloop* g₂ (transport B (emloop g₁) b) ◃∙ ! (ap embase* (transp-∙ (emloop g₁) (emloop g₂) b)) ◃∎ =ₛ₁⟨ 3 & 1 & ! (app=-β (emloop* g₂) (transport B (emloop g₁) b)) ⟩ ap (λ p → transport C p (embase* b)) (emloop-comp g₁ g₂) ◃∙ transp-∙ (emloop g₁) (emloop g₂) (embase* b) ◃∙ ap (transport C (emloop g₂)) (app= (λ= (emloop* g₁)) b) ◃∙ app= (λ= (emloop* g₂)) (transport B (emloop g₁) b) ◃∙ ! (ap embase* (transp-∙ (emloop g₁) (emloop g₂) b)) ◃∎ =ₛ⟨ 1 & 4 & contract ⟩ ap (λ p → transport C p (embase* b)) (emloop-comp g₁ g₂) ◃∙ intermediate' b ◃∎ =ₛ₁⟨ 0 & 1 & ap-∘ (_$ b) (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂) ⟩ app= (ap (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂)) b ◃∙ intermediate' b ◃∎ =ₛ₁⟨ 1 & 1 & ! (app=-β intermediate' b) ⟩ app= (ap (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂)) b ◃∙ app= (λ= intermediate') b ◃∎ ∎ₛ step₁' : λ= (emloop* (G.comp g₁ g₂)) ∙ ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂) == ap (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂) ∙ λ= intermediate' step₁' = –>-is-inj (app=-equiv {A = B embase} {P = λ _ → C embase} {f = transport C (emloop (G.comp g₁ g₂)) ∘ embase*} {g = embase* ∘ transport B (emloop g₁ ∙ emloop g₂)}) _ _ $ λ= $ λ b → app= (λ= (emloop* (G.comp g₁ g₂)) ∙ ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂)) b =⟨ ap-∙ (_$ b) (λ= (emloop* (G.comp g₁ g₂))) (ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂)) ⟩ app= (λ= (emloop* (G.comp g₁ g₂))) b ∙ app= (ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂)) b =⟨ =ₛ-out (step₁'' b) ⟩ app= (ap (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂)) b ∙ app= (λ= intermediate') b =⟨ ∙-ap (_$ b) (ap (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂)) (λ= intermediate') ⟩ app= (ap (λ p → transport C p ∘ embase*) (emloop-comp g₁ g₂) ∙ λ= intermediate') b =∎ step₁ : emloop** (G.comp g₁ g₂) == intermediate [ (λ p → embase* == embase* [ (λ x → B x → C x) ↓ p ]) ↓ emloop-comp g₁ g₂ ] step₁ = ap↓ ↓-→-from-transp $ ↓-='-in $ ∙'=∙ (λ= (emloop* (G.comp g₁ g₂))) (ap (λ p → embase* ∘ transport B p) (emloop-comp g₁ g₂)) ∙ step₁' step₂ : intermediate == emloop** g₁ ∙ᵈ emloop** g₂ step₂ = ↓-→-from-transp-∙ᵈ {B = B} {C = C} {p = emloop g₁} {q = emloop g₂} {u = embase*} {u' = embase*} {u'' = embase*} (λ= (emloop* g₁)) (λ= (emloop* g₂)) module M = EM₁Level₁Elim {P = λ x → B x → C x} {{EM₁-prop-elim {P = λ x → has-level 1 (B x → C x)} {{λ x → has-level-is-prop}} (Π-level {B = λ _ → C embase} (λ _ → C-level))}} embase* emloop** emloop-comp** open M public
// (C) Copyright Edward Diener 2011-2015 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #if !defined(BOOST_VMD_DETAIL_SETUP_HPP) #define BOOST_VMD_DETAIL_SETUP_HPP #include <boost/preprocessor/config/config.hpp> #if defined(BOOST_VMD_MSVC) #undef BOOST_VMD_MSVC #endif #if defined(BOOST_VMD_MSVC_V8) #undef BOOST_VMD_MSVC_V8 #endif #if BOOST_PP_VARIADICS #define BOOST_VMD_MSVC BOOST_PP_VARIADICS_MSVC #if BOOST_VMD_MSVC && defined(_MSC_VER) && _MSC_VER == 1400 #define BOOST_VMD_MSVC_V8 1 #else #define BOOST_VMD_MSVC_V8 0 #endif /* BOOST_VMD_MSVC && defined(_MSC_VER) && _MSC_VER == 1400 */ #if !defined(BOOST_VMD_ASSERT_DATA) #if defined(NDEBUG) #define BOOST_VMD_ASSERT_DATA 0 #else #define BOOST_VMD_ASSERT_DATA 1 #endif /* NDEBUG */ #endif /* BOOST_VMD_ASSERT_DATA */ #else #define BOOST_VMD_MSVC 0 #define BOOST_VMD_MSVC_V8 0 #if defined(BOOST_VMD_ASSERT_DATA) #undef BOOST_VMD_ASSERT_DATA #endif #define BOOST_VMD_ASSERT_DATA 0 #endif /* BOOST_PP_VARIADICS */ #endif /* BOOST_VMD_DETAIL_SETUP_HPP */
make_upper_unitriangular := proc(n,p) local G,i,j,k,m,g,L,f; m := n * (n - 1) / 2; G := table(): G["p"] := p; G["id"] := IdentityMatrix(n); G["o"] := (g,h) -> map(mods,g . h,G["p"]); G["inv"] := g -> map(mods,1/g,G["p"]); G["order"] := p ^ m; G["elementary"] := table(): for i from 1 to n do for j from i+1 to n do g := Matrix(n,n); for k from 1 to n do g[k,k] := 1; od: g[i,j] := 1; G["elementary"][i,j] := g; od: od: L := [[]]; for i from 1 to m do L := [seq(seq([op(u),j],j=0..p-1),u in L)]; od: f := proc(u) local i,j,k,g; g := Matrix(n,n); for k from 1 to n do g[k,k] := 1; od: k := 1; for i from 1 to n do for j from i+1 to n do g[i,j] := mods(u[k],p); k := k + 1; od: od: return g; end: G["elements"] := map(f,L); return eval(G); end:
\section{Motivating Example} \label{sec:example}
module System.Random import Data.Fin import Data.Vect import Data.List public export interface Random a where randomIO : HasIO io => io a ||| Takes a range (lo, hi), and returns a random value uniformly ||| distributed in the closed interval [lo, hi]. It is unspecified what ||| happens if lo > hi. randomRIO : HasIO io => (a, a) -> io a %foreign "scheme:blodwen-random" "javascript:lambda:(max)=>Math.floor(Math.random() * max)" prim__randomBits32 : Bits32 -> PrimIO Bits32 randomBits32 : Bits32 -> IO Bits32 randomBits32 upperBound = fromPrim (prim__randomBits32 upperBound) public export Random Int32 where -- Generate a random value within [-2^31, 2^31-1]. randomIO = do let maxInt : Bits32 = 2147483647 -- shiftL 1 31 - 1 negMinInt : Bits32 = 2147483648 -- negate $ shiftL 1 31 magnitude : Bits32 = maxInt + negMinInt bits32 <- liftIO $ randomBits32 magnitude let int : Integer = cast bits32 pure . cast $ int - (cast negMinInt) -- Generate a random value within [lo, hi]. randomRIO (lo, hi) = let range : Integer = (cast hi) - (cast lo) + 1 in pure . cast $ !(liftIO . randomBits32 $ cast range) + cast lo %foreign "scheme:blodwen-random" "javascript:lambda:()=>Math.random()" prim__randomDouble : PrimIO Double randomDouble : IO Double randomDouble = fromPrim prim__randomDouble public export Random Double where -- Generate a random value within [0, 1]. randomIO = liftIO randomDouble -- Generate a random value within [lo, hi]. randomRIO (lo, hi) = map ((+ lo) . (* (hi - lo))) (liftIO randomDouble) %foreign "scheme:blodwen-random-seed" prim__srand : Bits64 -> PrimIO () ||| Sets the random seed export srand : Bits64 -> IO () srand n = fromPrim (prim__srand n) ||| Generate a random number in Fin (S `k`) ||| ||| Note that rndFin k takes values 0, 1, ..., k. public export rndFin : HasIO io => (n : Nat) -> io (Fin (S n)) rndFin 0 = pure FZ rndFin (S k) = do let intBound = the Int32 (cast (S k)) randomInt <- randomRIO (0, intBound) pure $ restrict (S k) (cast randomInt) ||| Select a random element from a vector public export rndSelect' : HasIO io => {k : Nat} -> Vect (S k) a -> io a rndSelect' xs = pure $ Vect.index !(rndFin k) xs ||| Select a random element from a non-empty list public export rndSelect : HasIO io => (elems : List a) -> (0 _ : NonEmpty elems) => io a rndSelect (x :: xs) = rndSelect' $ fromList (x :: xs)
Formal statement is: lemma mult_poly_0_left: "(0::'a poly) * q = 0" Informal statement is: The product of a polynomial and the zero polynomial is the zero polynomial.
open import MJ.Types import MJ.Classtable.Core as Core module MJ.Syntax.Program {c}(Ct : Core.Classtable c) where open import Prelude open import Data.List open import MJ.Classtable.Code Ct open import MJ.Syntax Ct Prog : Ty c → Set Prog a = Code × (Body [] a)
State Before: ι : Type ?u.6644 α : Type u_1 m : MeasurableSpace α μ : Measure α s t u v : Set α ⊢ AEDisjoint μ (s ∪ t) u ↔ AEDisjoint μ s u ∧ AEDisjoint μ t u State After: no goals Tactic: simp [union_eq_iUnion, and_comm]