Datasets:
AI4M
/

text
stringlengths
0
3.34M
[STATEMENT] lemma set_less_eq_aux_empty [simp]: "A \<sqsubseteq>' {} \<longleftrightarrow> A = {}" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (A \<sqsubseteq>' {}) = (A = {}) [PROOF STEP] by(auto simp add: set_less_eq_aux_def finite_complement_partition)
Require Import Hask.Data.Functor. Generalizable All Variables. Definition Const (c a : Set) := c. Program Instance Const_Functor (c : Set) : Functor (Const c) := { fmap := fun _ _ _ => id }.
import argparse import logging import os from pathlib import Path from typing import List, Tuple import numpy from bfio import BioReader from bfio import BioWriter from preadator import ProcessManager import ftl from ftl_rust import PolygonSet POLUS_LOG = getattr(logging, os.environ.get('POLUS_LOG', 'INFO')) POLUS_EXT = os.environ.get('POLUS_EXT', '.ome.tif') # TODO: Figure out how to use this # Initialize the logger logging.basicConfig( format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', ) logger = logging.getLogger("main") logger.setLevel(POLUS_LOG) def get_output_name(filename: str) -> str: name = filename.split('.ome')[0] return f'{name}{POLUS_EXT}' def filter_by_size(file_paths: List[Path], size_threshold: int) -> Tuple[List[Path], List[Path]]: """ Partitions the input files by the memory-footprint for the images. Args: file_paths: The list of files to partition. size_threshold: The memory-size (in MB) to use as a threshold. Returns: A 2-tuple of lists of paths. The first list contains small images and the second list contains large images. """ small_files, large_files = list(), list() threshold: int = size_threshold * 1024 * 1024 for file_path in file_paths: with BioReader(file_path) as reader: num_pixels = numpy.prod(reader.shape) dtype = reader.dtype if dtype in (numpy.uint8, bool): pixel_bytes = 8 elif dtype == numpy.uint16: pixel_bytes = 16 elif dtype == numpy.uint32: pixel_bytes = 32 else: pixel_bytes = 64 image_size = num_pixels * (pixel_bytes / 8) # Convert bits to bytes (small_files if image_size <= threshold else large_files).append(file_path) return small_files, large_files def label_cython(input_path: Path, output_path: Path, connectivity: int): """ Label the input image and writes labels back out. Args: input_path: Path to input image. output_path: Path for output image. connectivity: Connectivity kind. """ with ProcessManager.thread() as active_threads: with BioReader( input_path, max_workers=active_threads.count, ) as reader: with BioWriter( output_path, max_workers=active_threads.count, metadata=reader.metadata, ) as writer: # Load an image and convert to binary image = numpy.squeeze(reader[..., 0, 0]) if not numpy.any(image): writer.dtype = numpy.uint8 writer[:] = numpy.zeros_like(image, dtype=numpy.uint8) return image = (image > 0) if connectivity > image.ndim: ProcessManager.log( f'{input_path.name}: Connectivity is not less than or equal to the number of image dimensions, ' f'skipping this image. connectivity={connectivity}, ndim={image.ndim}' ) return # Run the labeling algorithm labels = ftl.label_nd(image, connectivity) # Save the image writer.dtype = labels.dtype writer[:] = labels return True if __name__ == "__main__": # Setup the argument parsing logger.info("Parsing arguments...") parser = argparse.ArgumentParser( prog='main', description='Label objects in a 2d or 3d binary image.', ) parser.add_argument( '--inpDir', dest='inpDir', type=str, required=True, help='Input image collection to be processed by this plugin', ) parser.add_argument( '--connectivity', dest='connectivity', type=str, required=True, help='City block connectivity, must be less than or equal to the number of dimensions', ) parser.add_argument( '--outDir', dest='outDir', type=str, required=True, help='Output collection', ) # Parse the arguments args = parser.parse_args() _connectivity = int(args.connectivity) logger.info(f'connectivity = {_connectivity}') _input_dir = Path(args.inpDir).resolve() assert _input_dir.exists(), f'{_input_dir } does not exist.' if _input_dir.joinpath('images').is_dir(): _input_dir = _input_dir.joinpath('images') logger.info(f'inpDir = {_input_dir}') _output_dir = Path(args.outDir).resolve() assert _output_dir.exists(), f'{_output_dir } does not exist.' logger.info(f'outDir = {_output_dir}') # We only need a thread manager since labeling and image reading/writing # release the gil ProcessManager.init_threads() # Get all file names in inpDir image collection _files = list(filter( lambda _file: _file.is_file() and _file.name.endswith('.ome.tif'), _input_dir.iterdir() )) _small_files, _large_files = filter_by_size(_files, 500) logger.info(f'processing {len(_files)} images in total...') logger.info(f'processing {len(_small_files)} small images with cython...') logger.info(f'processing {len(_large_files)} large images with rust') if _small_files: for _infile in _small_files: ProcessManager.submit_thread( label_cython, _infile, _output_dir.joinpath(get_output_name(_infile.name)), _connectivity, ) ProcessManager.join_threads() if _large_files: for _infile in _large_files: _outfile = _output_dir.joinpath(get_output_name(_infile.name)) PolygonSet(_connectivity).read_from(_infile).write_to(_outfile)
(* Author: Tobias Nipkow Copyright 1994 TU Muenchen *) section \<open>Quicksort with function package\<close> theory Quicksort imports "HOL-Library.Multiset" begin context linorder begin fun quicksort :: "'a list \<Rightarrow> 'a list" where "quicksort [] = []" | "quicksort (x#xs) = quicksort [y\<leftarrow>xs. \<not> x\<le>y] @ [x] @ quicksort [y\<leftarrow>xs. x\<le>y]" lemma quicksort_permutes [simp]: "mset (quicksort xs) = mset xs" by (induct xs rule: quicksort.induct) (simp_all add: ac_simps) lemma set_quicksort [simp]: "set (quicksort xs) = set xs" proof - have "set_mset (mset (quicksort xs)) = set_mset (mset xs)" by simp then show ?thesis by (simp only: set_mset_mset) qed lemma sorted_quicksort: "sorted (quicksort xs)" by (induct xs rule: quicksort.induct) (auto simp add: sorted_Cons sorted_append not_le less_imp_le) theorem sort_quicksort: "sort = quicksort" by (rule ext, rule properties_for_sort) (fact quicksort_permutes sorted_quicksort)+ end end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Max manipulability index ALONG A LINE. % Use stomp like to optimize along a surface/line %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function experiment2B_K20_N30 close all; global parameters %STOMP PARAMETERS %number of particles K = 20; %repeat experiment number of times parameters.n_repeat = 30; parameters.experiment_name = 'experiment2B_K20_N30.mat'; parameters.animate = 0; %repeat the experiment E times random_manips=[]; Gout = []; for i=1:parameters.n_repeat close all [pk, final_manip] = path_planning_SCO_4DOF(K); Gout{i}=pk; random_manips = [random_manips; final_manip]; save(parameters.experiment_name) end 'ended' parameters.experiment_name
#include "quantum_gates.h" #include "quac_p.h" #include <stdlib.h> #include <stdio.h> #include <petsc.h> #include <stdarg.h> int _num_quantum_gates = 0; int _current_gate = 0; struct quantum_gate_struct _quantum_gate_list[MAX_GATES]; int _min_gate_enum = 5; // Minimum gate enumeration number int _gate_array_initialized = 0; int _num_circuits = 0; int _current_circuit = 0; circuit _circuit_list[MAX_GATES]; void (*_get_val_j_functions_gates[MAX_GATES])(PetscInt,struct quantum_gate_struct,PetscInt*,PetscInt[],PetscScalar[],PetscInt); /* EventFunction is one step in Petsc to apply some action at a specific time. * This function checks to see if an event has happened. */ PetscErrorCode _QG_EventFunction(TS ts,PetscReal t,Vec U,PetscScalar *fvalue,void *ctx) { /* Check if the time has passed a gate */ if (_current_gate<_num_quantum_gates) { /* We signal that we passed the time by returning a negative number */ fvalue[0] = _quantum_gate_list[_current_gate].time - t; } else { fvalue[0] = t; } return(0); } /* PostEventFunction is the other step in Petsc. If an event has happend, petsc will call this function * to apply that event. */ PetscErrorCode _QG_PostEventFunction(TS ts,PetscInt nevents,PetscInt event_list[],PetscReal t, Vec U,PetscBool forward,void* ctx) { /* We only have one event at the moment, so we do not need to branch. * If we had more than one event, we would put some logic here. */ if (nevents) { /* Apply the current gate */ //Deprecated? /* _apply_gate(_quantum_gate_list[_current_gate].my_gate_type,_quantum_gate_list[_current_gate].qubit_numbers,U); */ /* Increment our gate counter */ _current_gate = _current_gate + 1; } TSSetSolution(ts,U); return(0); } /* EventFunction is one step in Petsc to apply some action at a specific time. * This function checks to see if an event has happened. */ PetscErrorCode _QC_EventFunction(TS ts,PetscReal t,Vec U,PetscScalar *fvalue,void *ctx) { /* Check if the time has passed a gate */ PetscInt current_gate,num_gates; PetscLogEventBegin(_qc_event_function_event,0,0,0,0); if (_current_circuit<_num_circuits) { current_gate = _circuit_list[_current_circuit].current_gate; num_gates = _circuit_list[_current_circuit].num_gates; if (current_gate<num_gates) { /* We signal that we passed the time by returning a negative number */ fvalue[0] = _circuit_list[_current_circuit].gate_list[current_gate].time +_circuit_list[_current_circuit].start_time - t; } else { if (nid==0){ printf("ERROR! current_gate should never be larger than num_gates in _QC_EventFunction\n"); exit(0); } } } else { fvalue[0] = t; } PetscLogEventEnd(_qc_event_function_event,0,0,0,0); return(0); } /* PostEventFunction is the other step in Petsc. If an event has happend, petsc will call this function * to apply that event. */ PetscErrorCode _QC_PostEventFunction(TS ts,PetscInt nevents,PetscInt event_list[], PetscReal t,Vec U,PetscBool forward,void* ctx) { PetscInt current_gate,num_gates; PetscReal gate_time; /* We only have one event at the moment, so we do not need to branch. * If we had more than one event, we would put some logic here. */ PetscLogEventBegin(_qc_postevent_function_event,0,0,0,0); if (nevents) { num_gates = _circuit_list[_current_circuit].num_gates; current_gate = _circuit_list[_current_circuit].current_gate; gate_time = _circuit_list[_current_circuit].gate_list[current_gate].time; /* Apply all gates at a given time incrementally */ while (current_gate<num_gates && _circuit_list[_current_circuit].gate_list[current_gate].time == gate_time){ /* apply the current gate */ printf("current_gate %d num_gates %d\n",current_gate,num_gates); _apply_gate(_circuit_list[_current_circuit].gate_list[current_gate],U); /* Increment our gate counter */ _circuit_list[_current_circuit].current_gate = _circuit_list[_current_circuit].current_gate + 1; current_gate = _circuit_list[_current_circuit].current_gate; } if(_circuit_list[_current_circuit].current_gate>=_circuit_list[_current_circuit].num_gates){ /* We've exhausted this circuit; move on to the next. */ _current_circuit = _current_circuit + 1; } } TSSetSolution(ts,U); PetscLogEventEnd(_qc_postevent_function_event,0,0,0,0); return(0); } /* Add a gate to the list */ void add_gate(PetscReal time,gate_type my_gate_type,...) { int num_qubits=0,qubit,i; va_list ap; if (my_gate_type==HADAMARD) { num_qubits = 1; } else if (my_gate_type==CNOT){ num_qubits = 2; } else { if (nid==0){ printf("ERROR! Gate type not recognized!\n"); exit(0); } } // Store arguments in list _quantum_gate_list[_num_quantum_gates].qubit_numbers = malloc(num_qubits*sizeof(int)); _quantum_gate_list[_num_quantum_gates].time = time; _quantum_gate_list[_num_quantum_gates].my_gate_type = my_gate_type; _quantum_gate_list[_num_quantum_gates]._get_val_j_from_global_i = HADAMARD_get_val_j_from_global_i; // Loop through and store qubits for (i=0;i<num_qubits;i++){ qubit = va_arg(ap,int); _quantum_gate_list[_num_quantum_gates].qubit_numbers[i] = qubit; } _num_quantum_gates = _num_quantum_gates + 1; } /* Apply a specific gate */ void _apply_gate(struct quantum_gate_struct this_gate,Vec rho){ PetscScalar op_vals[total_levels*2]; Mat gate_mat; //FIXME Consider having only one static Mat for all gates, rather than creating new ones every time Vec tmp_answer; PetscInt dim,i,Istart,Iend,num_js,these_js[total_levels*2]; // FIXME: maybe total_levels*2 is too much or not enough? Consider having a better bound. PetscLogEventBegin(_apply_gate_event,0,0,0,0); if (_lindblad_terms){ dim = total_levels*total_levels; } else { dim = total_levels; } VecDuplicate(rho,&tmp_answer); //Create a new vec with the same size as rho MatCreate(PETSC_COMM_WORLD,&gate_mat); MatSetSizes(gate_mat,PETSC_DECIDE,PETSC_DECIDE,dim,dim); MatSetFromOptions(gate_mat); MatMPIAIJSetPreallocation(gate_mat,4,NULL,4,NULL); //This matrix is incredibly sparse! MatSetUp(gate_mat); /* Construct the gate matrix, on the fly */ MatGetOwnershipRange(gate_mat,&Istart,&Iend); for (i=Istart;i<Iend;i++){ if (_lindblad_terms){ // Get the corresponding j and val for the superoperator U* cross U this_gate._get_val_j_from_global_i(i,this_gate,&num_js,these_js,op_vals,0); } else { // Get the corresponding j and val for just the matrix U this_gate._get_val_j_from_global_i(i,this_gate,&num_js,these_js,op_vals,-1); } MatSetValues(gate_mat,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(gate_mat,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(gate_mat,MAT_FINAL_ASSEMBLY); /* MatView(gate_mat,PETSC_VIEWER_STDOUT_SELF); */ MatMult(gate_mat,rho,tmp_answer); VecCopy(tmp_answer,rho); //Copy our tmp_answer array into rho VecDestroy(&tmp_answer); //Destroy the temp answer MatDestroy(&gate_mat); PetscLogEventEnd(_apply_gate_event,0,0,0,0); } /*z * _construct_gate_mat constructs the matrix needed for the quantum * computing gates. * * Inputs: * gate_type my_gate_type type of quantum gate * int *s * Outputs: * Mat gate_mat: the expanded, superoperator matrix for that gate */ void _construct_gate_mat(gate_type my_gate_type,int *systems,Mat gate_mat){ PetscInt i,j,i_mat,j_mat,k1,k2,k3,k4,n_before1,n_before2,my_levels,n_after; PetscInt i1,j1,i2=0,j2=0,comb_levels,control=-1,moved_system; PetscReal val1,val2; PetscScalar add_to_mat; if (my_gate_type == CNOT) { /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ /* Figure out which system is first in our basis * 0 and 1 is hardcoded because CNOT gates have only 2 qubits */ n_before1 = subsystem_list[systems[0]]->n_before; n_before2 = subsystem_list[systems[1]]->n_before; control = 0; moved_system = systems[1]; /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */ /* 4 is hardcoded because 2 qubits with 2 levels each */ n_after = total_levels/(4*n_before1); /* Check which is the control and which is the target */ if (n_before2<n_before1) { n_after = total_levels/(4*n_before2); control = 1; moved_system = systems[0]; n_before1 = n_before2; } /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; for (k1=0;k1<n_after;k1++){ for (k2=0;k2<n_before1;k2++){ for (i=0;i<4;i++){ //4 is hardcoded because there are only 4 entries val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1); /* Get I_b cross CNOT cross I_a in the temporary basis */ i1 = i1*n_after + k1 + k2*my_levels*n_after; j1 = j1*n_after + k1 + k2*my_levels*n_after; /* Permute to computational basis * To aid in the computation, we generated the matrix in the 'temporary basis', * where we exchanged the subsystem immediately after the first qubit with * the second qubit of interest. I.e., doing a CNOT(q3,q7) * Computational basis: q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 * Temporary basis: q1 q2 q3 q7 q5 q6 q4 q8 q9 q10 * This allows us to calculate CNOT easily - we just need to change * the basis back to the computational one. * * Since the control variable tells us which qubit was the first, * we switched the system immediately before that one with the * stored variable moved_system */ _change_basis_ij_pair(&i1,&j1,systems[control]+1,moved_system); for (k3=0;k3<n_after;k3++){ for (k4=0;k4<n_before1;k4++){ for (j=0;j<4;j++){ //4 is hardcoded because there are only 4 entries val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2); /* Get I_b cross CNOT cross I_a in the temporary basis */ i2 = i2*n_after + k3 + k4*my_levels*n_after; j2 = j2*n_after + k3 + k4*my_levels*n_after; /* Permute to computational basis */ _change_basis_ij_pair(&i2,&j2,systems[control]+1,moved_system); add_to_mat = val1*val2; /* Do the normal kron product expansion */ i_mat = my_levels*n_before1*n_after*i1 + i2; j_mat = my_levels*n_before1*n_after*j1 + j2; MatSetValue(gate_mat,i_mat,j_mat,add_to_mat,ADD_VALUES); } } } } } } } else if (my_gate_type == HADAMARD) { /* * The Hadamard gate is a one qubit gate defined as: * * H = 1/sqrt(2) 1 1 * 1 -1 * * Find the necessary Hilbert space dimensions for constructing the * full space matrix. */ n_before1 = subsystem_list[systems[0]]->n_before; my_levels = subsystem_list[systems[0]]->my_levels; //Should be 2, because qubit n_after = total_levels/(my_levels*n_before1); comb_levels = my_levels*my_levels*n_before1*n_after; for (k4=0;k4<n_before1*n_after;k4++){ for (i=0;i<4;i++){ // 4 hardcoded because there are 4 values in the hadamard val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1); for (j=0;j<4;j++){ val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2); i2 = i2 + k4*my_levels; j2 = j2 + k4*my_levels; /* * We need my_levels*n_before*n_after because we are taking * H cross (Ia cross Ib cross H), so the the size of the second operator * is my_levels*n_before*n_after */ add_to_mat = val1*val2; i_mat = my_levels*n_before1*n_after*i1 + i2; j_mat = my_levels*n_before1*n_after*j1 + j2; _add_to_PETSc_kron_ij(gate_mat,add_to_mat,i_mat,j_mat,n_before1,n_after,comb_levels); } } } } else if (my_gate_type == SIGMAX || my_gate_type == SIGMAY || my_gate_type == SIGMAZ || my_gate_type == SWAP) { /* * The pauli matrices are two qubit gates, sigmax, sigmay, sigmaz * The SWAP gate swaps two qubits. */ n_before1 = subsystem_list[systems[0]]->n_before; my_levels = subsystem_list[systems[0]]->my_levels; //Should be 2, because qubit n_after = total_levels/(my_levels*n_before1); comb_levels = my_levels*my_levels*n_before1*n_after; for (k4=0;k4<n_before1*n_after;k4++){ for (i=0;i<2;i++){// 2 hardcoded because there are 4 values in the hadamard val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1); for (j=0;j<2;j++){ val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2); i2 = i2 + k4*my_levels; j2 = j2 + k4*my_levels; /* * We need my_levels*n_before*n_after because we are taking * H cross (Ia cross Ib cross H), so the the size of the second operator * is my_levels*n_before*n_after */ add_to_mat = val1*val2; i_mat = my_levels*n_before1*n_after*i1 + i2; j_mat = my_levels*n_before1*n_after*j1 + j2; _add_to_PETSc_kron_ij(gate_mat,add_to_mat,i_mat,j_mat,n_before1,n_after,comb_levels); } } } } return; } void _change_basis_ij_pair(PetscInt *i_op,PetscInt *j_op,PetscInt system1,PetscInt system2){ PetscInt na1,na2,lev1,lev2; /* * To apply our change of basis we use the neat trick that the row number * in a given basis can be calculated similar to how a binary number is * calculated (but generalized in that some bits can have more than two * states. e.g. with three qubits * i(| 0 1 0 >) = 0*4 + 1*2 + 0*1 = 2 * where i() is the index, in this ordering, of the ket. * Another example, with 1 2level, 1 3levels, and 1 4 level system: * i(| 0 1 0 >) = 0*12 + 1*4 + 0*1 = 4 * that is, * i(| a b c >) = a*n_af^a + b*n_af^b + c*n_af^c * where n_af^a is the Hilbert space before system a, etc. * * Given a specific i, and only switching two systems, * we can calculate i's partner in the switched basis * by subtracting off the part from the current basis and * adding in the part from the desired basis. This leaves everything * else the same, but switches the two systems of interest. * * We need to be able to go from i to a specific subsystem's state. * This is accomplished with the formula: * (i/n_a % l) * Take our example above: * three qubits: 2 -> 2/4 % 2 = 0$2 = 0 * 2 -> 2/2 % 2 = 1%2 = 1 * 2 -> 2/1 % 2 = 2%2 = 0 * Or, the other example: 4 -> 4/12 % 2 = 0 * 4 -> 4/4 % 3 = 1 * 4 -> 4/1 % 4 = 0 * Note that this depends on integer division - 4/12 = 0 * * Using this, we can precisely calculate a system's part of the sum, * subtract that off, and then add the new basis. * * For example, let's switch our qubits from before around: * i(| 1 0 0 >) = 1*4 + 0*2 + 0*1 = 4 * Now, switch back to the original basis. Note we swapped q3 and q2 * first, subtract off the contributions from q3 and q2 * i_new = 4 - 1*4 - 0*2 = 0 * Now, add on the contributions in the original basis * i_new = 0 + 0*4 + 1*2 = 2 * Algorithmically, * i_new = i - (i/na1)%lev1 * na1 - (i/na2)%lev2 * na2 * + (i/na2)%lev1 * na1 + (i/na1)%lev2 * na2 * Note that we use our formula above to calculate the qubits * state in this basis, given this specific i. */ lev1 = subsystem_list[system1]->my_levels; na1 = total_levels/(lev1*subsystem_list[system1]->n_before); lev2 = subsystem_list[system2]->my_levels; na2 = total_levels/(lev2*subsystem_list[system2]->n_before); // Changed from lev1->lev2 *i_op = *i_op - ((*i_op/na1)%lev1)*na1 - ((*i_op/na2)%lev2)*na2 + ((*i_op/na1)%lev2)*na2 + ((*i_op/na2)%lev1)*na1; *j_op = *j_op - ((*j_op/na1)%lev1)*na1 - ((*j_op/na2)%lev2)*na2 + ((*j_op/na1)%lev2)*na2 + ((*j_op/na2)%lev1)*na1; return; } /* * _get_val_in_subspace_gate is a simple function that returns the * i_op,j_op pair and val for a given index; * Inputs: * int i: current index * gate_type my_gate_type the gate type * Outputs: * int *i_op: row value in subspace * int *j_op: column value in subspace * Return value: * PetscScalar val: value at i_op,j_op */ PetscScalar _get_val_in_subspace_gate(PetscInt i,gate_type my_gate_type,PetscInt control,PetscInt *i_op,PetscInt *j_op){ PetscScalar val=0.0; if (my_gate_type == CNOT) { /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ if (control==0) { if (i==0){ *i_op = 0; *j_op = 0; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 1; val = 1.0; } else if (i==2) { *i_op = 2; *j_op = 3; val = 1.0; } else if (i==3) { *i_op = 3; *j_op = 2; val = 1.0; } } else if (control==1) { if (i==0){ *i_op = 0; *j_op = 0; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 3; val = 1.0; } else if (i==2) { *i_op = 2; *j_op = 2; val = 1.0; } else if (i==3) { *i_op = 3; *j_op = 1; val = 1.0; } } } else if (my_gate_type == HADAMARD) { /* * The Hadamard gate is a one qubit gate defined as: * * H = 1/sqrt(2) 1 1 * 1 -1 * * Find the necessary Hilbert space dimensions for constructing the * full space matrix. */ if (i==0){ *i_op = 0; *j_op = 0; val = 1.0/sqrt(2); } else if (i==1) { *i_op = 0; *j_op = 1; val = 1.0/sqrt(2); } else if (i==2) { *i_op = 1; *j_op = 0; val = 1.0/sqrt(2); } else if (i==3) { *i_op = 1; *j_op = 1; val = -1.0/sqrt(2); } } else if (my_gate_type == SIGMAX){ /* * SIGMAX gate * * | 0 1 | * | 1 0 | * */ if (i==0){ *i_op = 0; *j_op = 1; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 0; val = 1.0; } else if (i==2){ *i_op = 1; *j_op = 1; val = 0.0; } else if (i==2) { *i_op = 0; *j_op = 0; val = 0.0; } } else if (my_gate_type == SIGMAX){ /* * SIGMAY gate * * | 0 -1.j | * | 1.j 0 | * */ if (i==0){ *i_op = 0; *j_op = 1; val = -PETSC_i; } else if (i==1) { *i_op = 1; *j_op = 0; val = PETSC_i; } else if (i==2){ *i_op = 1; *j_op = 1; val = 0.0; } else if (i==2) { *i_op = 0; *j_op = 0; val = 0.0; } } else if (my_gate_type == SIGMAZ){ /* * SIGMAZ gate * * | 1 0 | * | 0 -1 | * */ if (i==0){ *i_op = 0; *j_op = 0; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 1; val = 1.0; }else if (i==2){ *i_op = 1; *j_op = 0; val = 0.0; } else if (i==2) { *i_op = 0; *j_op = 1; val = 0.0; } } return val; } /* * create_circuit initializez the circuit struct. Gates can be added * later. * * Inputs: * circuit circ: circuit to be initialized * PetscIn num_gates_est: an estimate of the number of gates in * the circuit; can be negative, if no * estimate is known. * Outputs: * operator *new_op: lowering op (op), raising op (op->dag), and number op (op->n) */ void create_circuit(circuit *circ,PetscInt num_gates_est){ (*circ).start_time = 0.0; (*circ).num_gates = 0; (*circ).current_gate = 0; /* * If num_gates_est was positive when passed in, use that * as the initial gate_list size, otherwise set to * 100. gate_list will be dynamically resized when needed. */ if (num_gates_est>0) { (*circ).gate_list_size = num_gates_est; } else { // Default gate_list_size (*circ).gate_list_size = 100; } // Allocate gate list (*circ).gate_list = malloc((*circ).gate_list_size * sizeof(struct quantum_gate_struct)); } /* * Add a gate to a circuit. * Inputs: * circuit circ: circuit to add to * PetscReal time: time that gate would be applied, counting from 0 at * the start of the circuit * gate_type my_gate_type: which gate to add * ...: list of qubit gate will act on, other (U for controlled_U?) */ void add_gate_to_circuit(circuit *circ,PetscReal time,gate_type my_gate_type,...){ PetscReal theta,phi,lambda; int num_qubits=0,qubit,i; va_list ap; if (_gate_array_initialized==0){ //Initialize the array of gate function pointers _initialize_gate_function_array(); _gate_array_initialized = 1; } _check_gate_type(my_gate_type,&num_qubits); if ((*circ).num_gates==(*circ).gate_list_size){ if (nid==0){ printf("ERROR! Gate list not large enough!\n"); exit(1); } } // Store arguments in list (*circ).gate_list[(*circ).num_gates].qubit_numbers = malloc(num_qubits*sizeof(int)); (*circ).gate_list[(*circ).num_gates].time = time; (*circ).gate_list[(*circ).num_gates].my_gate_type = my_gate_type; (*circ).gate_list[(*circ).num_gates]._get_val_j_from_global_i = _get_val_j_functions_gates[my_gate_type+_min_gate_enum]; if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ) { va_start(ap,num_qubits+1); } else if (my_gate_type==U3){ va_start(ap,num_qubits+3); } else { va_start(ap,num_qubits); } // Loop through and store qubits for (i=0;i<num_qubits;i++){ qubit = va_arg(ap,int); if (qubit>=num_subsystems) { if (nid==0){ // Disable warning because of qasm parser will make the circuit before // the qubits are allocated //printf("Warning! Qubit number greater than total systems\n"); } } (*circ).gate_list[(*circ).num_gates].qubit_numbers[i] = qubit; } if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ||my_gate_type==PHASESHIFT){ //Get the theta parameter from the last argument passed in theta = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].theta = theta; (*circ).gate_list[(*circ).num_gates].phi = 0; (*circ).gate_list[(*circ).num_gates].lambda = 0; } else if (my_gate_type==U3){ theta = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].theta = theta; phi = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].phi = phi; lambda = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].lambda = lambda; } else { //Set theta to 0 (*circ).gate_list[(*circ).num_gates].theta = 0; (*circ).gate_list[(*circ).num_gates].phi = 0; (*circ).gate_list[(*circ).num_gates].lambda = 0; } (*circ).num_gates = (*circ).num_gates + 1; return; } /* * Add a circuit to another circuit. * Assumes whole circuit happens at time */ void add_circuit_to_circuit(circuit *circ,circuit circ_to_add,PetscReal time){ int num_qubits=0,i,j; // Check that we can fit the circuit in if (((*circ).num_gates+circ_to_add.num_gates-1)==(*circ).gate_list_size){ if (nid==0){ printf("ERROR! Gate list not large enough to add this circuit!\n"); exit(1); } } for (i=0;i<circ_to_add.num_gates;i++){ // Copy gate information over (*circ).gate_list[(*circ).num_gates].time = time; if (circ_to_add.gate_list[i].my_gate_type<0){ num_qubits = 2; } else { num_qubits = 1; } (*circ).gate_list[(*circ).num_gates].qubit_numbers = malloc(num_qubits*sizeof(int)); for (j=0;j<num_qubits;j++){ (*circ).gate_list[(*circ).num_gates].qubit_numbers[j] = circ_to_add.gate_list[i].qubit_numbers[j]; } (*circ).gate_list[(*circ).num_gates].my_gate_type = circ_to_add.gate_list[i].my_gate_type; (*circ).gate_list[(*circ).num_gates]._get_val_j_from_global_i = circ_to_add.gate_list[i]._get_val_j_from_global_i; (*circ).gate_list[(*circ).num_gates].theta = circ_to_add.gate_list[i].theta; (*circ).num_gates = (*circ).num_gates + 1; } return; } /* register a circuit to be run a specific time during the time stepping */ void start_circuit_at_time(circuit *circ,PetscReal time){ (*circ).start_time = time; _circuit_list[_num_circuits] = *circ; _num_circuits = _num_circuits + 1; } /* * * tensor_control - switch on which superoperator to compute * -1: I cross G or just G (the difference is controlled by the passed in i's, but * the internal logic is exactly the same) * 0: G* cross G * 1: G* cross I */ void _get_val_j_from_global_i_gates(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ operator this_op1,this_op2; PetscInt n_after,i_sub,tmp_int,control,moved_system,my_levels,num_js_i1=0,num_js_i2=0; PetscInt k1,k2,n_before1,n_before2,i_tmp,j_sub,extra_after,i1,i2,j1,js_i1[2],js_i2[2]; PetscScalar vals_i1[2],vals_i2[2],theta,phi,lambda; //2 is hardcoded because 2 is the largest number of js from 1 i (HADAMARD) /* * We store our gates as a type and affected systems; * we use the stored information to calculate the global j(s) location * and nonzero value(s) for a give global i * * Fo all 2-qubit gates, we use the fact that * diagonal elements are diagonal, even in global space * and that off-diagonal elements can be worked out from the * following: * Off diagonal elements: * if (i_sub==1) * i = 1 * n_af + k1 + k2*n_me*n_af * j = 0 * n_af + k1 + k2*n_me*n_af * if (i_sub==0) * i = 0 * n_af + k1 + k2*n_l*n_af * j = 1 * n_af + k1 + k2*n_l*n_af * We work out k1 and k2 from i to get j. * */ if (tensor_control!= 0) { if (tensor_control==1) { extra_after = total_levels; } else { extra_after = 1; } if (gate.my_gate_type > 0) { // Single qubit gates are coded as positive numbers //Get the system this is affecting this_op1 = subsystem_list[gate.qubit_numbers[0]]; if (this_op1->my_levels!=2) { //Check that it is a two level system if (nid==0){ printf("ERROR! Single qubit gates can only affect 2-level systems\n"); exit(0); } } n_after = total_levels/(this_op1->my_levels*this_op1->n_before)*extra_after; i_sub = i/n_after%this_op1->my_levels; //Use integer arithmetic to get floor function //Branch on the gate types if (gate.my_gate_type == HADAMARD){ /* * HADAMARD gate * * 1/sqrt(2) | 1 1 | * | 1 -1 | * Hadamard gates have two values per row, * with both diagonal anad off diagonal elements * */ *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = pow(2,-0.5); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = pow(2,-0.5); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -pow(2,-0.5); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = pow(2,-0.5); } else { if (nid==0){ printf("ERROR! Hadamard gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == SIGMAX){ /* * SIGMAX gate * * | 0 1 | * | 1 0 | * */ *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = 1.0; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = 1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == SIGMAY){ /* * SIGMAY gate * * | 0 -1.j | * | 1.j 0 | * */ *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = -1.0*PETSC_i; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = 1.0*PETSC_i; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == SIGMAZ){ /* * SIGMAZ gate * * | 1 0 | * | 0 -1 | * */ *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == EYE){ /* * Identity (EYE) gate * * | 1 0 | * | 0 1 | * */ *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = 1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == PHASESHIFT){ /* * PHASESHIFT gate * * | 1 0 | * | 0 e^(-i*theta) | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*theta); } else { if (nid==0){ printf("ERROR! phaseshift gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == T){ /* * T gate * * | 1 0 | * | 0 e^(i*pi/4) | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! t gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == TDAG){ /* * TDAG gate * * | 1 0 | * | 0 e^(-i*pi/4) | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! tdag gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == S){ /* * S gate * * | 1 0 | * | 0 i | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! t gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == RX){ /* * RX gate * * | cos(theta/2) i*sin(theta/2) | * | i*sin(theta/2) cos(theta/2) | * */ theta = gate.theta; *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == U3) { /* * u3 gate * * u3(theta,phi,lambda) = | cos(theta/2) -e^(i lambda) * sin(theta/2) | * | e^(i phi) sin(theta/2) e^(i (lambda+phi)) cos(theta/2) | * the u3 gate is a general one qubit transformation. * the u2 gate is u3(pi/2,phi,lambda) * the u1 gate is u3(0,0,lambda) * The u3 gate has two elements per row, * with both diagonal anad off diagonal elements * */ theta = gate.theta; phi = gate.phi; lambda = gate.lambda; *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = -PetscExpComplex(PETSC_i*lambda)*PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*(lambda+phi))*PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = PetscExpComplex(PETSC_i*phi)*PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! u3 gate is only defined for qubits\n"); exit(0); } } } else { if (nid==0){ printf("ERROR! Gate type not understood! %d\n", gate.my_gate_type); exit(0); } } } else { //Two qubit gates this_op1 = subsystem_list[gate.qubit_numbers[0]]; this_op2 = subsystem_list[gate.qubit_numbers[1]]; if (this_op1->my_levels * this_op2->my_levels != 4) { //Check that it is a two level system if (nid==0){ printf("ERROR! Two qubit gates can only affect two 2-level systems (global_i)\n"); exit(0); } } n_before1 = this_op1->n_before; n_before2 = this_op2->n_before; control = 0; moved_system = gate.qubit_numbers[1]; /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */ /* 4 is hardcoded because 2 qubits with 2 levels each */ n_after = total_levels/(4*n_before1)*extra_after; /* * Check which is the control and which is the target, * flip if need be. */ if (n_before2<n_before1) { n_after = total_levels/(4*n_before2); control = 1; moved_system = gate.qubit_numbers[0]; n_before1 = n_before2; } /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; /* * Permute to temporary basis * Get the i_sub in the permuted basis */ i_tmp = i; _change_basis_ij_pair(&i_tmp,&j1,gate.qubit_numbers[control]+1,moved_system); // j1 useless here i_sub = i_tmp/n_after%my_levels; //Use integer arithmetic to get floor function if (gate.my_gate_type == CNOT) { /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CNOT gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CXZ) { /* The controlled-XZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * sig_z * 0 0 0 -1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit if (control==0){ // Diagonal vals[0] = 1.0; js[0] = i; } else { // Off diagonal vals[0] = -1.0; tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ if (control==0){ vals[0] = -1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal vals[0] = 1.0; js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CXZ gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CZX) { /* The controlled-ZX gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * sig_x * 0 0 0 1 * 0 0 -1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = -1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CZX gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CZ) { /* The controlled-Z gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * 0 0 1 0 * 0 0 0 -1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * * Controlled-z is the same for both possible controls */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==2){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==3){ vals[0] = -1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CZ gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CmZ) { /* The controlled-mZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 -sig_z * 0 0 -1 0 * 0 0 0 1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal js[0] = i; if (control==0) { vals[0] = 1.0; } else { vals[0] = -1.0; } } else if (i_sub==2){ // Diagonal js[0] = i; if (control==0) { vals[0] = -1.0; } else { vals[0] = 1.0; } } else if (i_sub==3){ vals[0] = 1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CmZ gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == SWAP) { /* The swap gate swaps two qubits. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 0 1 0 = 0 sig_z * sig_x * 0 1 0 0 * 0 0 0 1 */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==2){ vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==3){ vals[0] = 1.0; // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! SWAP gate is only defined for 2 qubits!\n"); exit(0); } } } else { if (nid==0){ printf("ERROR!Two Qubit gate type not understood! %d\n",gate.my_gate_type); exit(0); } } } if (tensor_control==1){ //Take complex conjugate of answer to get U* cross I for (i=0;i<*num_js;i++){ vals[i] = PetscConjComplex(vals[i]); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ _get_val_j_from_global_i_gates(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ _get_val_j_from_global_i_gates(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void combine_circuit_to_mat2(Mat *matrix_out,circuit circ){ PetscScalar op_val,op_vals[total_levels],vals[2]={0}; PetscInt Istart,Iend; PetscInt i,j,k,l,this_i,these_js[total_levels],js[2]={0},num_js_tmp=0,num_js,num_js_current; // Should this inherit its stucture from full_A? MatCreate(PETSC_COMM_WORLD,matrix_out); MatSetType(*matrix_out,MATMPIAIJ); MatSetSizes(*matrix_out,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels); MatSetFromOptions(*matrix_out); MatMPIAIJSetPreallocation(*matrix_out,16,NULL,16,NULL); /* * Calculate G1*G2*G3*.. using the following observation: * Each gate is very sparse - having no more than * 2 values per row. This allows us to efficiently do the * multiplication by just touching the nonzero values */ MatGetOwnershipRange(*matrix_out,&Istart,&Iend); for (i=Istart;i<Iend;i++){ this_i = i; // The leading index which we check // Reset the result for the row num_js = 1; these_js[0] = i; op_vals[0] = 1.0; for (j=0;j<circ.num_gates;j++){ num_js_current = num_js; for (k=0;k<num_js_current;k++){ // Loop through all of the js from the previous gate multiplications this_i = these_js[k]; op_val = op_vals[k]; _get_val_j_from_global_i_gates(this_i,circ.gate_list[j],&num_js_tmp,js,vals,-1); // Get the corresponding j and val /* * Assume there is always at least 1 nonzero per row. This is a good assumption * because all basic quantum gates have at least 1 nonzero per row */ // WARNING! CODE NOT FINISHED // WILL NOT WORK FOR HADAMARD * HADAMARD these_js[k] = js[0]; op_vals[k] = op_val*vals[0]; for (l=1;l<num_js_tmp;l++){ //If we have more than 1 num_js_tmp, we append to the end of the list these_js[num_js+l-1] = js[l]; op_vals[num_js+l-1] = op_val*vals[l]; } num_js = num_js + num_js_tmp - 1; //If we spawned an extra j, add it here } } MatSetValues(*matrix_out,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(*matrix_out,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(*matrix_out,MAT_FINAL_ASSEMBLY); return; } void combine_circuit_to_mat(Mat *matrix_out,circuit circ){ PetscScalar op_vals[2]; PetscInt Istart,Iend,i_mat; PetscInt i,these_js[2],num_js; Mat tmp_mat1,tmp_mat2,tmp_mat3; // Should this inherit its stucture from full_A? MatCreate(PETSC_COMM_WORLD,&tmp_mat1); MatSetType(tmp_mat1,MATMPIAIJ); MatSetSizes(tmp_mat1,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels); MatSetFromOptions(tmp_mat1); MatMPIAIJSetPreallocation(tmp_mat1,2,NULL,2,NULL); /* Construct the first matrix in tmp_mat1 */ MatGetOwnershipRange(tmp_mat1,&Istart,&Iend); for (i=Istart;i<Iend;i++){ circ.gate_list[0]._get_val_j_from_global_i(i,circ.gate_list[0],&num_js,these_js,op_vals,-1); // Get the corresponding j and val MatSetValues(tmp_mat1,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat1,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat1,MAT_FINAL_ASSEMBLY); for (i_mat=1;i_mat<circ.num_gates;i_mat++){ // Create the next matrix MatCreate(PETSC_COMM_WORLD,&tmp_mat2); MatSetType(tmp_mat2,MATMPIAIJ); MatSetSizes(tmp_mat2,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels); MatSetFromOptions(tmp_mat2); MatMPIAIJSetPreallocation(tmp_mat2,2,NULL,2,NULL); /* Construct new matrix */ MatGetOwnershipRange(tmp_mat2,&Istart,&Iend); for (i=Istart;i<Iend;i++){ _get_val_j_from_global_i_gates(i,circ.gate_list[i_mat],&num_js,these_js,op_vals,-1); // Get the corresponding j and val MatSetValues(tmp_mat2,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat2,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat2,MAT_FINAL_ASSEMBLY); // Now do matrix matrix multiply MatMatMult(tmp_mat2,tmp_mat1,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&tmp_mat3); MatDestroy(&tmp_mat1); MatDestroy(&tmp_mat2); //Do I need to destroy it? //Store tmp_mat3 into tmp_mat1 MatConvert(tmp_mat3,MATSAME,MAT_INITIAL_MATRIX,&tmp_mat1); MatDestroy(&tmp_mat3); } //Copy tmp_mat1 into *matrix_out MatConvert(tmp_mat1,MATSAME,MAT_INITIAL_MATRIX,matrix_out);; MatDestroy(&tmp_mat1); return; } void combine_circuit_to_super_mat(Mat *matrix_out,circuit circ){ PetscScalar op_vals[4]; PetscInt Istart,Iend,i_mat,dim; PetscInt i,these_js[4],num_js; Mat tmp_mat1,tmp_mat2,tmp_mat3; // Should this inherit its stucture from full_A? dim = total_levels*total_levels; MatCreate(PETSC_COMM_WORLD,&tmp_mat1); MatSetType(tmp_mat1,MATMPIAIJ); MatSetSizes(tmp_mat1,PETSC_DECIDE,PETSC_DECIDE,dim,dim); MatSetFromOptions(tmp_mat1); MatMPIAIJSetPreallocation(tmp_mat1,8,NULL,8,NULL); /* Construct the first matrix in tmp_mat1 */ MatGetOwnershipRange(tmp_mat1,&Istart,&Iend); for (i=Istart;i<Iend;i++){ _get_val_j_from_global_i_gates(i,circ.gate_list[0],&num_js,these_js,op_vals,0); // Get the corresponding j and val MatSetValues(tmp_mat1,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat1,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat1,MAT_FINAL_ASSEMBLY); for (i_mat=1;i_mat<circ.num_gates;i_mat++){ // Create the next matrix MatCreate(PETSC_COMM_WORLD,&tmp_mat2); MatSetType(tmp_mat2,MATMPIAIJ); MatSetSizes(tmp_mat2,PETSC_DECIDE,PETSC_DECIDE,dim,dim); MatSetFromOptions(tmp_mat2); MatMPIAIJSetPreallocation(tmp_mat2,8,NULL,8,NULL); /* Construct new matrix */ MatGetOwnershipRange(tmp_mat2,&Istart,&Iend); for (i=Istart;i<Iend;i++){ _get_val_j_from_global_i_gates(i,circ.gate_list[i_mat],&num_js,these_js,op_vals,0); // Get the corresponding j and val MatSetValues(tmp_mat2,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat2,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat2,MAT_FINAL_ASSEMBLY); // Now do matrix matrix multiply MatMatMult(tmp_mat2,tmp_mat1,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&tmp_mat3); MatDestroy(&tmp_mat1); MatDestroy(&tmp_mat2); //Do I need to destroy it? //Store tmp_mat3 into tmp_mat1 MatConvert(tmp_mat3,MATSAME,MAT_INITIAL_MATRIX,&tmp_mat1); MatDestroy(&tmp_mat3); } //Copy tmp_mat1 into *matrix_out MatConvert(tmp_mat1,MATSAME,MAT_INITIAL_MATRIX,matrix_out);; MatDestroy(&tmp_mat1); return; } /* * No issue for js_i* = -1 because every row is guaranteed to have a 0 * in all the gates implemented below. * See commit: 9956c78171fdac1fa0ef9e2f0a39cbffd4d755dc where this was an issue * in _get_val_j_from_global_i for raising / lowering / number operators, where * -1 was used to say there was no nonzero in that row. */ void CNOT_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CNOT gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CNOT_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CNOT_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CXZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-XZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * sig_z * 0 0 0 -1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit if (control==0){ // Diagonal vals[0] = 1.0; js[0] = i; } else { // Off diagonal vals[0] = -1.0; tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ if (control==0){ vals[0] = -1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal vals[0] = 1.0; js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CXZ gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CXZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CXZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,moved_system; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-Z gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * 0 0 1 0 * 0 0 0 -1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * * Controlled-z is the same for both possible controls */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==2){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==3){ vals[0] = -1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CZ gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CmZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,moved_system; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-mZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 -sig_z * 0 0 -1 0 * 0 0 0 1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal js[0] = i; if (control==0) { vals[0] = 1.0; } else { vals[0] = -1.0; } } else if (i_sub==2){ // Diagonal js[0] = i; if (control==0) { vals[0] = -1.0; } else { vals[0] = 1.0; } } else if (i_sub==3){ vals[0] = 1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CmZ gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CmZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CmZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CZX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-ZX gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * sig_x * 0 0 0 1 * 0 0 -1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = -1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CZX gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CZX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CZX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SWAP_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The swap gate swaps two qubits. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 0 1 0 = 0 sig_z * sig_x * 0 1 0 0 * 0 0 0 1 */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); printf("\n tensor_control %d,control %d,i_sub %d n_after %d\n", tensor_control, control, i_sub, n_after ); *num_js = 1; if (i_sub==0){ // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub // Permute back to computational basis _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==2){ vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==3){ // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else { if (nid==0){ printf("ERROR! SWAP gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SWAP_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SWAP_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void HADAMARD_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * HADAMARD gate * * 1/sqrt(2) | 1 1 | * | 1 -1 | * Hadamard gates have two values per row, * with both diagonal anad off diagonal elements * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = pow(2,-0.5); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = pow(2,-0.5); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -pow(2,-0.5); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = pow(2,-0.5); } else { if (nid==0){ printf("ERROR! Hadamard gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ HADAMARD_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ HADAMARD_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void U3_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta,lambda,phi; /* * u3 gate * * u3(theta,phi,lambda) = | cos(theta/2) -e^(i lambda) * sin(theta/2) | * | e^(i phi) sin(theta/2) e^(i (lambda+phi)) cos(theta/2) | * the u3 gate is a general one qubit transformation. * the u2 gate is u3(pi/2,phi,lambda) * the u1 gate is u3(0,0,lambda) * The u3 gate has two elements per row, * with both diagonal anad off diagonal elements * */ theta = gate.theta; phi = gate.phi; lambda = gate.lambda; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = -PetscExpComplex(PETSC_i*lambda)*PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*(lambda+phi))*PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = PetscExpComplex(PETSC_i*phi)*PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! u3 gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ U3_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ U3_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void EYE_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2]; PetscScalar vals_i1[2],vals_i2[2]; /* * Identity (EYE) gate * * | 1 0 | * | 0 1 | * */ if (tensor_control!= 0) { _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; js[0] = i; vals[0] = 1.0; } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ EYE_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ EYE_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void PHASESHIFT_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * PHASESHIFT gate * * | 1 0 | * | 0 e^(-i*theta) | * */ theta=gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*theta); } else { if (nid==0){ printf("ERROR! phaseshift gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ PHASESHIFT_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ PHASESHIFT_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SIGMAZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * SIGMAZ gate * * | 1 0 | * | 0 -1 | * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -1.0; } else { if (nid==0){ printf("ERROR! sigmaz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SIGMAZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SIGMAZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void RZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * RZ gate * * | exp(i*theta/2) 0 | * | 0 -exp(i*theta/2) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ RZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ RZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void RY_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * RY gate * * | cos(theta/2) sin(theta/2) | * | -sin(theta/2) cos(theta/2) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2.0); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = -PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ RY_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ RY_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void RX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * RX gate * * | cos(theta/2) i*sin(theta/2) | * | i*sin(theta/2) cos(theta/2) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ RX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ RX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SIGMAY_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * SIGMAY gate * * | 0 -1.j | * | 1.j 0 | * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[0] = -1.0*PETSC_i; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = 0 * n_after + k1 + k2*my_levels*n_after; vals[0] = 1.0*PETSC_i; } else { if (nid==0){ printf("ERROR! sigmay gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SIGMAY_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SIGMAY_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SIGMAX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * SIGMAX gate * * | 0 1 | * | 1 0 | * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[0] = 1.0; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = 0 * n_after + k1 + k2*my_levels*n_after; vals[0] = 1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SIGMAX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SIGMAX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void T_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * T gate * * | 1 0 | * | 0 exp(i*pi/4) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! T gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ T_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ T_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void TDAG_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * TDAG gate * * | 1 0 | * | 0 exp(i*pi/4) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! T gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ TDAG_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ TDAG_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void S_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * S gate * * | 1 0 | * | 0 i | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PETSC_i; } else { if (nid==0){ printf("ERROR! S gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ S_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ S_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void _get_n_after_2qbit(PetscInt *i,int qubit_numbers[],PetscInt tensor_control,PetscInt *n_after, PetscInt *control, PetscInt *moved_system, PetscInt *i_sub){ operator this_op1,this_op2; PetscInt n_before1,n_before2,extra_after,my_levels=4,j1; //4 is hardcoded because 2 qbits if (tensor_control==1) { extra_after = total_levels; } else { extra_after = 1; } //Two qubit gates this_op1 = subsystem_list[qubit_numbers[0]]; this_op2 = subsystem_list[qubit_numbers[1]]; if (this_op1->my_levels * this_op2->my_levels != 4) { //Check that it is a two level system if (nid==0){ printf("ERROR! Two qubit gates can only affect two 2-level systems (global_i)\n"); exit(0); } } n_before1 = this_op1->n_before; n_before2 = this_op2->n_before; *control = 0; *moved_system = qubit_numbers[1]; /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */ /* 4 is hardcoded because 2 qubits with 2 levels each */ *n_after = total_levels/(4*n_before1)*extra_after; /* * Check which is the control and which is the target, * flip if need be. */ if (n_before2<n_before1) { *n_after = total_levels/(4*n_before2); *control = 1; *moved_system = qubit_numbers[0]; n_before1 = n_before2; } /* * Permute to temporary basis * Get the i_sub in the permuted basis */ _change_basis_ij_pair(i,&j1,qubit_numbers[*control]+1,*moved_system); // j1 useless here *i_sub = *i/(*n_after)%my_levels; //Use integer arithmetic to get floor function return; } void _get_n_after_1qbit(PetscInt i,int qubit_number,PetscInt tensor_control,PetscInt *n_after,PetscInt *i_sub){ operator this_op1; PetscInt extra_after; if (tensor_control==1) { extra_after = total_levels; } else { extra_after = 1; } //Get the system this is affecting this_op1 = subsystem_list[qubit_number]; if (this_op1->my_levels!=2) { //Check that it is a two level system if (nid==0){ printf("ERROR! Single qubit gates can only affect 2-level systems\n"); exit(0); } } *n_after = total_levels/(this_op1->my_levels*this_op1->n_before)*extra_after; *i_sub = i/(*n_after)%this_op1->my_levels; //Use integer arithmetic to get floor function return; } // Check that the gate type is valid and set the number of qubits void _check_gate_type(gate_type my_gate_type,int *num_qubits){ if (my_gate_type==HADAMARD||my_gate_type==SIGMAX||my_gate_type==SIGMAY||my_gate_type==SIGMAZ||my_gate_type==EYE|| my_gate_type==RZ||my_gate_type==RX||my_gate_type==RY||my_gate_type==U3||my_gate_type==PHASESHIFT||my_gate_type==T||my_gate_type==TDAG||my_gate_type==S) { *num_qubits = 1; } else if (my_gate_type==CNOT||my_gate_type==CXZ||my_gate_type==CZ||my_gate_type==CmZ||my_gate_type==CZX||my_gate_type==SWAP){ *num_qubits = 2; } else { if (nid==0){ printf("ERROR! Gate type not recognized\n"); exit(0); } } } /* * Put the gate function pointers into an array */ void _initialize_gate_function_array(){ _get_val_j_functions_gates[CZX+_min_gate_enum] = CZX_get_val_j_from_global_i; _get_val_j_functions_gates[CmZ+_min_gate_enum] = CmZ_get_val_j_from_global_i; _get_val_j_functions_gates[CZ+_min_gate_enum] = CZ_get_val_j_from_global_i; _get_val_j_functions_gates[CXZ+_min_gate_enum] = CXZ_get_val_j_from_global_i; _get_val_j_functions_gates[CNOT+_min_gate_enum] = CNOT_get_val_j_from_global_i; _get_val_j_functions_gates[HADAMARD+_min_gate_enum] = HADAMARD_get_val_j_from_global_i; _get_val_j_functions_gates[SIGMAX+_min_gate_enum] = SIGMAX_get_val_j_from_global_i; _get_val_j_functions_gates[SIGMAY+_min_gate_enum] = SIGMAY_get_val_j_from_global_i; _get_val_j_functions_gates[SIGMAZ+_min_gate_enum] = SIGMAZ_get_val_j_from_global_i; _get_val_j_functions_gates[EYE+_min_gate_enum] = EYE_get_val_j_from_global_i; _get_val_j_functions_gates[RX+_min_gate_enum] = RX_get_val_j_from_global_i; _get_val_j_functions_gates[RY+_min_gate_enum] = RY_get_val_j_from_global_i; _get_val_j_functions_gates[RZ+_min_gate_enum] = RZ_get_val_j_from_global_i; _get_val_j_functions_gates[U3+_min_gate_enum] = U3_get_val_j_from_global_i; _get_val_j_functions_gates[SWAP+_min_gate_enum] = SWAP_get_val_j_from_global_i; _get_val_j_functions_gates[PHASESHIFT+_min_gate_enum] = PHASESHIFT_get_val_j_from_global_i; _get_val_j_functions_gates[T+_min_gate_enum] = T_get_val_j_from_global_i; _get_val_j_functions_gates[TDAG+_min_gate_enum] = TDAG_get_val_j_from_global_i; _get_val_j_functions_gates[S+_min_gate_enum] = S_get_val_j_from_global_i; }
\chapterimage{chapter_head_2.pdf} \chapter{Avoid Duplication} \section{DRY} Unfortunately, knowledge isn't stable. It changes—often rapidly. Your understanding of a requirement may change following a meeting with the client. The government changes a regulation and some business logic gets outdated. Tests may show that the chosen algorithm won't work. All this instability means that we spend a large part of our time in maintenance mode, reorganizing and reexpressing the knowledge in our systems. Most people assume that maintenance begins when an application is released, that maintenance means fixing bugs and enhancing features. We think these people are wrong. Programmers are constantly in maintenance mode. Our understanding changes day by day. New requirements arrive as we're designing or coding. Perhaps the environment changes. Whatever the reason, maintenance is not a discrete activity, but a routine part of the entire development process. When we perform maintenance, we have to find and change the representations of things—those capsules of knowledge embedded in the application. The problem is that it's easy to duplicate knowledge in the specifications, processes, and programs that we develop, and when we do so, we invite a maintenance nightmare—one that starts well before the application ships. We feel that the only way to develop software reliably, and to make our developments easier to understand and maintain, is to follow what we call the DRY(Don't Repeat Yourself) principle: \begin{remark} EVERY PIECE OF KNOWLEDGE MUST HAVE A SINGLE, UNAMBIGUOUS, AUTHORITATIVE REPRESENTATION WITHIN A SYSTEM. \end{remark} \begin{marker} On duplicated codes, ask code author to remove it \end{marker} \section{How Does Duplication Arise?} Most of the duplication we see falls into one of the following categories: \begin{itemize} \item \textbf{Imposed duplication} Developers feel they have no choice—the environment seems to require duplication. \item \textbf{Inadvertent duplication} Developers don't realize that they are duplicating information. \item \textbf{Impatient duplication} Developers get lazy and duplicate because it seems easier. \item \textbf{Inter-developer duplication} Multiple people on a team (or on different teams) duplicate a piece of information. \end{itemize}
(** * Dependently-typed events *) (** A _type family_ is given by a parameter type [I : Type] and a type function [F : I -> Type]. A type family [(I, F : I -> Type)] can be encoded as an indexed type [E : Type -> Type]. A value [i : I] can be seen as a "flat representation" of a value [e : E X] (for arbitrary [X]), while [F i : Type] gives the type index [X] of this [e]. This encoding can be seen as a kind of "dependently-typed event", although the general use indexed types for event types already provides an equally expressive form of dependency. *) (* begin hide *) From ITree Require Import Basics.Basics Core.ITreeDefinition Indexed.Sum Core.Subevent. Import Basics.Basics.Monads. (* end hide *) Variant depE {I : Type} (F : I -> Type) : Type -> Type := | Dep (i : I) : depE F (F i). Arguments Dep {I F}. Definition dep {I F E G} `{depE F +? G -< E} (i : I) : itree E (F i) := trigger (E := depE F) (Dep i). Definition undep {I F} (f : forall i : I, F i) : depE F ~> identity := fun _ d => match d with | Dep i => f i end.
library(tidyverse) library(kableExtra) library(data.table) library(ggplot2) library(cluster) #Библиотека для каластерного анализа library(captioner) #Библиотка для нумерации таблиц и рисунков и вообще всего library(treemap) #Библиотека для площадных диаграмм library(RColorBrewer) #Пакет для цветовых схем для диаграмм #library(readxl) экспериментировал с импотром из экселя library(DT) #экспериментировал с datatable #library(htmltools) экспериментировал с datatable # Функция вывода таблицы с помощью библиотеки DT, get_dt = function(top_data, col_names = c("Федеральный округ" = "FO_name", "Субъект федерации" = "Subj_Name", "Срез показателя" = "Col_num"), output_file_name) { datatable(top_data, colnames = col_names, extensions = 'Buttons', escape = FALSE, rownames = FALSE, filter = 'top', options = list(searching = TRUE, pageLength = 10, lengthMenu = c(8, 10, 85, 100), dom = 'Bfrtip', buttons = list('colvis', list( extend = 'collection', buttons = list(list(extend='csv', filename = output_file_name), list(extend='excel', filename = output_file_name), list(extend='pdf', filename= output_file_name)), text = 'Download' )), scrollX = TRUE, pageLength = nrow(top_data))) } #Функция для импорта данных из csv файлов в переменные R (требует имя файла в кавычках и берет из каталока data рабочей директории проекта) import_table = function(file_name){ read_delim(paste0("data/", file_name), ";", escape_double = FALSE, locale = locale(decimal_mark = ",", grouping_mark = "", encoding = "WINDOWS-1251"), trim_ws = TRUE) }
Formal statement is: lemma cnj_in_Ints_iff [simp]: "cnj x \<in> \<int> \<longleftrightarrow> x \<in> \<int>" Informal statement is: The complex conjugate of an algebraic integer is an algebraic integer if and only if the original number is an algebraic integer.
lemma complex_cnj_divide [simp]: "cnj (x / y) = cnj x / cnj y"
[STATEMENT] lemma dbm_lt_not_inf_less[intro]: "A \<noteq> \<infinity> \<Longrightarrow> A \<prec> \<infinity>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. A \<noteq> \<infinity> \<Longrightarrow> A \<prec> \<infinity> [PROOF STEP] by (cases A) auto
module Cordial.Model.Interface.PortGroup import Data.Vect import Data.DList import Data.Ranged import Text.Markup.Edda import Cordial.Model.Common import Cordial.Model.Specification import Cordial.Model.Projection import Cordial.Model.Interface.Kinds import Cordial.Model.Interface.Ports %default total %access public export {- [ NOTE ] We take note, at the type level, if the port is required or not. We use this information with `PortGroup` below to describe thinnings. With Port notice how we constrain the value level values using type level values. This is core principle behind how we type check our ports/interfaces against an abstract definition. We first project the definition based on the kind of interface, and use that projection in the type to source values. -} ||| A collection of ports that respects the projected port group. ||| ||| Universe that logical names arise from. ||| Are we producing/consuming information. ||| The originating projected port type that constrains the value level values. ||| data PortGroup : (annot : Type) -> (labelTy : Type) -> (endpoint : Endpoint) -> (endian : Maybe Endian) -> (ps : PortGroupTy annot labelTy) -> (pportTys : DList (PortTy annot labelTy) (ProjectedPortTy labelTy endpoint) ps) -> Type where ||| No ports Empty : PortGroup annot labelTy endpoint endian Nil Nil ||| Add a port to the group such that the description comes from ||| the projected port list. Add : {type : PortTy annot labelTy} -> {projectedType : ProjectedPortTy labelTy endpoint type} -> (port : Port annot labelTy type projectedType endpoint endian) -> (rest : PortGroup annot labelTy endpoint endian ps pps) -> PortGroup annot labelTy endpoint endian (type :: ps) (projectedType :: pps) ||| Skip an optional port from the projected port list. Skip : (rest : PortGroup annot labelTy endpoint endian ps pps) -> (prf : OptionalProjectedPort type endpoint projectedType) -> PortGroup annot labelTy endpoint endian (type :: ps) (projectedType :: pps) infixr 5 <::>, <::~> (<::>) : {type : PortTy annot labelTy} -> {projectedType : ProjectedPortTy labelTy endpoint type} -> (port : Port annot labelTy type projectedType endpoint endian) -> (rest : PortGroup annot labelTy endpoint endian ps pps) -> PortGroup annot labelTy endpoint endian (type::ps) (projectedType::pps) (<::>) port rest = Add port rest (<::~>) : (port : Port annot labelTy type projectedType endpoint endian) -> (rest : PortGroup annot labelTy endpoint endian ps pps) -> {auto prf : OptionalProjectedPort typeOfSkipped endpoint projectedTypeOfSkipped} -> PortGroup annot labelTy endpoint endian (type::typeOfSkipped::ps) (projectedType::projectedTypeOfSkipped::pps) (<::~>) port rest {prf} = Add port (Skip rest prf) -- --------------------------------------------------------------------- [ EOF ]
#@author: Hoofar Pourzand #This file is copyright protected - do not redistribute #For R style exercise https://google.github.io/styleguide/Rguide.xml library(ggplot2) source("http://www.bioconductor.org/biocLite.R") biocLite("GEOquery") library(Biobase) library(GEOquery) GDS5093 <- getGEO('GDS5093', destdir="/Users/romeokienzler/Documents/tmp/") GDS5088 <- getGEO('GDS5088', destdir="/Users/romeokienzler/Documents/tmp/") dfVirus = Table(GDS5093) dfMother = Table(GDS5088) dim(dfVirus) dim(dfMother) colnames(dfMother) dfVirus[,2] dfMother[,2] commonGenes = intersect(dfVirus[,2],dfMother[,2]) length(commonGenes) length(dfVirus[,2]) length(dfMother[,2]) dfVirusFilterMask = (dfVirus$IDENTIFIER %in% commonGenes) & !duplicated(dfVirus$IDENTIFIER) dfVirusFiltered = dfVirus[dfVirusFilterMask,] dfMotherFilterMask = dfMother$IDENTIFIER %in% commonGenes & !duplicated(dfMother$IDENTIFIER) dfMotherFiltered = dfMother[dfMotherFilterMask,] dim(dfVirusFiltered) dim(dfMotherFiltered) #qplot(dfVirusFiltered$IDENTIFIER,dfVirusFiltered$GSM1253056, geom = "point") meanVirus=colMeans(apply(dfVirusFiltered[,3:dim(dfVirusFiltered)[[2]]],1, as.numeric)) meanMother=colMeans(apply(dfMotherFiltered[,3:dim(dfMotherFiltered)[[2]]],1, as.numeric)) dfMeanVirus = data.frame(1:length(meanVirus),replicate(length(meanVirus),0),meanVirus) dfMeanMother = data.frame(1:length(meanMother),replicate(length(meanMother),1),meanMother) #gene sorting? #kommentare colnames(dfMeanVirus) colnames(dfMeanVirus)[1] = "geneid" colnames(dfMeanVirus)[2] = "sample" colnames(dfMeanVirus)[3] = "mean" colnames(dfMeanMother)[1] = "geneid" colnames(dfMeanMother)[2] = "sample" colnames(dfMeanMother)[3] = "mean" result = rbind(dfMeanVirus,dfMeanMother) qplot(result$geneid,result$mean, color=factor(result$sample)) subresult = result[result$geneid<100,] qplot(subresult$geneid,subresult$mean, color=factor(subresult$sample))
[GOAL] x : ℝ ⊢ Irrational x ↔ ∀ (a b : ℤ), x ≠ ↑a / ↑b [PROOFSTEP] simp only [Irrational, Rat.forall, cast_mk, not_exists, Set.mem_range, cast_coe_int, cast_div, eq_comm] [GOAL] r : ℝ tr : Transcendental ℚ r ⊢ Irrational r [PROOFSTEP] rintro ⟨a, rfl⟩ [GOAL] case intro a : ℚ tr : Transcendental ℚ ↑a ⊢ False [PROOFSTEP] exact tr (isAlgebraic_algebraMap a) [GOAL] x : ℝ n : ℕ m : ℤ hxr : x ^ n = ↑m hv : ¬∃ y, x = ↑y hnpos : 0 < n ⊢ Irrational x [PROOFSTEP] rintro ⟨⟨N, D, P, C⟩, rfl⟩ [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : ↑(mk' N D) ^ n = ↑m hv : ¬∃ y, ↑(mk' N D) = ↑y ⊢ False [PROOFSTEP] rw [← cast_pow] at hxr [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : ↑(mk' N D ^ n) = ↑m hv : ¬∃ y, ↑(mk' N D) = ↑y ⊢ False [PROOFSTEP] have c1 : ((D : ℤ) : ℝ) ≠ 0 := by rw [Int.cast_ne_zero, Int.coe_nat_ne_zero] exact P [GOAL] n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : ↑(mk' N D ^ n) = ↑m hv : ¬∃ y, ↑(mk' N D) = ↑y ⊢ ↑↑D ≠ 0 [PROOFSTEP] rw [Int.cast_ne_zero, Int.coe_nat_ne_zero] [GOAL] n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : ↑(mk' N D ^ n) = ↑m hv : ¬∃ y, ↑(mk' N D) = ↑y ⊢ D ≠ 0 [PROOFSTEP] exact P [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : ↑(mk' N D ^ n) = ↑m hv : ¬∃ y, ↑(mk' N D) = ↑y c1 : ↑↑D ≠ 0 ⊢ False [PROOFSTEP] have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1 [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : ↑(mk' N D ^ n) = ↑m hv : ¬∃ y, ↑(mk' N D) = ↑y c1 : ↑↑D ≠ 0 c2 : ↑↑D ^ n ≠ 0 ⊢ False [PROOFSTEP] rw [num_den', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2, ← Int.cast_pow, ← Int.cast_pow, ← Int.cast_mul, Int.cast_inj] at hxr [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : m * ↑D ^ n = N ^ n hv : ¬∃ y, ↑(mk' N D) = ↑y c1 : ↑↑D ≠ 0 c2 : ↑↑D ^ n ≠ 0 ⊢ False [PROOFSTEP] have hdivn : (D : ℤ) ^ n ∣ N ^ n := Dvd.intro_left m hxr [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : m * ↑D ^ n = N ^ n hv : ¬∃ y, ↑(mk' N D) = ↑y c1 : ↑↑D ≠ 0 c2 : ↑↑D ^ n ≠ 0 hdivn : ↑D ^ n ∣ N ^ n ⊢ False [PROOFSTEP] rw [← Int.dvd_natAbs, ← Int.coe_nat_pow, Int.coe_nat_dvd, Int.natAbs_pow, Nat.pow_dvd_pow_iff hnpos] at hdivn [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : m * ↑D ^ n = N ^ n hv : ¬∃ y, ↑(mk' N D) = ↑y c1 : ↑↑D ≠ 0 c2 : ↑↑D ^ n ≠ 0 hdivn : D ∣ Int.natAbs N ⊢ False [PROOFSTEP] obtain rfl : D = 1 := by rw [← Nat.gcd_eq_right hdivn, C.gcd_eq_one] [GOAL] n : ℕ m : ℤ hnpos : 0 < n N : ℤ D : ℕ P : D ≠ 0 C : Nat.coprime (Int.natAbs N) D hxr : m * ↑D ^ n = N ^ n hv : ¬∃ y, ↑(mk' N D) = ↑y c1 : ↑↑D ≠ 0 c2 : ↑↑D ^ n ≠ 0 hdivn : D ∣ Int.natAbs N ⊢ D = 1 [PROOFSTEP] rw [← Nat.gcd_eq_right hdivn, C.gcd_eq_one] [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ P : 1 ≠ 0 C : Nat.coprime (Int.natAbs N) 1 hxr : m * ↑1 ^ n = N ^ n hv : ¬∃ y, ↑(mk' N 1) = ↑y c1 : ↑↑1 ≠ 0 c2 : ↑↑1 ^ n ≠ 0 hdivn : 1 ∣ Int.natAbs N ⊢ False [PROOFSTEP] refine' hv ⟨N, _⟩ [GOAL] case intro.mk' n : ℕ m : ℤ hnpos : 0 < n N : ℤ P : 1 ≠ 0 C : Nat.coprime (Int.natAbs N) 1 hxr : m * ↑1 ^ n = N ^ n hv : ¬∃ y, ↑(mk' N 1) = ↑y c1 : ↑↑1 ≠ 0 c2 : ↑↑1 ^ n ≠ 0 hdivn : 1 ∣ Int.natAbs N ⊢ ↑(mk' N 1) = ↑N [PROOFSTEP] rw [num_den', Int.ofNat_one, divInt_one, cast_coe_int] [GOAL] x : ℝ n : ℕ m : ℤ hm : m ≠ 0 p : ℕ hp : Fact (Nat.Prime p) hxr : x ^ n = ↑m hv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % n ≠ 0 ⊢ Irrational x [PROOFSTEP] rcases Nat.eq_zero_or_pos n with (rfl | hnpos) [GOAL] case inl x : ℝ m : ℤ hm : m ≠ 0 p : ℕ hp : Fact (Nat.Prime p) hxr : x ^ 0 = ↑m hv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % 0 ≠ 0 ⊢ Irrational x [PROOFSTEP] rw [eq_comm, pow_zero, ← Int.cast_one, Int.cast_inj] at hxr [GOAL] case inl x : ℝ m : ℤ hm : m ≠ 0 p : ℕ hp : Fact (Nat.Prime p) hxr : m = 1 hv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % 0 ≠ 0 ⊢ Irrational x [PROOFSTEP] simp [hxr, multiplicity.one_right (mt isUnit_iff_dvd_one.1 (mt Int.coe_nat_dvd.1 hp.1.not_dvd_one)), Nat.zero_mod] at hv [GOAL] case inr x : ℝ n : ℕ m : ℤ hm : m ≠ 0 p : ℕ hp : Fact (Nat.Prime p) hxr : x ^ n = ↑m hv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % n ≠ 0 hnpos : n > 0 ⊢ Irrational x [PROOFSTEP] refine' irrational_nrt_of_notint_nrt _ _ hxr _ hnpos [GOAL] case inr x : ℝ n : ℕ m : ℤ hm : m ≠ 0 p : ℕ hp : Fact (Nat.Prime p) hxr : x ^ n = ↑m hv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % n ≠ 0 hnpos : n > 0 ⊢ ¬∃ y, x = ↑y [PROOFSTEP] rintro ⟨y, rfl⟩ [GOAL] case inr.intro n : ℕ m : ℤ hm : m ≠ 0 p : ℕ hp : Fact (Nat.Prime p) hv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % n ≠ 0 hnpos : n > 0 y : ℤ hxr : ↑y ^ n = ↑m ⊢ False [PROOFSTEP] rw [← Int.cast_pow, Int.cast_inj] at hxr [GOAL] case inr.intro n : ℕ m : ℤ hm : m ≠ 0 p : ℕ hp : Fact (Nat.Prime p) hv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % n ≠ 0 hnpos : n > 0 y : ℤ hxr : y ^ n = m ⊢ False [PROOFSTEP] subst m [GOAL] case inr.intro n p : ℕ hp : Fact (Nat.Prime p) hnpos : n > 0 y : ℤ hm : y ^ n ≠ 0 hv : Part.get (multiplicity (↑p) (y ^ n)) (_ : multiplicity.Finite (↑p) (y ^ n)) % n ≠ 0 ⊢ False [PROOFSTEP] have : y ≠ 0 := by rintro rfl rw [zero_pow hnpos] at hm exact hm rfl [GOAL] n p : ℕ hp : Fact (Nat.Prime p) hnpos : n > 0 y : ℤ hm : y ^ n ≠ 0 hv : Part.get (multiplicity (↑p) (y ^ n)) (_ : multiplicity.Finite (↑p) (y ^ n)) % n ≠ 0 ⊢ y ≠ 0 [PROOFSTEP] rintro rfl [GOAL] n p : ℕ hp : Fact (Nat.Prime p) hnpos : n > 0 hm : 0 ^ n ≠ 0 hv : Part.get (multiplicity (↑p) (0 ^ n)) (_ : multiplicity.Finite (↑p) (0 ^ n)) % n ≠ 0 ⊢ False [PROOFSTEP] rw [zero_pow hnpos] at hm [GOAL] n p : ℕ hp : Fact (Nat.Prime p) hnpos : n > 0 hm✝ : 0 ^ n ≠ 0 hm : 0 ≠ 0 hv : Part.get (multiplicity (↑p) (0 ^ n)) (_ : multiplicity.Finite (↑p) (0 ^ n)) % n ≠ 0 ⊢ False [PROOFSTEP] exact hm rfl [GOAL] case inr.intro n p : ℕ hp : Fact (Nat.Prime p) hnpos : n > 0 y : ℤ hm : y ^ n ≠ 0 hv : Part.get (multiplicity (↑p) (y ^ n)) (_ : multiplicity.Finite (↑p) (y ^ n)) % n ≠ 0 this : y ≠ 0 ⊢ False [PROOFSTEP] erw [multiplicity.pow' (Nat.prime_iff_prime_int.1 hp.1) (finite_int_iff.2 ⟨hp.1.ne_one, this⟩), Nat.mul_mod_right] at hv [GOAL] case inr.intro n p : ℕ hp : Fact (Nat.Prime p) hnpos : n > 0 y : ℤ hm : y ^ n ≠ 0 this : y ≠ 0 hv : 0 ≠ 0 ⊢ False [PROOFSTEP] exact hv rfl [GOAL] m : ℤ hm : 0 < m p : ℕ hp : Fact (Nat.Prime p) Hpv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % 2 = 1 ⊢ Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % 2 ≠ 0 [PROOFSTEP] rw [Hpv] [GOAL] m : ℤ hm : 0 < m p : ℕ hp : Fact (Nat.Prime p) Hpv : Part.get (multiplicity (↑p) m) (_ : multiplicity.Finite (↑p) m) % 2 = 1 ⊢ 1 ≠ 0 [PROOFSTEP] exact one_ne_zero [GOAL] p : ℕ hp : Prime p ⊢ Part.get (multiplicity ↑p ↑p) (_ : multiplicity.Finite ↑p ↑p) % 2 = 1 [PROOFSTEP] simp [multiplicity.multiplicity_self (mt isUnit_iff_dvd_one.1 (mt Int.coe_nat_dvd.1 hp.not_dvd_one))] [GOAL] ⊢ Irrational (Real.sqrt 2) [PROOFSTEP] simpa using Nat.prime_two.irrational_sqrt [GOAL] q : ℚ H1 : Rat.sqrt q * Rat.sqrt q = q ⊢ ↑(Rat.sqrt q) = Real.sqrt ↑q [PROOFSTEP] rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 <| Rat.sqrt_nonneg q), sqrt_eq, abs_of_nonneg (Rat.sqrt_nonneg q)] [GOAL] q : ℚ H1 : ¬Rat.sqrt q * Rat.sqrt q = q H2 : 0 ≤ q x✝ : Real.sqrt ↑q ∈ Set.range Rat.cast r : ℚ hr : ↑r = Real.sqrt ↑q ⊢ r * r = q [PROOFSTEP] rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, Rat.cast_inj] at hr [GOAL] q : ℚ H1 : ¬Rat.sqrt q * Rat.sqrt q = q H2 : 0 ≤ q x✝ : Real.sqrt ↑q ∈ Set.range Rat.cast r : ℚ hr : Real.sqrt ↑q = ↑r ⊢ 0 ≤ ↑r [PROOFSTEP] rw [← hr] [GOAL] q : ℚ H1 : ¬Rat.sqrt q * Rat.sqrt q = q H2 : 0 ≤ q x✝ : Real.sqrt ↑q ∈ Set.range Rat.cast r : ℚ hr : Real.sqrt ↑q = ↑r ⊢ 0 ≤ Real.sqrt ↑q [PROOFSTEP] exact Real.sqrt_nonneg _ [GOAL] q : ℚ H1 : ¬Rat.sqrt q * Rat.sqrt q = q H2 : ¬0 ≤ q ⊢ ↑0 = Real.sqrt ↑q [PROOFSTEP] rw [cast_zero] [GOAL] q : ℚ H1 : ¬Rat.sqrt q * Rat.sqrt q = q H2 : ¬0 ≤ q ⊢ 0 = Real.sqrt ↑q [PROOFSTEP] exact (sqrt_eq_zero_of_nonpos (Rat.cast_nonpos.2 <| le_of_not_le H2)).symm [GOAL] x : ℝ h : Irrational x m : ℤ ⊢ x ≠ ↑m [PROOFSTEP] rw [← Rat.cast_coe_int] [GOAL] x : ℝ h : Irrational x m : ℤ ⊢ x ≠ ↑↑m [PROOFSTEP] exact h.ne_rat _ [GOAL] x : ℝ h : Irrational x ⊢ x ≠ 0 [PROOFSTEP] exact_mod_cast h.ne_nat 0 [GOAL] x : ℝ h : Irrational x ⊢ x ≠ 1 [PROOFSTEP] simpa only [Nat.cast_one] using h.ne_nat 1 [GOAL] q : ℚ x y : ℝ ⊢ Irrational (x + y) → Irrational x ∨ Irrational y [PROOFSTEP] delta Irrational [GOAL] q : ℚ x y : ℝ ⊢ ¬x + y ∈ Set.range Rat.cast → ¬x ∈ Set.range Rat.cast ∨ ¬y ∈ Set.range Rat.cast [PROOFSTEP] contrapose! [GOAL] q : ℚ x y : ℝ ⊢ x ∈ Set.range Rat.cast ∧ y ∈ Set.range Rat.cast → x + y ∈ Set.range Rat.cast [PROOFSTEP] rintro ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩ [GOAL] case intro.intro.intro q rx ry : ℚ ⊢ ↑rx + ↑ry ∈ Set.range Rat.cast [PROOFSTEP] exact ⟨rx + ry, cast_add rx ry⟩ [GOAL] q : ℚ x y : ℝ h : Irrational x ⊢ Irrational (↑(-q) + (↑q + x)) [PROOFSTEP] rwa [cast_neg, neg_add_cancel_left] [GOAL] q : ℚ x y : ℝ m : ℤ h : Irrational (↑m + x) ⊢ Irrational x [PROOFSTEP] rw [← cast_coe_int] at h [GOAL] q : ℚ x y : ℝ m : ℤ h : Irrational (↑↑m + x) ⊢ Irrational x [PROOFSTEP] exact h.of_rat_add m [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ ⊢ Irrational (↑m + x) [PROOFSTEP] rw [← cast_coe_int] [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ ⊢ Irrational (↑↑m + x) [PROOFSTEP] exact h.rat_add m [GOAL] q✝ : ℚ x y : ℝ h : Irrational (-x) x✝ : x ∈ Set.range Rat.cast q : ℚ hx : ↑q = x ⊢ ↑(-q) = -x [PROOFSTEP] rw [cast_neg, hx] [GOAL] q : ℚ x y : ℝ h : Irrational x ⊢ Irrational (- -x) [PROOFSTEP] rwa [neg_neg] [GOAL] q : ℚ x y : ℝ h : Irrational x ⊢ Irrational (x - ↑q) [PROOFSTEP] simpa only [sub_eq_add_neg, cast_neg] using h.add_rat (-q) [GOAL] q : ℚ x y : ℝ h : Irrational x ⊢ Irrational (↑q - x) [PROOFSTEP] simpa only [sub_eq_add_neg] using h.neg.rat_add q [GOAL] q : ℚ x y : ℝ h : Irrational (x - ↑q) ⊢ Irrational (x + ↑(-q)) [PROOFSTEP] simpa only [cast_neg, sub_eq_add_neg] using h [GOAL] q : ℚ x y : ℝ h : Irrational (↑q - x) ⊢ Irrational (↑q + -x) [PROOFSTEP] simpa only [sub_eq_add_neg] using h [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ ⊢ Irrational (x - ↑m) [PROOFSTEP] simpa only [Rat.cast_coe_int] using h.sub_rat m [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ ⊢ Irrational (↑m - x) [PROOFSTEP] simpa only [Rat.cast_coe_int] using h.rat_sub m [GOAL] q : ℚ x y : ℝ m : ℤ h : Irrational (x - ↑m) ⊢ Irrational (x - ↑↑m) [PROOFSTEP] rwa [Rat.cast_coe_int] [GOAL] q : ℚ x y : ℝ m : ℤ h : Irrational (↑m - x) ⊢ Irrational (↑↑m - x) [PROOFSTEP] rwa [Rat.cast_coe_int] [GOAL] q : ℚ x y : ℝ ⊢ Irrational (x * y) → Irrational x ∨ Irrational y [PROOFSTEP] delta Irrational [GOAL] q : ℚ x y : ℝ ⊢ ¬x * y ∈ Set.range Rat.cast → ¬x ∈ Set.range Rat.cast ∨ ¬y ∈ Set.range Rat.cast [PROOFSTEP] contrapose! [GOAL] q : ℚ x y : ℝ ⊢ x ∈ Set.range Rat.cast ∧ y ∈ Set.range Rat.cast → x * y ∈ Set.range Rat.cast [PROOFSTEP] rintro ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩ [GOAL] case intro.intro.intro q rx ry : ℚ ⊢ ↑rx * ↑ry ∈ Set.range Rat.cast [PROOFSTEP] exact ⟨rx * ry, cast_mul rx ry⟩ [GOAL] q✝ : ℚ x y : ℝ h : Irrational x q : ℚ hq : q ≠ 0 ⊢ Irrational (x * ↑q * ↑q⁻¹) [PROOFSTEP] rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one] [GOAL] q : ℚ x y : ℝ m : ℤ h : Irrational (x * ↑m) ⊢ Irrational (x * ↑↑m) [PROOFSTEP] rwa [cast_coe_int] [GOAL] q : ℚ x y : ℝ m : ℤ h : Irrational (↑m * x) ⊢ Irrational (↑↑m * x) [PROOFSTEP] rwa [cast_coe_int] [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ hm : m ≠ 0 ⊢ Irrational (x * ↑m) [PROOFSTEP] rw [← cast_coe_int] [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ hm : m ≠ 0 ⊢ Irrational (x * ↑↑m) [PROOFSTEP] refine' h.mul_rat _ [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ hm : m ≠ 0 ⊢ ↑m ≠ 0 [PROOFSTEP] rwa [Int.cast_ne_zero] [GOAL] q : ℚ x y : ℝ h : Irrational x ⊢ Irrational x⁻¹⁻¹ [PROOFSTEP] rwa [inv_inv] [GOAL] q✝ : ℚ x y : ℝ h : Irrational x q : ℚ hq : q ≠ 0 ⊢ Irrational (x / ↑q) [PROOFSTEP] rw [div_eq_mul_inv, ← cast_inv] [GOAL] q✝ : ℚ x y : ℝ h : Irrational x q : ℚ hq : q ≠ 0 ⊢ Irrational (x * ↑q⁻¹) [PROOFSTEP] exact h.mul_rat (inv_ne_zero hq) [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ hm : m ≠ 0 ⊢ Irrational (x / ↑m) [PROOFSTEP] rw [← cast_coe_int] [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ hm : m ≠ 0 ⊢ Irrational (x / ↑↑m) [PROOFSTEP] refine' h.div_rat _ [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℤ hm : m ≠ 0 ⊢ ↑m ≠ 0 [PROOFSTEP] rwa [Int.cast_ne_zero] [GOAL] q : ℚ x y : ℝ h : Irrational x m : ℕ hm : m ≠ 0 ⊢ ↑m ≠ 0 [PROOFSTEP] rwa [Int.coe_nat_ne_zero] [GOAL] q : ℚ x y : ℝ h : Irrational (1 / x) ⊢ Irrational (↑1 / x) [PROOFSTEP] rwa [cast_one] [GOAL] q : ℚ x y : ℝ h : Irrational (x ^ 0) ⊢ Irrational x [PROOFSTEP] rw [pow_zero] at h [GOAL] q : ℚ x y : ℝ h : Irrational 1 ⊢ Irrational x [PROOFSTEP] exact (h ⟨1, cast_one⟩).elim [GOAL] q : ℚ x y : ℝ n : ℕ h : Irrational (x ^ (n + 1)) ⊢ Irrational x [PROOFSTEP] rw [pow_succ] at h [GOAL] q : ℚ x y : ℝ n : ℕ h : Irrational (x * x ^ n) ⊢ Irrational x [PROOFSTEP] exact h.mul_cases.elim id (of_pow n) [GOAL] q : ℚ x y : ℝ n : ℕ h : Irrational (x ^ ↑n) ⊢ Irrational x [PROOFSTEP] rw [zpow_ofNat] at h [GOAL] q : ℚ x y : ℝ n : ℕ h : Irrational (x ^ n) ⊢ Irrational x [PROOFSTEP] exact h.of_pow _ [GOAL] q : ℚ x y : ℝ n : ℕ h : Irrational (x ^ -[n+1]) ⊢ Irrational x [PROOFSTEP] rw [zpow_negSucc] at h [GOAL] q : ℚ x y : ℝ n : ℕ h : Irrational (x ^ (n + 1))⁻¹ ⊢ Irrational x [PROOFSTEP] exact h.of_inv.of_pow _ [GOAL] x : ℝ p : ℤ[X] hx : Irrational x p_nonzero : p ≠ 0 x_is_root : ↑(aeval x) p = 0 ⊢ 1 < natDegree p [PROOFSTEP] by_contra rid [GOAL] x : ℝ p : ℤ[X] hx : Irrational x p_nonzero : p ≠ 0 x_is_root : ↑(aeval x) p = 0 rid : ¬1 < natDegree p ⊢ False [PROOFSTEP] rcases exists_eq_X_add_C_of_natDegree_le_one (not_lt.1 rid) with ⟨a, b, rfl⟩ [GOAL] case intro.intro x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 rid : ¬1 < natDegree (↑C a * X + ↑C b) ⊢ False [PROOFSTEP] clear rid [GOAL] case intro.intro x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 ⊢ False [PROOFSTEP] have : (a : ℝ) * x = -b := by simpa [eq_neg_iff_add_eq_zero] using x_is_root [GOAL] x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 ⊢ ↑a * x = -↑b [PROOFSTEP] simpa [eq_neg_iff_add_eq_zero] using x_is_root [GOAL] case intro.intro x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 this : ↑a * x = -↑b ⊢ False [PROOFSTEP] rcases em (a = 0) with (rfl | ha) [GOAL] case intro.intro.inl x : ℝ hx : Irrational x b : ℤ p_nonzero : ↑C 0 * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C 0 * X + ↑C b) = 0 this : ↑0 * x = -↑b ⊢ False [PROOFSTEP] obtain rfl : b = 0 := by simpa [GOAL] x : ℝ hx : Irrational x b : ℤ p_nonzero : ↑C 0 * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C 0 * X + ↑C b) = 0 this : ↑0 * x = -↑b ⊢ b = 0 [PROOFSTEP] simpa [GOAL] case intro.intro.inl x : ℝ hx : Irrational x p_nonzero : ↑C 0 * X + ↑C 0 ≠ 0 x_is_root : ↑(aeval x) (↑C 0 * X + ↑C 0) = 0 this : ↑0 * x = -↑0 ⊢ False [PROOFSTEP] simp at p_nonzero [GOAL] case intro.intro.inr x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 this : ↑a * x = -↑b ha : ¬a = 0 ⊢ False [PROOFSTEP] rw [mul_comm, ← eq_div_iff_mul_eq, eq_comm] at this [GOAL] case intro.intro.inr x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 this : -↑b / ↑a = x ha : ¬a = 0 ⊢ False case intro.intro.inr x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 this : x * ↑a = -↑b ha : ¬a = 0 ⊢ ↑a ≠ 0 [PROOFSTEP] refine' hx ⟨-b / a, _⟩ [GOAL] case intro.intro.inr x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 this : -↑b / ↑a = x ha : ¬a = 0 ⊢ ↑(-↑b / ↑a) = x case intro.intro.inr x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 this : x * ↑a = -↑b ha : ¬a = 0 ⊢ ↑a ≠ 0 [PROOFSTEP] assumption_mod_cast [GOAL] case intro.intro.inr x : ℝ hx : Irrational x a b : ℤ p_nonzero : ↑C a * X + ↑C b ≠ 0 x_is_root : ↑(aeval x) (↑C a * X + ↑C b) = 0 this : x * ↑a = -↑b ha : ¬a = 0 ⊢ ↑a ≠ 0 [PROOFSTEP] assumption_mod_cast [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (x * ↑q) ↔ q ≠ 0 ∧ Irrational x [PROOFSTEP] rw [mul_comm, irrational_rat_mul_iff] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (↑m * x) ↔ m ≠ 0 ∧ Irrational x [PROOFSTEP] rw [← cast_coe_int, irrational_rat_mul_iff, Int.cast_ne_zero] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (x * ↑m) ↔ m ≠ 0 ∧ Irrational x [PROOFSTEP] rw [← cast_coe_int, irrational_mul_rat_iff, Int.cast_ne_zero] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (↑n * x) ↔ n ≠ 0 ∧ Irrational x [PROOFSTEP] rw [← cast_coe_nat, irrational_rat_mul_iff, Nat.cast_ne_zero] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (x * ↑n) ↔ n ≠ 0 ∧ Irrational x [PROOFSTEP] rw [← cast_coe_nat, irrational_mul_rat_iff, Nat.cast_ne_zero] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (↑q / x) ↔ q ≠ 0 ∧ Irrational x [PROOFSTEP] simp [div_eq_mul_inv] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (x / ↑q) ↔ q ≠ 0 ∧ Irrational x [PROOFSTEP] rw [div_eq_mul_inv, ← cast_inv, irrational_mul_rat_iff, Ne.def, inv_eq_zero] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (↑m / x) ↔ m ≠ 0 ∧ Irrational x [PROOFSTEP] simp [div_eq_mul_inv] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (x / ↑m) ↔ m ≠ 0 ∧ Irrational x [PROOFSTEP] rw [← cast_coe_int, irrational_div_rat_iff, Int.cast_ne_zero] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (↑n / x) ↔ n ≠ 0 ∧ Irrational x [PROOFSTEP] simp [div_eq_mul_inv] [GOAL] q : ℚ m : ℤ n : ℕ x : ℝ ⊢ Irrational (x / ↑n) ↔ n ≠ 0 ∧ Irrational x [PROOFSTEP] rw [← cast_coe_nat, irrational_div_rat_iff, Nat.cast_ne_zero]
All bright steam cleaning services philosophy is simple – outstanding customer service, the best network for your present and future needs and your complete satisfaction. Don't risk your communications – call us now. All bright steam cleaning services is a customer-focused and quality-driven Home Services (Home and Building Services) business based in Morphett Vale, SA . We take great pride in the work we do.We have built and maintained a loyal customer base, which includes domestic and commercial clients. We became established throughout Morphett Vale and surrounding suburbs by offering excellent customer service and maintaining both integrity and accountability of our work. We guarantee quality results and are totally committed to customer satisfaction. If you live in Morphett Vale or surrounding suburbs, please get in touch for all of your Home and Building Services needs.
[GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α ⊢ ⊤ * ⊤ = ⊤ [PROOFSTEP] simp [mul_def] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α ⊢ Option.map₂ (fun x x_1 => x * x_1) ⊤ ⊤ = ⊤ [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a : WithTop α ⊢ a * ⊤ = if a = 0 then 0 else ⊤ [PROOFSTEP] induction a using recTopCoe [GOAL] case top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α ⊢ ⊤ * ⊤ = if ⊤ = 0 then 0 else ⊤ [PROOFSTEP] simp [mul_def] [GOAL] case coe α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a✝ : α ⊢ ↑a✝ * ⊤ = if ↑a✝ = 0 then 0 else ⊤ [PROOFSTEP] simp [mul_def] [GOAL] case top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α ⊢ Option.map₂ (fun x x_1 => x * x_1) ⊤ ⊤ = ⊤ [PROOFSTEP] rfl [GOAL] case coe α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a✝ : α ⊢ (if a✝ = 0 then 0 else Option.map₂ (fun x x_1 => x * x_1) ↑a✝ ⊤) = if a✝ = 0 then 0 else ⊤ [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a : WithTop α h : a ≠ 0 ⊢ a * ⊤ = ⊤ [PROOFSTEP] rw [mul_top', if_neg h] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a : WithTop α ⊢ ⊤ * a = if a = 0 then 0 else ⊤ [PROOFSTEP] induction a using recTopCoe [GOAL] case top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α ⊢ ⊤ * ⊤ = if ⊤ = 0 then 0 else ⊤ [PROOFSTEP] simp [mul_def] [GOAL] case coe α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a✝ : α ⊢ ⊤ * ↑a✝ = if ↑a✝ = 0 then 0 else ⊤ [PROOFSTEP] simp [mul_def] [GOAL] case top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α ⊢ Option.map₂ (fun x x_1 => x * x_1) ⊤ ⊤ = ⊤ [PROOFSTEP] rfl [GOAL] case coe α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a✝ : α ⊢ (if a✝ = 0 then 0 else Option.map₂ (fun x x_1 => x * x_1) ⊤ ↑a✝) = if a✝ = 0 then 0 else ⊤ [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a : WithTop α h : a ≠ 0 ⊢ ⊤ * a = ⊤ [PROOFSTEP] rw [top_mul', if_neg h] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a b : WithTop α ⊢ a * b = ⊤ ↔ a ≠ 0 ∧ b = ⊤ ∨ a = ⊤ ∧ b ≠ 0 [PROOFSTEP] rw [mul_def, ite_eq_iff, ← none_eq_top, Option.map₂_eq_none_iff] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a b : WithTop α ⊢ (a = 0 ∨ b = 0) ∧ 0 = none ∨ ¬(a = 0 ∨ b = 0) ∧ (a = none ∨ b = none) ↔ a ≠ 0 ∧ b = none ∨ a = none ∧ b ≠ 0 [PROOFSTEP] have ha : a = 0 → a ≠ none := fun h => h.symm ▸ zero_ne_top [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a b : WithTop α ha : a = 0 → a ≠ none ⊢ (a = 0 ∨ b = 0) ∧ 0 = none ∨ ¬(a = 0 ∨ b = 0) ∧ (a = none ∨ b = none) ↔ a ≠ 0 ∧ b = none ∨ a = none ∧ b ≠ 0 [PROOFSTEP] have hb : b = 0 → b ≠ none := fun h => h.symm ▸ zero_ne_top [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : Zero α inst✝ : Mul α a b : WithTop α ha : a = 0 → a ≠ none hb : b = 0 → b ≠ none ⊢ (a = 0 ∨ b = 0) ∧ 0 = none ∨ ¬(a = 0 ∨ b = 0) ∧ (a = none ∨ b = none) ↔ a ≠ 0 ∧ b = none ∨ a = none ∧ b ≠ 0 [PROOFSTEP] tauto [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Zero α inst✝¹ : Mul α inst✝ : LT α a b : WithTop α ha : a < ⊤ hb : b < ⊤ ⊢ a * b < ⊤ [PROOFSTEP] rw [WithTop.lt_top_iff_ne_top] at * [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Zero α inst✝¹ : Mul α inst✝ : LT α a b : WithTop α ha : a ≠ ⊤ hb : b ≠ ⊤ ⊢ a * b ≠ ⊤ [PROOFSTEP] simp only [Ne.def, mul_eq_top_iff, *, and_false, false_and, false_or] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Zero α inst✝¹ : Mul α inst✝ : NoZeroDivisors α ⊢ NoZeroDivisors (WithTop α) [PROOFSTEP] refine ⟨fun h₁ => Decidable.by_contradiction <| fun h₂ => ?_⟩ [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Zero α inst✝¹ : Mul α inst✝ : NoZeroDivisors α a✝ b✝ : WithTop α h₁ : a✝ * b✝ = 0 h₂ : ¬(a✝ = 0 ∨ b✝ = 0) ⊢ False [PROOFSTEP] rw [mul_def, if_neg h₂] at h₁ [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : Zero α inst✝¹ : Mul α inst✝ : NoZeroDivisors α a✝ b✝ : WithTop α h₁ : Option.map₂ (fun x x_1 => x * x_1) a✝ b✝ = 0 h₂ : ¬(a✝ = 0 ∨ b✝ = 0) ⊢ False [PROOFSTEP] rcases Option.mem_map₂_iff.1 h₁ with ⟨a, b, (rfl : _ = _), (rfl : _ = _), hab⟩ [GOAL] case intro.intro.intro.intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : Zero α inst✝¹ : Mul α inst✝ : NoZeroDivisors α a b : α hab : a * b = 0 h₁ : Option.map₂ (fun x x_1 => x * x_1) (Option.some a) (Option.some b) = 0 h₂ : ¬(Option.some a = 0 ∨ Option.some b = 0) ⊢ False [PROOFSTEP] exact h₂ ((eq_zero_or_eq_zero_of_mul_eq_zero hab).imp (congr_arg some) (congr_arg some)) [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : α ⊢ ↑(a * b) = ↑a * ↑b [PROOFSTEP] by_cases ha : a = 0 [GOAL] case pos α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : α ha : a = 0 ⊢ ↑(a * b) = ↑a * ↑b [PROOFSTEP] simp [ha] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : α ha : ¬a = 0 ⊢ ↑(a * b) = ↑a * ↑b [PROOFSTEP] by_cases hb : b = 0 [GOAL] case pos α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : α ha : ¬a = 0 hb : b = 0 ⊢ ↑(a * b) = ↑a * ↑b [PROOFSTEP] simp [hb] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : α ha : ¬a = 0 hb : ¬b = 0 ⊢ ↑(a * b) = ↑a * ↑b [PROOFSTEP] simp [*, mul_def] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : α ha : ¬a = 0 hb : ¬b = 0 ⊢ ↑(a * b) = Option.map₂ (fun x x_1 => x * x_1) ↑a ↑b [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α b : α hb : b ≠ 0 ⊢ (if ⊤ = 0 ∨ ↑b = 0 then 0 else ⊤) = ⊤ [PROOFSTEP] simp [hb] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α b : α hb : b ≠ 0 a : α ⊢ Option.some a * ↑b = Option.bind (Option.some a) fun a => Option.some (a * b) [PROOFSTEP] rw [some_eq_coe, ← coe_mul] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α b : α hb : b ≠ 0 a : α ⊢ ↑(a * b) = Option.bind ↑a fun a => Option.some (a * b) [PROOFSTEP] rfl [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : WithTop α ⊢ untop' 0 (a * b) = untop' 0 a * untop' 0 b [PROOFSTEP] by_cases ha : a = 0 [GOAL] case pos α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : WithTop α ha : a = 0 ⊢ untop' 0 (a * b) = untop' 0 a * untop' 0 b [PROOFSTEP] rw [ha, zero_mul, ← coe_zero, untop'_coe, zero_mul] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : WithTop α ha : ¬a = 0 ⊢ untop' 0 (a * b) = untop' 0 a * untop' 0 b [PROOFSTEP] by_cases hb : b = 0 [GOAL] case pos α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : WithTop α ha : ¬a = 0 hb : b = 0 ⊢ untop' 0 (a * b) = untop' 0 a * untop' 0 b [PROOFSTEP] rw [hb, mul_zero, ← coe_zero, untop'_coe, mul_zero] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a b : WithTop α ha : ¬a = 0 hb : ¬b = 0 ⊢ untop' 0 (a * b) = untop' 0 a * untop' 0 b [PROOFSTEP] induction a using WithTop.recTopCoe [GOAL] case neg.top α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α b : WithTop α hb : ¬b = 0 ha : ¬⊤ = 0 ⊢ untop' 0 (⊤ * b) = untop' 0 ⊤ * untop' 0 b [PROOFSTEP] rw [top_mul hb, untop'_top, zero_mul] [GOAL] case neg.coe α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α b : WithTop α hb : ¬b = 0 a✝ : α ha : ¬↑a✝ = 0 ⊢ untop' 0 (↑a✝ * b) = untop' 0 ↑a✝ * untop' 0 b [PROOFSTEP] induction b using WithTop.recTopCoe [GOAL] case neg.coe.top α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a✝ : α ha : ¬↑a✝ = 0 hb : ¬⊤ = 0 ⊢ untop' 0 (↑a✝ * ⊤) = untop' 0 ↑a✝ * untop' 0 ⊤ [PROOFSTEP] rw [mul_top ha, untop'_top, mul_zero] [GOAL] case neg.coe.coe α : Type u_1 inst✝¹ : DecidableEq α inst✝ : MulZeroClass α a✝¹ : α ha : ¬↑a✝¹ = 0 a✝ : α hb : ¬↑a✝ = 0 ⊢ untop' 0 (↑a✝¹ * ↑a✝) = untop' 0 ↑a✝¹ * untop' 0 ↑a✝ [PROOFSTEP] rw [← coe_mul, untop'_coe, untop'_coe, untop'_coe] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : MulZeroOneClass α inst✝ : Nontrivial α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ : WithTop α a : α ⊢ 1 * ↑a = ↑a [PROOFSTEP] rw [← coe_one, ← coe_mul, one_mul] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : MulZeroOneClass α inst✝ : Nontrivial α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ : WithTop α a : α ⊢ ↑a * 1 = ↑a [PROOFSTEP] rw [← coe_one, ← coe_mul, mul_one] [GOAL] α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x y : WithTop R ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (x * y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } y [PROOFSTEP] have : ∀ z, map f z = 0 ↔ z = 0 := fun z => (Option.map_injective hf).eq_iff' f.toZeroHom.withTopMap.map_zero [GOAL] α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (x * y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } y [PROOFSTEP] rcases Decidable.eq_or_ne x 0 with (rfl | hx) [GOAL] case inl α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (0 * y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } 0 * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } y [PROOFSTEP] simp [GOAL] case inr α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx : x ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (x * y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } y [PROOFSTEP] rcases Decidable.eq_or_ne y 0 with (rfl | hy) [GOAL] case inr.inl α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx : x ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (x * 0) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } 0 [PROOFSTEP] simp [GOAL] case inr.inr α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx : x ≠ 0 hy : y ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (x * y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } y [PROOFSTEP] induction' x using WithTop.recTopCoe with x [GOAL] case inr.inr.top α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx✝ : x ≠ 0 hy : y ≠ 0 hx : ⊤ ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (⊤ * y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ⊤ * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } y [PROOFSTEP] simp [hy, this] [GOAL] case inr.inr.coe α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x✝ y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx✝ : x✝ ≠ 0 hy : y ≠ 0 x : R hx : ↑x ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (↑x * y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ↑x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } y [PROOFSTEP] induction' y using WithTop.recTopCoe with y [GOAL] case inr.inr.coe.top α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x✝ y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx✝ : x✝ ≠ 0 hy✝ : y ≠ 0 x : R hx : ↑x ≠ 0 hy : ⊤ ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (↑x * ⊤) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ↑x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ⊤ [PROOFSTEP] have : (f x : WithTop S) ≠ 0 := by simpa [hf.eq_iff' (map_zero f)] using hx [GOAL] α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x✝ y : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx✝ : x✝ ≠ 0 hy✝ : y ≠ 0 x : R hx : ↑x ≠ 0 hy : ⊤ ≠ 0 ⊢ ↑(↑f x) ≠ 0 [PROOFSTEP] simpa [hf.eq_iff' (map_zero f)] using hx [GOAL] case inr.inr.coe.top α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x✝ y : WithTop R this✝ : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx✝ : x✝ ≠ 0 hy✝ : y ≠ 0 x : R hx : ↑x ≠ 0 hy : ⊤ ≠ 0 this : ↑(↑f x) ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (↑x * ⊤) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ↑x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ⊤ [PROOFSTEP] simp [mul_top hx, mul_top this] [GOAL] case inr.inr.coe.coe α : Type u_1 inst✝⁶ : DecidableEq α R : Type u_2 S : Type u_3 inst✝⁵ : MulZeroOneClass R inst✝⁴ : DecidableEq R inst✝³ : Nontrivial R inst✝² : MulZeroOneClass S inst✝¹ : DecidableEq S inst✝ : Nontrivial S f : R →*₀ S hf : Function.Injective ↑f src✝¹ : ZeroHom (WithTop R) (WithTop S) := ZeroHom.withTopMap ↑f src✝ : OneHom (WithTop R) (WithTop S) := OneHom.withTopMap ↑↑f x✝ y✝ : WithTop R this : ∀ (z : WithTop R), map (↑f) z = 0 ↔ z = 0 hx✝ : x✝ ≠ 0 hy✝ : y✝ ≠ 0 x : R hx : ↑x ≠ 0 y : R hy : ↑y ≠ 0 ⊢ ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } (↑x * ↑y) = ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ↑x * ZeroHom.toFun { toFun := map ↑f, map_zero' := (_ : ZeroHom.toFun src✝¹ 0 = 0) } ↑y [PROOFSTEP] simp only [map_coe, ← coe_mul, map_mul] [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a b c : WithTop α ⊢ a * b * c = a * (b * c) [PROOFSTEP] rcases eq_or_ne a 0 with (rfl | ha) [GOAL] case inl α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop b c : WithTop α ⊢ 0 * b * c = 0 * (b * c) [PROOFSTEP] simp only [zero_mul] [GOAL] case inr α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a b c : WithTop α ha : a ≠ 0 ⊢ a * b * c = a * (b * c) [PROOFSTEP] rcases eq_or_ne b 0 with (rfl | hb) [GOAL] case inr.inl α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a c : WithTop α ha : a ≠ 0 ⊢ a * 0 * c = a * (0 * c) [PROOFSTEP] simp only [zero_mul, mul_zero] [GOAL] case inr.inr α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a b c : WithTop α ha : a ≠ 0 hb : b ≠ 0 ⊢ a * b * c = a * (b * c) [PROOFSTEP] rcases eq_or_ne c 0 with (rfl | hc) [GOAL] case inr.inr.inl α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a b : WithTop α ha : a ≠ 0 hb : b ≠ 0 ⊢ a * b * 0 = a * (b * 0) [PROOFSTEP] simp only [mul_zero] -- Porting note: below needed to be rewritten due to changed `simp` behaviour for `coe` [GOAL] case inr.inr.inr α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a b c : WithTop α ha : a ≠ 0 hb : b ≠ 0 hc : c ≠ 0 ⊢ a * b * c = a * (b * c) [PROOFSTEP] induction' a using WithTop.recTopCoe with a [GOAL] case inr.inr.inr.top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a b c : WithTop α ha✝ : a ≠ 0 hb : b ≠ 0 hc : c ≠ 0 ha : ⊤ ≠ 0 ⊢ ⊤ * b * c = ⊤ * (b * c) [PROOFSTEP] simp [hb, hc] [GOAL] case inr.inr.inr.coe α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ b c : WithTop α ha✝ : a✝ ≠ 0 hb : b ≠ 0 hc : c ≠ 0 a : α ha : ↑a ≠ 0 ⊢ ↑a * b * c = ↑a * (b * c) [PROOFSTEP] induction' b using WithTop.recTopCoe with b [GOAL] case inr.inr.inr.coe.top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ b c : WithTop α ha✝ : a✝ ≠ 0 hb✝ : b ≠ 0 hc : c ≠ 0 a : α ha : ↑a ≠ 0 hb : ⊤ ≠ 0 ⊢ ↑a * ⊤ * c = ↑a * (⊤ * c) [PROOFSTEP] simp [mul_top ha, top_mul hc] [GOAL] case inr.inr.inr.coe.coe α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ b✝ c : WithTop α ha✝ : a✝ ≠ 0 hb✝ : b✝ ≠ 0 hc : c ≠ 0 a : α ha : ↑a ≠ 0 b : α hb : ↑b ≠ 0 ⊢ ↑a * ↑b * c = ↑a * (↑b * c) [PROOFSTEP] induction' c using WithTop.recTopCoe with c [GOAL] case inr.inr.inr.coe.coe.top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ b✝ c : WithTop α ha✝ : a✝ ≠ 0 hb✝ : b✝ ≠ 0 hc✝ : c ≠ 0 a : α ha : ↑a ≠ 0 b : α hb : ↑b ≠ 0 hc : ⊤ ≠ 0 ⊢ ↑a * ↑b * ⊤ = ↑a * (↑b * ⊤) [PROOFSTEP] rw [mul_top hb, mul_top ha] [GOAL] case inr.inr.inr.coe.coe.top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ b✝ c : WithTop α ha✝ : a✝ ≠ 0 hb✝ : b✝ ≠ 0 hc✝ : c ≠ 0 a : α ha : ↑a ≠ 0 b : α hb : ↑b ≠ 0 hc : ⊤ ≠ 0 ⊢ ↑a * ↑b * ⊤ = ⊤ [PROOFSTEP] rw [← coe_zero, ne_eq, coe_eq_coe] at ha hb [GOAL] case inr.inr.inr.coe.coe.top α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ b✝ c : WithTop α ha✝ : a✝ ≠ 0 hb✝ : b✝ ≠ 0 hc✝ : c ≠ 0 a : α ha : ¬a = 0 b : α hb : ¬b = 0 hc : ⊤ ≠ 0 ⊢ ↑a * ↑b * ⊤ = ⊤ [PROOFSTEP] simp [ha, hb] [GOAL] case inr.inr.inr.coe.coe.coe α : Type u_1 inst✝² : DecidableEq α inst✝¹ : SemigroupWithZero α inst✝ : NoZeroDivisors α src✝ : MulZeroClass (WithTop α) := instMulZeroClassWithTop a✝ b✝ c✝ : WithTop α ha✝ : a✝ ≠ 0 hb✝ : b✝ ≠ 0 hc✝ : c✝ ≠ 0 a : α ha : ↑a ≠ 0 b : α hb : ↑b ≠ 0 c : α hc : ↑c ≠ 0 ⊢ ↑a * ↑b * ↑c = ↑a * (↑b * ↑c) [PROOFSTEP] simp only [← coe_mul, mul_assoc] [GOAL] α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b c : WithTop α ⊢ (a + b) * c = a * c + b * c [PROOFSTEP] induction' c using WithTop.recTopCoe with c [GOAL] case top α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b : WithTop α ⊢ (a + b) * ⊤ = a * ⊤ + b * ⊤ [PROOFSTEP] by_cases ha : a = 0 [GOAL] case pos α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b : WithTop α ha : a = 0 ⊢ (a + b) * ⊤ = a * ⊤ + b * ⊤ [PROOFSTEP] simp [ha] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b : WithTop α ha : ¬a = 0 ⊢ (a + b) * ⊤ = a * ⊤ + b * ⊤ [PROOFSTEP] simp [ha] [GOAL] case coe α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b : WithTop α c : α ⊢ (a + b) * ↑c = a * ↑c + b * ↑c [PROOFSTEP] by_cases hc : c = 0 [GOAL] case pos α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b : WithTop α c : α hc : c = 0 ⊢ (a + b) * ↑c = a * ↑c + b * ↑c [PROOFSTEP] simp [hc] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b : WithTop α c : α hc : ¬c = 0 ⊢ (a + b) * ↑c = a * ↑c + b * ↑c [PROOFSTEP] simp [mul_coe hc] [GOAL] case neg α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α a b : WithTop α c : α hc : ¬c = 0 ⊢ (Option.bind (a + b) fun a => Option.some (a * c)) = (Option.bind a fun a => Option.some (a * c)) + Option.bind b fun a => Option.some (a * c) [PROOFSTEP] cases a [GOAL] case neg.none α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α b : WithTop α c : α hc : ¬c = 0 ⊢ (Option.bind (none + b) fun a => Option.some (a * c)) = (Option.bind none fun a => Option.some (a * c)) + Option.bind b fun a => Option.some (a * c) [PROOFSTEP] cases b [GOAL] case neg.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α b : WithTop α c : α hc : ¬c = 0 val✝ : α ⊢ (Option.bind (Option.some val✝ + b) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝) fun a => Option.some (a * c)) + Option.bind b fun a => Option.some (a * c) [PROOFSTEP] cases b [GOAL] case neg.none.none α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 ⊢ (Option.bind (none + none) fun a => Option.some (a * c)) = (Option.bind none fun a => Option.some (a * c)) + Option.bind none fun a => Option.some (a * c) case neg.none.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝ : α ⊢ (Option.bind (none + Option.some val✝) fun a => Option.some (a * c)) = (Option.bind none fun a => Option.some (a * c)) + Option.bind (Option.some val✝) fun a => Option.some (a * c) case neg.some.none α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝ : α ⊢ (Option.bind (Option.some val✝ + none) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝) fun a => Option.some (a * c)) + Option.bind none fun a => Option.some (a * c) case neg.some.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝¹ val✝ : α ⊢ (Option.bind (Option.some val✝¹ + Option.some val✝) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝¹) fun a => Option.some (a * c)) + Option.bind (Option.some val✝) fun a => Option.some (a * c) [PROOFSTEP] repeat' first | rfl | exact congr_arg some (add_mul _ _ _) [GOAL] case neg.none.none α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 ⊢ (Option.bind (none + none) fun a => Option.some (a * c)) = (Option.bind none fun a => Option.some (a * c)) + Option.bind none fun a => Option.some (a * c) [PROOFSTEP] first | rfl | exact congr_arg some (add_mul _ _ _) [GOAL] case neg.none.none α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 ⊢ (Option.bind (none + none) fun a => Option.some (a * c)) = (Option.bind none fun a => Option.some (a * c)) + Option.bind none fun a => Option.some (a * c) [PROOFSTEP] rfl [GOAL] case neg.none.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝ : α ⊢ (Option.bind (none + Option.some val✝) fun a => Option.some (a * c)) = (Option.bind none fun a => Option.some (a * c)) + Option.bind (Option.some val✝) fun a => Option.some (a * c) [PROOFSTEP] first | rfl | exact congr_arg some (add_mul _ _ _) [GOAL] case neg.none.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝ : α ⊢ (Option.bind (none + Option.some val✝) fun a => Option.some (a * c)) = (Option.bind none fun a => Option.some (a * c)) + Option.bind (Option.some val✝) fun a => Option.some (a * c) [PROOFSTEP] rfl [GOAL] case neg.some.none α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝ : α ⊢ (Option.bind (Option.some val✝ + none) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝) fun a => Option.some (a * c)) + Option.bind none fun a => Option.some (a * c) [PROOFSTEP] first | rfl | exact congr_arg some (add_mul _ _ _) [GOAL] case neg.some.none α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝ : α ⊢ (Option.bind (Option.some val✝ + none) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝) fun a => Option.some (a * c)) + Option.bind none fun a => Option.some (a * c) [PROOFSTEP] rfl [GOAL] case neg.some.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝¹ val✝ : α ⊢ (Option.bind (Option.some val✝¹ + Option.some val✝) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝¹) fun a => Option.some (a * c)) + Option.bind (Option.some val✝) fun a => Option.some (a * c) [PROOFSTEP] first | rfl | exact congr_arg some (add_mul _ _ _) [GOAL] case neg.some.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝¹ val✝ : α ⊢ (Option.bind (Option.some val✝¹ + Option.some val✝) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝¹) fun a => Option.some (a * c)) + Option.bind (Option.some val✝) fun a => Option.some (a * c) [PROOFSTEP] rfl [GOAL] case neg.some.some α : Type u_1 inst✝¹ : DecidableEq α inst✝ : CanonicallyOrderedCommSemiring α c : α hc : ¬c = 0 val✝¹ val✝ : α ⊢ (Option.bind (Option.some val✝¹ + Option.some val✝) fun a => Option.some (a * c)) = (Option.bind (Option.some val✝¹) fun a => Option.some (a * c)) + Option.bind (Option.some val✝) fun a => Option.some (a * c) [PROOFSTEP] exact congr_arg some (add_mul _ _ _) [GOAL] α : Type u_1 inst✝² : DecidableEq α inst✝¹ : CanonicallyOrderedCommSemiring α inst✝ : Nontrivial α src✝¹ : AddCommMonoidWithOne (WithTop α) := addCommMonoidWithOne src✝ : CommMonoidWithZero (WithTop α) := commMonoidWithZero a b c : WithTop α ⊢ a * (b + c) = a * b + a * c [PROOFSTEP] rw [mul_comm, distrib', mul_comm b, mul_comm c] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α ⊢ Covariant { x // 0 ≤ x } (WithBot α) (fun x y => ↑x * y) fun x x_1 => x ≤ x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b ⊢ (fun x y => ↑x * y) { val := x, property := x0 } a ≤ (fun x y => ↑x * y) { val := x, property := x0 } b [PROOFSTEP] simp only [Subtype.coe_mk] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b ⊢ x * a ≤ x * b [PROOFSTEP] rcases eq_or_ne x 0 with rfl | x0' [GOAL] case inl α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α a b : WithBot α h : a ≤ b x0 : 0 ≤ 0 ⊢ 0 * a ≤ 0 * b [PROOFSTEP] simp [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b x0' : x ≠ 0 ⊢ x * a ≤ x * b [PROOFSTEP] lift x to α [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b x0' : x ≠ 0 ⊢ x ≠ ⊥ [PROOFSTEP] rintro rfl [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α a b : WithBot α h : a ≤ b x0 : 0 ≤ ⊥ x0' : ⊥ ≠ 0 ⊢ False [PROOFSTEP] exact (WithBot.bot_lt_coe (0 : α)).not_le x0 [GOAL] case inr.intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α a b : WithBot α h : a ≤ b x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 ⊢ ↑x * a ≤ ↑x * b [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case inr.intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α b : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 h : ⊥ ≤ b ⊢ ↑x * ⊥ ≤ ↑x * b [PROOFSTEP] simp_rw [mul_bot x0', bot_le] [GOAL] case inr.intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α b : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : ↑a✝ ≤ b ⊢ ↑x * ↑a✝ ≤ ↑x * b [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case inr.intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : ↑a✝ ≤ ⊥ ⊢ ↑x * ↑a✝ ≤ ↑x * ⊥ [PROOFSTEP] exact absurd h (bot_lt_coe _).not_le [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : ↑a✝¹ ≤ ↑a✝ ⊢ ↑x * ↑a✝¹ ≤ ↑x * ↑a✝ [PROOFSTEP] simp only [← coe_mul, coe_le_coe] at * [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : a✝¹ ≤ a✝ ⊢ x * a✝¹ ≤ x * a✝ [PROOFSTEP] norm_cast at x0 [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMono α x : α x0' : ↑x ≠ 0 a✝¹ a✝ : α h : a✝¹ ≤ a✝ x0 : 0 ≤ x ⊢ x * a✝¹ ≤ x * a✝ [PROOFSTEP] exact mul_le_mul_of_nonneg_left h x0 [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α ⊢ Covariant { x // 0 ≤ x } (WithBot α) (fun x y => y * ↑x) fun x x_1 => x ≤ x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b ⊢ (fun x y => y * ↑x) { val := x, property := x0 } a ≤ (fun x y => y * ↑x) { val := x, property := x0 } b [PROOFSTEP] simp only [Subtype.coe_mk] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b ⊢ a * x ≤ b * x [PROOFSTEP] rcases eq_or_ne x 0 with rfl | x0' [GOAL] case inl α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α a b : WithBot α h : a ≤ b x0 : 0 ≤ 0 ⊢ a * 0 ≤ b * 0 [PROOFSTEP] simp [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b x0' : x ≠ 0 ⊢ a * x ≤ b * x [PROOFSTEP] lift x to α [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a ≤ b x0' : x ≠ 0 ⊢ x ≠ ⊥ [PROOFSTEP] rintro rfl [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α a b : WithBot α h : a ≤ b x0 : 0 ≤ ⊥ x0' : ⊥ ≠ 0 ⊢ False [PROOFSTEP] exact (WithBot.bot_lt_coe (0 : α)).not_le x0 [GOAL] case inr.intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α a b : WithBot α h : a ≤ b x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 ⊢ a * ↑x ≤ b * ↑x [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case inr.intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α b : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 h : ⊥ ≤ b ⊢ ⊥ * ↑x ≤ b * ↑x [PROOFSTEP] simp_rw [bot_mul x0', bot_le] [GOAL] case inr.intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α b : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : ↑a✝ ≤ b ⊢ ↑a✝ * ↑x ≤ b * ↑x [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case inr.intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : ↑a✝ ≤ ⊥ ⊢ ↑a✝ * ↑x ≤ ⊥ * ↑x [PROOFSTEP] exact absurd h (bot_lt_coe _).not_le [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : ↑a✝¹ ≤ ↑a✝ ⊢ ↑a✝¹ * ↑x ≤ ↑a✝ * ↑x [PROOFSTEP] simp only [← coe_mul, coe_le_coe] at * [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : a✝¹ ≤ a✝ ⊢ a✝¹ * x ≤ a✝ * x [PROOFSTEP] norm_cast at x0 [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMono α x : α x0' : ↑x ≠ 0 a✝¹ a✝ : α h : a✝¹ ≤ a✝ x0 : 0 ≤ x ⊢ a✝¹ * x ≤ a✝ * x [PROOFSTEP] exact mul_le_mul_of_nonneg_right h x0 [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α ⊢ Covariant { x // 0 < x } (WithBot α) (fun x y => ↑x * y) fun x x_1 => x < x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α x : WithBot α x0 : 0 < x a b : WithBot α h : a < b ⊢ (fun x y => ↑x * y) { val := x, property := x0 } a < (fun x y => ↑x * y) { val := x, property := x0 } b [PROOFSTEP] simp only [Subtype.coe_mk] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α x : WithBot α x0 : 0 < x a b : WithBot α h : a < b ⊢ x * a < x * b [PROOFSTEP] lift x to α using x0.ne_bot [GOAL] case intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α a b : WithBot α h : a < b x : α x0 : 0 < ↑x ⊢ ↑x * a < ↑x * b [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α a : WithBot α x : α x0 : 0 < ↑x h : a < ⊥ ⊢ ↑x * a < ↑x * ⊥ [PROOFSTEP] exact absurd h not_lt_bot [GOAL] case intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α a : WithBot α x : α x0 : 0 < ↑x a✝ : α h : a < ↑a✝ ⊢ ↑x * a < ↑x * ↑a✝ [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α x : α x0 : 0 < ↑x a✝ : α h : ⊥ < ↑a✝ ⊢ ↑x * ⊥ < ↑x * ↑a✝ [PROOFSTEP] simp_rw [mul_bot x0.ne.symm, ← coe_mul, bot_lt_coe] [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : ↑a✝ < ↑a✝¹ ⊢ ↑x * ↑a✝ < ↑x * ↑a✝¹ [PROOFSTEP] simp only [← coe_mul, coe_lt_coe] at * [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : a✝ < a✝¹ ⊢ x * a✝ < x * a✝¹ [PROOFSTEP] norm_cast at x0 [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulStrictMono α x a✝¹ a✝ : α h : a✝ < a✝¹ x0 : 0 < x ⊢ x * a✝ < x * a✝¹ [PROOFSTEP] exact mul_lt_mul_of_pos_left h x0 [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α ⊢ Covariant { x // 0 < x } (WithBot α) (fun x y => y * ↑x) fun x x_1 => x < x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α x : WithBot α x0 : 0 < x a b : WithBot α h : a < b ⊢ (fun x y => y * ↑x) { val := x, property := x0 } a < (fun x y => y * ↑x) { val := x, property := x0 } b [PROOFSTEP] simp only [Subtype.coe_mk] [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α x : WithBot α x0 : 0 < x a b : WithBot α h : a < b ⊢ a * x < b * x [PROOFSTEP] lift x to α using x0.ne_bot [GOAL] case intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α a b : WithBot α h : a < b x : α x0 : 0 < ↑x ⊢ a * ↑x < b * ↑x [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α a : WithBot α x : α x0 : 0 < ↑x h : a < ⊥ ⊢ a * ↑x < ⊥ * ↑x [PROOFSTEP] exact absurd h not_lt_bot [GOAL] case intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α a : WithBot α x : α x0 : 0 < ↑x a✝ : α h : a < ↑a✝ ⊢ a * ↑x < ↑a✝ * ↑x [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α x : α x0 : 0 < ↑x a✝ : α h : ⊥ < ↑a✝ ⊢ ⊥ * ↑x < ↑a✝ * ↑x [PROOFSTEP] simp_rw [bot_mul x0.ne.symm, ← coe_mul, bot_lt_coe] [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : ↑a✝ < ↑a✝¹ ⊢ ↑a✝ * ↑x < ↑a✝¹ * ↑x [PROOFSTEP] simp only [← coe_mul, coe_lt_coe] at * [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : a✝ < a✝¹ ⊢ a✝ * x < a✝¹ * x [PROOFSTEP] norm_cast at x0 [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosStrictMono α x a✝¹ a✝ : α h : a✝ < a✝¹ x0 : 0 < x ⊢ a✝ * x < a✝¹ * x [PROOFSTEP] exact mul_lt_mul_of_pos_right h x0 [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α ⊢ Contravariant { x // 0 ≤ x } (WithBot α) (fun x y => ↑x * y) fun x x_1 => x < x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : (fun x y => ↑x * y) { val := x, property := x0 } a < (fun x y => ↑x * y) { val := x, property := x0 } b ⊢ a < b [PROOFSTEP] simp only [Subtype.coe_mk] at h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : x * a < x * b ⊢ a < b [PROOFSTEP] rcases eq_or_ne x 0 with rfl | x0' [GOAL] case inl α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α a b : WithBot α x0 : 0 ≤ 0 h : 0 * a < 0 * b ⊢ a < b [PROOFSTEP] simp at h [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : x * a < x * b x0' : x ≠ 0 ⊢ a < b [PROOFSTEP] lift x to α [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : x * a < x * b x0' : x ≠ 0 ⊢ x ≠ ⊥ [PROOFSTEP] rintro rfl [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α a b : WithBot α x0 : 0 ≤ ⊥ h : ⊥ * a < ⊥ * b x0' : ⊥ ≠ 0 ⊢ False [PROOFSTEP] exact (WithBot.bot_lt_coe (0 : α)).not_le x0 [GOAL] case inr.intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α a b : WithBot α x : α x0 : 0 ≤ ↑x h : ↑x * a < ↑x * b x0' : ↑x ≠ 0 ⊢ a < b [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case inr.intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α a : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 h : ↑x * a < ↑x * ⊥ ⊢ a < ⊥ [PROOFSTEP] rw [mul_bot x0'] at h [GOAL] case inr.intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α a : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 h : ↑x * a < ⊥ ⊢ a < ⊥ [PROOFSTEP] exact absurd h bot_le.not_lt [GOAL] case inr.intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α a : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : ↑x * a < ↑x * ↑a✝ ⊢ a < ↑a✝ [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case inr.intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : ↑x * ⊥ < ↑x * ↑a✝ ⊢ ⊥ < ↑a✝ [PROOFSTEP] exact WithBot.bot_lt_coe _ [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : ↑x * ↑a✝ < ↑x * ↑a✝¹ ⊢ ↑a✝ < ↑a✝¹ [PROOFSTEP] simp only [← coe_mul, coe_lt_coe] at * [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : x * a✝ < x * a✝¹ ⊢ a✝ < a✝¹ [PROOFSTEP] norm_cast at x0 [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulReflectLT α x : α x0' : ↑x ≠ 0 a✝¹ a✝ : α h : x * a✝ < x * a✝¹ x0 : 0 ≤ x ⊢ a✝ < a✝¹ [PROOFSTEP] exact lt_of_mul_lt_mul_left h x0 [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α ⊢ Contravariant { x // 0 ≤ x } (WithBot α) (fun x y => y * ↑x) fun x x_1 => x < x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : (fun x y => y * ↑x) { val := x, property := x0 } a < (fun x y => y * ↑x) { val := x, property := x0 } b ⊢ a < b [PROOFSTEP] simp only [Subtype.coe_mk] at h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a * x < b * x ⊢ a < b [PROOFSTEP] rcases eq_or_ne x 0 with rfl | x0' [GOAL] case inl α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α a b : WithBot α x0 : 0 ≤ 0 h : a * 0 < b * 0 ⊢ a < b [PROOFSTEP] simp at h [GOAL] case inr α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a * x < b * x x0' : x ≠ 0 ⊢ a < b [PROOFSTEP] lift x to α [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : WithBot α x0 : 0 ≤ x a b : WithBot α h : a * x < b * x x0' : x ≠ 0 ⊢ x ≠ ⊥ [PROOFSTEP] rintro rfl [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α a b : WithBot α x0 : 0 ≤ ⊥ h : a * ⊥ < b * ⊥ x0' : ⊥ ≠ 0 ⊢ False [PROOFSTEP] exact (WithBot.bot_lt_coe (0 : α)).not_le x0 [GOAL] case inr.intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α a b : WithBot α x : α x0 : 0 ≤ ↑x h : a * ↑x < b * ↑x x0' : ↑x ≠ 0 ⊢ a < b [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case inr.intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α a : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 h : a * ↑x < ⊥ * ↑x ⊢ a < ⊥ [PROOFSTEP] rw [bot_mul x0'] at h [GOAL] case inr.intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α a : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 h : a * ↑x < ⊥ ⊢ a < ⊥ [PROOFSTEP] exact absurd h bot_le.not_lt [GOAL] case inr.intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α a : WithBot α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : a * ↑x < ↑a✝ * ↑x ⊢ a < ↑a✝ [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case inr.intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝ : α h : ⊥ * ↑x < ↑a✝ * ↑x ⊢ ⊥ < ↑a✝ [PROOFSTEP] exact WithBot.bot_lt_coe _ [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : ↑a✝ * ↑x < ↑a✝¹ * ↑x ⊢ ↑a✝ < ↑a✝¹ [PROOFSTEP] simp only [← coe_mul, coe_lt_coe] at * [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : α x0 : 0 ≤ ↑x x0' : ↑x ≠ 0 a✝¹ a✝ : α h : a✝ * x < a✝¹ * x ⊢ a✝ < a✝¹ [PROOFSTEP] norm_cast at x0 [GOAL] case inr.intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosReflectLT α x : α x0' : ↑x ≠ 0 a✝¹ a✝ : α h : a✝ * x < a✝¹ * x x0 : 0 ≤ x ⊢ a✝ < a✝¹ [PROOFSTEP] exact lt_of_mul_lt_mul_right h x0 [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α ⊢ Contravariant { x // 0 < x } (WithBot α) (fun x y => ↑x * y) fun x x_1 => x ≤ x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α x : WithBot α x0 : 0 < x a b : WithBot α h : (fun x y => ↑x * y) { val := x, property := x0 } a ≤ (fun x y => ↑x * y) { val := x, property := x0 } b ⊢ a ≤ b [PROOFSTEP] simp only [Subtype.coe_mk] at h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α x : WithBot α x0 : 0 < x a b : WithBot α h : x * a ≤ x * b ⊢ a ≤ b [PROOFSTEP] lift x to α using x0.ne_bot [GOAL] case intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α a b : WithBot α x : α x0 : 0 < ↑x h : ↑x * a ≤ ↑x * b ⊢ a ≤ b [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α b : WithBot α x : α x0 : 0 < ↑x h : ↑x * ⊥ ≤ ↑x * b ⊢ ⊥ ≤ b [PROOFSTEP] exact bot_le [GOAL] case intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α b : WithBot α x : α x0 : 0 < ↑x a✝ : α h : ↑x * ↑a✝ ≤ ↑x * b ⊢ ↑a✝ ≤ b [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α x : α x0 : 0 < ↑x a✝ : α h : ↑x * ↑a✝ ≤ ↑x * ⊥ ⊢ ↑a✝ ≤ ⊥ [PROOFSTEP] rw [mul_bot x0.ne.symm, ← coe_mul] at h [GOAL] case intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α x : α x0 : 0 < ↑x a✝ : α h : ↑(x * a✝) ≤ ⊥ ⊢ ↑a✝ ≤ ⊥ [PROOFSTEP] exact absurd h (bot_lt_coe _).not_le [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : ↑x * ↑a✝¹ ≤ ↑x * ↑a✝ ⊢ ↑a✝¹ ≤ ↑a✝ [PROOFSTEP] simp only [← coe_mul, coe_le_coe] at * [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : x * a✝¹ ≤ x * a✝ ⊢ a✝¹ ≤ a✝ [PROOFSTEP] norm_cast at x0 [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : PosMulMonoRev α x a✝¹ a✝ : α h : x * a✝¹ ≤ x * a✝ x0 : 0 < x ⊢ a✝¹ ≤ a✝ [PROOFSTEP] exact le_of_mul_le_mul_left h x0 [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α ⊢ Contravariant { x // 0 < x } (WithBot α) (fun x y => y * ↑x) fun x x_1 => x ≤ x_1 [PROOFSTEP] intro ⟨x, x0⟩ a b h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α x : WithBot α x0 : 0 < x a b : WithBot α h : (fun x y => y * ↑x) { val := x, property := x0 } a ≤ (fun x y => y * ↑x) { val := x, property := x0 } b ⊢ a ≤ b [PROOFSTEP] simp only [Subtype.coe_mk] at h [GOAL] α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α x : WithBot α x0 : 0 < x a b : WithBot α h : a * x ≤ b * x ⊢ a ≤ b [PROOFSTEP] lift x to α using x0.ne_bot [GOAL] case intro α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α a b : WithBot α x : α x0 : 0 < ↑x h : a * ↑x ≤ b * ↑x ⊢ a ≤ b [PROOFSTEP] induction a using WithBot.recBotCoe [GOAL] case intro.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α b : WithBot α x : α x0 : 0 < ↑x h : ⊥ * ↑x ≤ b * ↑x ⊢ ⊥ ≤ b [PROOFSTEP] exact bot_le [GOAL] case intro.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α b : WithBot α x : α x0 : 0 < ↑x a✝ : α h : ↑a✝ * ↑x ≤ b * ↑x ⊢ ↑a✝ ≤ b [PROOFSTEP] induction b using WithBot.recBotCoe [GOAL] case intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α x : α x0 : 0 < ↑x a✝ : α h : ↑a✝ * ↑x ≤ ⊥ * ↑x ⊢ ↑a✝ ≤ ⊥ [PROOFSTEP] rw [bot_mul x0.ne.symm, ← coe_mul] at h [GOAL] case intro.coe.bot α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α x : α x0 : 0 < ↑x a✝ : α h : ↑(a✝ * x) ≤ ⊥ ⊢ ↑a✝ ≤ ⊥ [PROOFSTEP] exact absurd h (bot_lt_coe _).not_le [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : ↑a✝¹ * ↑x ≤ ↑a✝ * ↑x ⊢ ↑a✝¹ ≤ ↑a✝ [PROOFSTEP] simp only [← coe_mul, coe_le_coe] at * [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α x : α x0 : 0 < ↑x a✝¹ a✝ : α h : a✝¹ * x ≤ a✝ * x ⊢ a✝¹ ≤ a✝ [PROOFSTEP] norm_cast at x0 [GOAL] case intro.coe.coe α : Type u_1 inst✝³ : DecidableEq α inst✝² : MulZeroClass α inst✝¹ : Preorder α inst✝ : MulPosMonoRev α x a✝¹ a✝ : α h : a✝¹ * x ≤ a✝ * x x0 : 0 < x ⊢ a✝¹ ≤ a✝ [PROOFSTEP] exact le_of_mul_le_mul_right h x0
(************************************** not Finish reading, not Finish exercise **************************************) Require Import Coq.Init.Nat. Require Import Coq.Lists.List. (* ================================================================= *) (** * The apply Tactic *) (* This is proved in chapter Lists. *) Theorem rev_involutive: forall l: list nat, rev (rev l) = l. Proof. Admitted. (** **** Exercise: 2 stars, optional (silly_ex) *) Theorem silly_ex: (forall n, even n = true -> odd (S n) = true) -> even 3 = true -> odd 4 = true. Proof. intros H. apply H. Qed. (** **** Exercise: 3 stars (apply_exercise1) *) Theorem rev_exercise1: forall (l l': list nat), l = rev l' -> l' = rev l. Proof. intros l l' H. rewrite H. symmetry. apply rev_involutive. Qed. (** **** Exercise: 1 star, optional (apply_rewrite) *) (** apply: change goal by forall rule or non-forall rule. rewrite: change goal by non-forall rule. **) (* ================================================================= *) (** * The apply ... with ... Tactic *) Theorem trans_eq : forall (X:Type) (n m o : X), n = m -> m = o -> n = o. Proof. intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2. reflexivity. Qed. Definition minustwo (n: nat): nat := match n with | O => O | S O => O | S (S n') => n' end. (** **** Exercise: 3 stars, optional (apply_with_exercise) *) Example trans_eq_exercise: forall (n m o p: nat), m = (minustwo o) -> (n + p) = m -> (n + p) = (minustwo o). Proof. intros n m o p P Q. rewrite <- P. rewrite -> Q. reflexivity. Qed. (* do not know how to use apply with *) (* ================================================================= *) (** * The inversion Tactic *) (** **** Exercise: 1 star (inversion_ex3) *) Example inversion_ex3: forall (X: Type) (x y z: X) (l j: list X), x :: y :: l = z :: j -> y :: l = x :: j -> x = y. Proof. intros X x y z l j P Q. inversion P. inversion Q. rewrite H0. reflexivity. Qed. (** **** Exercise: 1 star (inversion_ex6) *) Example inversion_ex6: forall (X: Type) (x y z: X) (l j: list X), x :: y :: l = nil -> y :: l = z :: j -> x = z. Proof. intros X x y z l j P Q. inversion P. Qed. (* ================================================================= *) (** * Using Tactics on Hypotheses *) (** **** Exercise: 3 stars, recommended (plus_n_n_injective) *) Theorem plus_n_n_injective: forall n m, n + n = m + m -> n = m. Proof. intros n m P. induction n. - simpl in P. destruct m. + reflexivity. + inversion P. - induction m. + simpl in P. inversion P. + simpl in P. inversion P. rewrite <- plus_n_Sm in H0. rewrite <- plus_n_Sm in H0. inversion H0. rewrite -> H1 in IHn. Abort. (* TODO *) (* ================================================================= *) (** * Varying the Induction Hypothesis *) (* ================================================================= *) (** * Using destruct on Compound Expressions *) (** **** Exercise: 3 stars, optional (combine_split) *) Theorem combine_split: forall X Y (l: list (X * Y)) l1 l2, split l = (l1, l2) -> combine l1 l2 = l. Proof. induction l as [|(x, y) l']. + intros l1 l2 h1. simpl in h1. inversion h1. reflexivity. + simpl. destruct (split l') as [xs ys]. intros l1 l2 h1. inversion h1. simpl. rewrite IHl'. - reflexivity. - reflexivity. Qed. (** **** Exercise: 2 stars (destruct_eqn_practice) *) Theorem bool_fn_applied_thrice: forall (f: bool -> bool)(b: bool), f (f (f b)) = f b. Proof. intros f b. destruct b. - destruct (f true) eqn:H. + rewrite H. rewrite H. reflexivity. + destruct (f false) eqn:H1. * apply H. * apply H1. - destruct (f true) eqn:H. + destruct (f false) eqn:H1. * rewrite H. rewrite H. reflexivity. * rewrite H1. rewrite H1. reflexivity. + destruct (f false) eqn:H1. * rewrite H. rewrite H1. reflexivity. * rewrite H1. rewrite H1. reflexivity. Qed.
(*<*) theory Interval imports "HOL-Library.Extended_Nat" "HOL-Library.Product_Lexorder" begin (*>*) section \<open>Intervals\<close> typedef \<I> = "{(i :: nat, j :: enat). i \<le> j}" by (intro exI[of _ "(0, \<infinity>)"]) auto setup_lifting type_definition_\<I> instantiation \<I> :: equal begin lift_definition equal_\<I> :: "\<I> \<Rightarrow> \<I> \<Rightarrow> bool" is "(=)" . instance by standard (transfer, auto) end instantiation \<I> :: linorder begin lift_definition less_eq_\<I> :: "\<I> \<Rightarrow> \<I> \<Rightarrow> bool" is "(\<le>)" . lift_definition less_\<I> :: "\<I> \<Rightarrow> \<I> \<Rightarrow> bool" is "(<)" . instance by standard (transfer, auto)+ end lift_definition all :: \<I> is "(0, \<infinity>)" by simp lift_definition left :: "\<I> \<Rightarrow> nat" is fst . lift_definition right :: "\<I> \<Rightarrow> enat" is snd . lift_definition point :: "nat \<Rightarrow> \<I>" is "\<lambda>n. (n, enat n)" by simp lift_definition init :: "nat \<Rightarrow> \<I>" is "\<lambda>n. (0, enat n)" by auto abbreviation mem where "mem n I \<equiv> (left I \<le> n \<and> n \<le> right I)" lift_definition subtract :: "nat \<Rightarrow> \<I> \<Rightarrow> \<I>" is "\<lambda>n (i, j). (i - n, j - enat n)" by (auto simp: diff_enat_def split: enat.splits) lift_definition add :: "nat \<Rightarrow> \<I> \<Rightarrow> \<I>" is "\<lambda>n (a, b). (a, b + enat n)" by (auto simp add: add_increasing2) lemma left_right: "left I \<le> right I" by transfer auto lemma point_simps[simp]: "left (point n) = n" "right (point n) = n" by (transfer; auto)+ lemma init_simps[simp]: "left (init n) = 0" "right (init n) = n" by (transfer; auto)+ lemma subtract_simps[simp]: "left (subtract n I) = left I - n" "right (subtract n I) = right I - n" "subtract 0 I = I" "subtract x (point y) = point (y - x)" by (transfer; auto)+ definition shifted :: "\<I> \<Rightarrow> \<I> set" where "shifted I = (\<lambda>n. subtract n I) ` {0 .. (case right I of \<infinity> \<Rightarrow> left I | enat n \<Rightarrow> n)}" lemma subtract_shifted: "subtract n I \<in> shifted I" by (cases "n \<le> (case right I of \<infinity> \<Rightarrow> left I | enat n \<Rightarrow> n)") (auto simp: shifted_def subtract_too_much) lemma finite_shifted: "finite (shifted I)" unfolding shifted_def by auto definition interval :: "nat \<Rightarrow> enat \<Rightarrow> \<I>" where "interval l r = (if l \<le> r then Abs_\<I> (l, r) else undefined)" lemma [code abstract]: "Rep_\<I> (interval l r) = (if l \<le> r then (l, r) else Rep_\<I> undefined)" unfolding interval_def using Abs_\<I>_inverse by simp (*<*) end (*>*)
theory Funpow imports "HOL-Library.FuncSet" "HOL-Library.Permutations" begin section \<open>Auxiliary Lemmas about @{term "(^^)"}\<close> lemma funpow_simp_l: "f ((f ^^ n) x) = (f ^^ Suc n) x" by (metis comp_apply funpow.simps(2)) lemma funpow_add_app: "(f ^^ n) ((f ^^ m) x) = (f ^^ (n + m)) x" by (metis comp_apply funpow_add) lemma funpow_mod_eq: assumes "(f ^^ n) x = x" "0 < n" shows "(f ^^ (m mod n)) x = (f ^^ m) x" proof (induct m rule: less_induct) case (less m) { assume "m < n" then have ?case by simp } moreover { assume "m = n" then have ?case by (simp add: \<open>_ = x\<close>)} moreover { assume "n < m" then have "m - n < m" "0 < m - n" using \<open>0 < n\<close> by arith+ have "(f ^^ (m mod n)) x = (f ^^ ((m - n) mod n)) x" using \<open>0 < m - n\<close> by (simp add: mod_geq) also have "\<dots> = (f ^^ (m - n)) x" using \<open>m - n < m\<close> by (rule less) also have "\<dots> = (f ^^ (m - n)) ((f ^^ n) x)" by (simp add: assms) also have "\<dots> = (f ^^ m) x" using \<open>0 < m - n\<close> by (simp add: funpow_add_app) finally have ?case . } ultimately show ?case by (metis linorder_neqE_nat) qed lemma id_funpow_id: assumes "f x = x" shows "(f ^^ n) x = x" using assms by (induct n) auto lemma inv_id_abs[simp]: "inv (\<lambda>a. a) = id" unfolding id_def[symmetric] by simp lemma inj_funpow: fixes f :: "'a \<Rightarrow> 'a" assumes "inj f" shows "inj (f ^^ n)" proof (induct n) case 0 then show ?case by (auto simp: id_def[symmetric]) next case (Suc n) with assms show ?case unfolding funpow.simps by (rule inj_compose) qed lemma funpow_inj_finite: assumes "inj p" "finite {(p ^^ n) x |n. True}" shows "\<exists>n>0. (p ^^ n) x = x" proof - have "\<not>finite {0::nat..}" by simp moreover have "{(p ^^ n) x |n. True} = (\<lambda>n. (p ^^ n) x) ` {0..}" by auto with assms have "finite \<dots>" by simp ultimately have "\<exists>n\<in>{0..}. \<not> finite {m \<in> {0..}. (p ^^ m) x = (p ^^ n) x}" by (rule pigeonhole_infinite) then obtain n where "\<not>finite {m. (p ^^ m) x = (p ^^ n) x}" by auto then have "\<not>finite ({m. (p ^^ m) x = (p ^^ n) x} - {n})" by auto then have "({m. (p ^^ m) x = (p ^^ n) x} - {n}) \<noteq> {}" by (metis finite.emptyI) then obtain m where m: "(p ^^ m) x = (p ^^ n) x" "m \<noteq> n" by auto { fix m n assume "(p ^^ n) x = (p ^^ m) x" "m < n" have "(p ^^ (n - m)) x = inv (p ^^ m) ((p ^^ m) ((p ^^ (n - m)) x))" using \<open>inj p\<close> by (simp add: inv_f_f inj_funpow) also have "((p ^^ m) ((p ^^ (n - m)) x)) = (p ^^ n) x" using \<open>m < n\<close> by (simp add: funpow_add_app) also have "inv (p ^^ m) \<dots> = x" using \<open>inj p\<close> by (simp add: \<open>(p ^^ n) x = _\<close> inj_funpow) finally have "(p ^^ (n - m)) x = x" "0 < n - m" using \<open>m < n\<close> by auto } note general = this show ?thesis proof (cases m n rule: linorder_cases) case less then show ?thesis using general m by metis next case equal then show ?thesis using m by metis next case greater then show ?thesis using general m by metis qed qed lemma permutes_in_funpow_image: assumes "f permutes S" "x \<in> S" shows "(f ^^ n) x \<in> S" using assms by (induct n) (auto simp: permutes_in_image) (* XXX move*) lemma permutation_self: assumes "permutation p" shows "\<exists>n>0. (p ^^ n) x = x" proof cases assume "p x = x" then show ?thesis by auto next assume "p x \<noteq> x" from assms have "inj p" by (intro permutation_bijective bij_is_inj) { fix n from \<open>p x \<noteq> x\<close> have "(p ^^ Suc n) x \<noteq> (p ^^ n) x" proof (induct n arbitrary: x) case 0 then show ?case by simp next case (Suc n) have "p (p x) \<noteq> p x" proof (rule notI) assume "p (p x) = p x" then show False using \<open>p x \<noteq> x\<close> \<open>inj p\<close> by (simp add: inj_eq) qed have "(p ^^ Suc (Suc n)) x = (p ^^ Suc n) (p x)" by (metis funpow_simp_l funpow_swap1) also have "\<dots> \<noteq> (p ^^ n) (p x)" by (rule Suc) fact also have "(p ^^ n) (p x) = (p ^^ Suc n) x" by (metis funpow_simp_l funpow_swap1) finally show ?case by simp qed } then have "{(p ^^ n) x | n. True} \<subseteq> {x. p x \<noteq> x}" by auto then have "finite {(p ^^ n) x | n. True}" using permutation_finite_support[OF assms] by (rule finite_subset) with \<open>inj p\<close> show ?thesis by (rule funpow_inj_finite) qed (* XXX move *) lemma (in -) funpow_invs: assumes "m \<le> n" and inv: "\<And>x. f (g x) = x" shows "(f ^^ m) ((g ^^ n) x) = (g ^^ (n - m)) x" using \<open>m \<le> n\<close> proof (induction m) case (Suc m) moreover then have "n - m = Suc (n - Suc m)" by auto ultimately show ?case by (auto simp: inv) qed simp section \<open>Function-power distance between values\<close> (* xxx move *) definition funpow_dist :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> nat" where "funpow_dist f x y \<equiv> LEAST n. (f ^^ n) x = y" abbreviation funpow_dist1 :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> nat" where "funpow_dist1 f x y \<equiv> Suc (funpow_dist f (f x) y)" lemma funpow_dist_0: assumes "x = y" shows "funpow_dist f x y = 0" using assms unfolding funpow_dist_def by (intro Least_eq_0) simp lemma funpow_dist_least: assumes "n < funpow_dist f x y" shows "(f ^^ n) x \<noteq> y" proof (rule notI) assume "(f ^^ n) x = y" then have "funpow_dist f x y \<le> n" unfolding funpow_dist_def by (rule Least_le) with assms show False by linarith qed lemma funpow_dist1_least: assumes "0 < n" "n < funpow_dist1 f x y" shows "(f ^^ n) x \<noteq> y" proof (rule notI) assume "(f ^^ n) x = y" then have "(f ^^ (n - 1)) (f x) = y" using \<open>0 < n\<close> by (cases n) (simp_all add: funpow_swap1) then have "funpow_dist f (f x) y \<le> n - 1" unfolding funpow_dist_def by (rule Least_le) with assms show False by simp qed section \<open>Cyclic Permutations\<close> inductive_set orbit :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a set" for f x where base: "f x \<in> orbit f x" | step: "y \<in> orbit f x \<Longrightarrow> f y \<in> orbit f x" definition cyclic_on :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a set \<Rightarrow> bool" where "cyclic_on f S \<longleftrightarrow> (\<exists>s\<in>S. S = orbit f s)" lemma orbit_altdef: "orbit f x = {(f ^^ n) x | n. 0 < n}" (is "?L = ?R") proof (intro set_eqI iffI) fix y assume "y \<in> ?L" then show "y \<in> ?R" by (induct rule: orbit.induct) (auto simp: exI[where x=1] exI[where x="Suc n" for n]) next fix y assume "y \<in> ?R" then obtain n where "y = (f ^^ n) x" "0 < n" by blast then show "y \<in> ?L" proof (induction n arbitrary: y) case (Suc n) then show ?case by (cases "n = 0") (auto intro: orbit.intros) qed simp qed lemma orbit_trans: assumes "s \<in> orbit f t" "t \<in> orbit f u" shows "s \<in> orbit f u" using assms by induct (auto intro: orbit.intros) lemma orbit_subset: assumes "s \<in> orbit f (f t)" shows "s \<in> orbit f t" using assms by (induct) (auto intro: orbit.intros) lemma orbit_sim_step: assumes "s \<in> orbit f t" shows "f s \<in> orbit f (f t)" using assms by induct (auto intro: orbit.intros) lemma orbit_step: assumes "y \<in> orbit f x" "f x \<noteq> y" shows "y \<in> orbit f (f x)" using assms proof induction case (step y) then show ?case by (cases "x = y") (auto intro: orbit.intros) qed simp lemma self_in_orbit_trans: assumes "s \<in> orbit f s" "t \<in> orbit f s" shows "t \<in> orbit f t" using assms(2,1) by induct (auto intro: orbit_sim_step) lemma orbit_swap: assumes "s \<in> orbit f s" "t \<in> orbit f s" shows "s \<in> orbit f t" using assms(2,1) proof induction case base then show ?case by (cases "f s = s") (auto intro: orbit_step) next case (step x) then show ?case by (cases "f x = s") (auto intro: orbit_step) qed lemma permutation_self_in_orbit: assumes "permutation f" shows "s \<in> orbit f s" unfolding orbit_altdef using permutation_self[OF assms, of s] by simp metis lemma orbit_altdef_self_in: assumes "s \<in> orbit f s" shows "orbit f s = {(f ^^ n) s | n. True}" proof (intro set_eqI iffI) fix x assume "x \<in> {(f ^^ n) s | n. True}" then obtain n where "x = (f ^^ n) s" by auto then show "x \<in> orbit f s" using assms by (cases "n = 0") (auto simp: orbit_altdef) qed (auto simp: orbit_altdef) lemma orbit_altdef_permutation: assumes "permutation f" shows "orbit f s = {(f ^^ n) s | n. True}" using assms by (intro orbit_altdef_self_in permutation_self_in_orbit) lemma orbit_altdef_bounded: assumes "(f ^^ n) s = s" "0 < n" shows "orbit f s = {(f ^^ m) s| m. m < n}" proof - from assms have "s \<in> orbit f s" unfolding orbit_altdef by auto metis then have "orbit f s = {(f ^^ m) s|m. True}" by (rule orbit_altdef_self_in) also have "\<dots> = {(f ^^ m) s| m. m < n}" using assms by (auto simp: funpow_mod_eq intro: exI[where x="m mod n" for m]) finally show ?thesis . qed lemma funpow_in_orbit: assumes "s \<in> orbit f t" shows "(f ^^ n) s \<in> orbit f t" using assms by (induct n) (auto intro: orbit.intros) lemma finite_orbit: assumes "s \<in> orbit f s" shows "finite (orbit f s)" proof - from assms obtain n where n: "0 < n" "(f ^^n) s = s" by (auto simp: orbit_altdef) then show ?thesis by (auto simp: orbit_altdef_bounded) qed lemma self_in_orbit_step: assumes "s \<in> orbit f s" shows "orbit f (f s) = orbit f s" proof (intro set_eqI iffI) fix t assume "t \<in> orbit f s" then show "t \<in> orbit f (f s)" using assms by (auto intro: orbit_step orbit_sim_step) qed (auto intro: orbit_subset) lemma permutation_orbit_step: assumes "permutation f" shows "orbit f (f s) = orbit f s" using assms by (intro self_in_orbit_step permutation_self_in_orbit) lemma orbit_nonempty: "orbit f s \<noteq> {}" using orbit.base by fastforce lemma orbit_inv_eq: assumes "permutation f" shows "orbit (inv f) x = orbit f x" (is "?L = ?R") proof - { fix g y assume A: "permutation g" "y \<in> orbit (inv g) x" have "y \<in> orbit g x" proof - have inv_g: "\<And>y. x = g y \<Longrightarrow> inv g x = y" "\<And>y. inv g (g y) = y" by (metis A(1) bij_inv_eq_iff permutation_bijective)+ { fix y assume "y \<in> orbit g x" then have "inv g y \<in> orbit g x" by (cases) (simp_all add: inv_g A(1) permutation_self_in_orbit) } note inv_g_in_orb = this from A(2) show ?thesis by induct (simp_all add: inv_g_in_orb A permutation_self_in_orbit) qed } note orb_inv_ss = this have "inv (inv f) = f" by (simp add: assms inv_inv_eq permutation_bijective) then show ?thesis using orb_inv_ss[OF assms] orb_inv_ss[OF permutation_inverse[OF assms]] by auto qed lemma cyclic_on_alldef: "cyclic_on f S \<longleftrightarrow> S \<noteq> {} \<and> (\<forall>s\<in>S. S = orbit f s)" unfolding cyclic_on_def by (auto intro: orbit.step orbit_swap orbit_trans) lemma cyclic_on_funpow_in: assumes "cyclic_on f S" "s \<in> S" shows "(f^^n) s \<in> S" using assms unfolding cyclic_on_def by (auto intro: funpow_in_orbit) lemma finite_cyclic_on: assumes "cyclic_on f S" shows "finite S" using assms by (auto simp: cyclic_on_def finite_orbit) lemma cyclic_on_singleI: assumes "s \<in> S" "S = orbit f s" shows "cyclic_on f S" using assms unfolding cyclic_on_def by blast lemma inj_on_funpow_least: assumes "(f ^^ n) s = s" "\<And>m. \<lbrakk>m < n; 0 < m\<rbrakk> \<Longrightarrow> (f ^^ m) s \<noteq> s" shows "inj_on (\<lambda>k. (f^^k) s) {0..<n}" proof - { fix k l assume A: "k < n" "l < n" "k \<noteq> l" "(f ^^ k) s = (f ^^ l) s" define k' l' where "k' = min k l" and "l' = max k l" with A have A': "k' < l'" "(f ^^ k') s = (f ^^ l') s" "l' < n" by (auto simp: min_def max_def) have "s = (f ^^ ((n - l') + l')) s" using assms \<open>l' < n\<close> by simp also have "\<dots> = (f ^^ (n - l')) ((f ^^ l') s)" by (simp add: funpow_add) also have "(f ^^ l') s = (f ^^ k') s" by (simp add: A') also have "(f ^^ (n - l')) \<dots> = (f ^^ (n - l' + k')) s" by (simp add: funpow_add) finally have "(f ^^ (n - l' + k')) s = s" by simp moreover have "n - l' + k' < n" "0 < n - l' + k'"using A' by linarith+ ultimately have False using assms(2) by auto } then show ?thesis by (intro inj_onI) auto qed lemma cyclic_on_inI: assumes "cyclic_on f S" "s \<in> S" shows "f s \<in> S" using assms by (auto simp: cyclic_on_def intro: orbit.intros) lemma bij_betw_funpow: assumes "bij_betw f S S" shows "bij_betw (f ^^ n) S S" proof (induct n) case 0 then show ?case by (auto simp: id_def[symmetric]) next case (Suc n) then show ?case unfolding funpow.simps using assms by (rule bij_betw_trans) qed (*XXX rename move*) lemma orbit_FOO: assumes self:"a \<in> orbit g a" and eq: "\<And>x. x \<in> orbit g a \<Longrightarrow> g' (f x) = f (g x)" shows "f ` orbit g a = orbit g' (f a)" (is "?L = ?R") proof (intro set_eqI iffI) fix x assume "x \<in> ?L" then obtain x0 where "x0 \<in> orbit g a" "x = f x0" by auto then show "x \<in> ?R" proof (induct arbitrary: x) case base then show ?case by (auto simp: self orbit.base eq[symmetric]) next case step then show ?case by cases (auto simp: eq[symmetric] orbit.intros) qed next fix x assume "x \<in> ?R" then show "x \<in> ?L" proof (induct arbitrary: ) case base then show ?case by (auto simp: self orbit.base eq) next case step then show ?case by cases (auto simp: eq orbit.intros) qed qed lemma cyclic_on_FOO: assumes "cyclic_on f S" assumes "\<And>x. x \<in> S \<Longrightarrow> g (h x) = h (f x)" shows "cyclic_on g (h ` S)" using assms by (auto simp: cyclic_on_def) (meson orbit_FOO) lemma cyclic_on_f_in: assumes "f permutes S" "cyclic_on f A" "f x \<in> A" shows "x \<in> A" proof - from assms have fx_in_orb: "f x \<in> orbit f (f x)" by (auto simp: cyclic_on_alldef) from assms have "A = orbit f (f x)" by (auto simp: cyclic_on_alldef) moreover then have "\<dots> = orbit f x" using \<open>f x \<in> A\<close> by (auto intro: orbit_step orbit_subset) ultimately show ?thesis by (metis (no_types) orbit.simps permutes_inverses(2)[OF assms(1)]) qed lemma permutes_not_in: assumes "f permutes S" "x \<notin> S" shows "f x = x" using assms by (auto simp: permutes_def) lemma orbit_cong0: assumes "x \<in> A" "f \<in> A \<rightarrow> A" "\<And>y. y \<in> A \<Longrightarrow> f y = g y" shows "orbit f x = orbit g x" proof - { fix n have "(f ^^ n) x = (g ^^ n) x \<and> (f ^^ n) x \<in> A" by (induct n rule: nat.induct) (insert assms, auto) } then show ?thesis by (auto simp: orbit_altdef) qed lemma orbit_cong: assumes self_in: "t \<in> orbit f t" and eq: "\<And>s. s \<in> orbit f t \<Longrightarrow> g s = f s" shows "orbit g t = orbit f t" using assms(1) _ assms(2) by (rule orbit_cong0) (auto simp: orbit.step eq) lemma cyclic_cong: assumes "\<And>s. s \<in> S \<Longrightarrow> f s = g s" shows "cyclic_on f S = cyclic_on g S" proof - have "(\<exists>s\<in>S. orbit f s = orbit g s) \<Longrightarrow> cyclic_on f S = cyclic_on g S" by (metis cyclic_on_alldef cyclic_on_def) then show ?thesis by (metis assms orbit_cong cyclic_on_def) qed lemma permutes_comp_preserves_cyclic1: assumes "g permutes B" "cyclic_on f C" assumes "A \<inter> B = {}" "C \<subseteq> A" shows "cyclic_on (f o g) C" proof - have *: "\<And>c. c \<in> C \<Longrightarrow> f (g c) = f c" using assms by (subst permutes_not_in[where f=g]) auto with assms(2) show ?thesis by (simp cong: cyclic_cong) qed lemma permutes_comp_preserves_cyclic2: assumes "f permutes A" "cyclic_on g C" assumes "A \<inter> B = {}" "C \<subseteq> B" shows "cyclic_on (f o g) C" proof - obtain c where c: "c \<in> C" "C = orbit g c" "c \<in> orbit g c" using \<open>cyclic_on g C\<close> by (auto simp: cyclic_on_def) then have "\<And>c. c \<in> C \<Longrightarrow> f (g c) = g c" using assms c by (subst permutes_not_in[where f=f]) (auto intro: orbit.intros) with assms(2) show ?thesis by (simp cong: cyclic_cong) qed (*XXX merge with previous section?*) subsection \<open>Orbits\<close> lemma permutes_orbit_subset: assumes "f permutes S" "x \<in> S" shows "orbit f x \<subseteq> S" proof fix y assume "y \<in> orbit f x" then show "y \<in> S" by induct (auto simp: permutes_in_image assms) qed lemma cyclic_on_orbit': assumes "permutation f" shows "cyclic_on f (orbit f x)" unfolding cyclic_on_alldef using orbit_nonempty[of f x] by (auto intro: assms orbit_swap orbit_trans permutation_self_in_orbit) (* XXX remove? *) lemma cyclic_on_orbit: assumes "f permutes S" "finite S" shows "cyclic_on f (orbit f x)" using assms by (intro cyclic_on_orbit') (auto simp: permutation_permutes) lemma orbit_cyclic_eq3: assumes "cyclic_on f S" "y \<in> S" shows "orbit f y = S" using assms unfolding cyclic_on_alldef by simp (*XXX move*) lemma orbit_eq_singleton_iff: "orbit f x = {x} \<longleftrightarrow> f x = x" (is "?L \<longleftrightarrow> ?R") proof assume A: ?R { fix y assume "y \<in> orbit f x" then have "y = x" by induct (auto simp: A) } then show ?L by (metis orbit_nonempty singletonI subsetI subset_singletonD) next assume A: ?L then have "\<And>y. y \<in> orbit f x \<Longrightarrow> f x = y" by - (erule orbit.cases, simp_all) then show ?R using A by blast qed (* XXX move *) lemma eq_on_cyclic_on_iff1: assumes "cyclic_on f S" "x \<in> S" obtains "f x \<in> S" "f x = x \<longleftrightarrow> card S = 1" proof from assms show "f x \<in> S" by (auto simp: cyclic_on_def intro: orbit.intros) from assms have "S = orbit f x" by (auto simp: cyclic_on_alldef) then have "f x = x \<longleftrightarrow> S = {x}" by (metis orbit_eq_singleton_iff) then show "f x = x \<longleftrightarrow> card S = 1" using \<open>x \<in> S\<close> by (auto simp: card_Suc_eq) qed subsection \<open>Decomposition of Arbitrary Permutations\<close> definition perm_restrict :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a set \<Rightarrow> ('a \<Rightarrow> 'a)" where "perm_restrict f S x \<equiv> if x \<in> S then f x else x" lemma perm_restrict_comp: assumes "A \<inter> B = {}" "cyclic_on f B" shows "perm_restrict f A o perm_restrict f B = perm_restrict f (A \<union> B)" proof - have "\<And>x. x \<in> B \<Longrightarrow> f x \<in> B" using \<open>cyclic_on f B\<close> by (rule cyclic_on_inI) with assms show ?thesis by (auto simp: perm_restrict_def fun_eq_iff) qed lemma perm_restrict_simps: "x \<in> S \<Longrightarrow> perm_restrict f S x = f x" "x \<notin> S \<Longrightarrow> perm_restrict f S x = x" by (auto simp: perm_restrict_def) lemma perm_restrict_perm_restrict: "perm_restrict (perm_restrict f A) B = perm_restrict f (A \<inter> B)" by (auto simp: perm_restrict_def) lemma perm_restrict_union: assumes "perm_restrict f A permutes A" "perm_restrict f B permutes B" "A \<inter> B = {}" shows "perm_restrict f A o perm_restrict f B = perm_restrict f (A \<union> B)" using assms by (auto simp: fun_eq_iff perm_restrict_def permutes_def) (metis Diff_iff Diff_triv) lemma perm_restrict_id[simp]: assumes "f permutes S" shows "perm_restrict f S = f" using assms by (auto simp: permutes_def perm_restrict_def) lemma cyclic_on_perm_restrict: "cyclic_on (perm_restrict f S) S \<longleftrightarrow> cyclic_on f S" by (simp add: perm_restrict_def cong: cyclic_cong) lemma perm_restrict_diff_cyclic: assumes "f permutes S" "cyclic_on f A" shows "perm_restrict f (S - A) permutes (S - A)" proof - { fix y have "\<exists>x. perm_restrict f (S - A) x = y" proof cases assume A: "y \<in> S - A" with \<open>f permutes S\<close> obtain x where "f x = y" "x \<in> S" unfolding permutes_def by auto metis moreover with A have "x \<notin> A" by (metis Diff_iff assms(2) cyclic_on_inI) ultimately have "perm_restrict f (S - A) x = y" by (simp add: perm_restrict_simps) then show ?thesis .. next assume "y \<notin> S - A" then have "perm_restrict f (S - A) y = y" by (simp add: perm_restrict_simps) then show ?thesis .. qed } note X = this { fix x y assume "perm_restrict f (S - A) x = perm_restrict f (S - A) y" with assms have "x = y" by (auto simp: perm_restrict_def permutes_def split: if_splits intro: cyclic_on_f_in) } note Y = this show ?thesis by (auto simp: permutes_def perm_restrict_simps X intro: Y) qed lemma orbit_eqI: "y = f x \<Longrightarrow> y \<in> orbit f x" "z = f y \<Longrightarrow>y \<in> orbit f x \<Longrightarrow>z \<in> orbit f x" by (metis orbit.base) (metis orbit.step) lemma permutes_decompose: assumes "f permutes S" "finite S" shows "\<exists>C. (\<forall>c \<in> C. cyclic_on f c) \<and> \<Union>C = S \<and> (\<forall>c1 \<in> C. \<forall>c2 \<in> C. c1 \<noteq> c2 \<longrightarrow> c1 \<inter> c2 = {})" using assms(2,1) proof (induction arbitrary: f rule: finite_psubset_induct) case (psubset S) show ?case proof (cases "S = {}") case True then show ?thesis by (intro exI[where x="{}"]) auto next case False then obtain s where "s \<in> S" by auto with \<open>f permutes S\<close> have "orbit f s \<subseteq> S" by (rule permutes_orbit_subset) have cyclic_orbit: "cyclic_on f (orbit f s)" using \<open>f permutes S\<close> \<open>finite S\<close> by (rule cyclic_on_orbit) let ?f' = "perm_restrict f (S - orbit f s)" have "f s \<in> S" using \<open>f permutes S\<close> \<open>s \<in> S\<close> by (auto simp: permutes_in_image) then have "S - orbit f s \<subset> S" using orbit.base[of f s] \<open>s \<in> S\<close> by blast moreover have "?f' permutes (S - orbit f s)" using \<open>f permutes S\<close> cyclic_orbit by (rule perm_restrict_diff_cyclic) ultimately obtain C where C: "\<And>c. c \<in> C \<Longrightarrow> cyclic_on ?f' c" "\<Union>C = S - orbit f s" "\<forall>c1 \<in> C. \<forall>c2 \<in> C. c1 \<noteq> c2 \<longrightarrow> c1 \<inter> c2 = {}" using psubset.IH by metis { fix c assume "c \<in> C" then have *: "\<And>x. x \<in> c \<Longrightarrow> perm_restrict f (S - orbit f s) x = f x" using C(2) \<open>f permutes S\<close> by (auto simp add: perm_restrict_def) then have "cyclic_on f c" using C(1)[OF \<open>c \<in> C\<close>] by (simp cong: cyclic_cong add: *) } note in_C_cyclic = this have Un_ins: "\<Union>(insert (orbit f s) C) = S" using \<open>\<Union>C = _\<close> \<open>orbit f s \<subseteq> S\<close> by blast have Disj_ins: "(\<forall>c1 \<in> insert (orbit f s) C. \<forall>c2 \<in> insert (orbit f s) C. c1 \<noteq> c2 \<longrightarrow> c1 \<inter> c2 = {})" using C by auto show ?thesis by (intro conjI Un_ins Disj_ins exI[where x="insert (orbit f s) C"]) (auto simp: cyclic_orbit in_C_cyclic) qed qed subsection \<open>Funpow + Orbit\<close> lemma funpow_dist_prop: "y \<in> orbit f x \<Longrightarrow> (f ^^ funpow_dist f x y) x = y" unfolding funpow_dist_def by (rule LeastI_ex) (auto simp: orbit_altdef) lemma funpow_dist_0_eq: assumes "y \<in> orbit f x" shows "funpow_dist f x y = 0 \<longleftrightarrow> x = y" using assms by (auto simp: funpow_dist_0 dest: funpow_dist_prop) lemma funpow_dist_step: assumes "x \<noteq> y" "y \<in> orbit f x" shows "funpow_dist f x y = Suc (funpow_dist f (f x) y)" proof - from \<open>y \<in> _\<close> obtain n where "(f ^^ n) x = y" by (auto simp: orbit_altdef) with \<open>x \<noteq> y\<close> obtain n' where [simp]: "n = Suc n'" by (cases n) auto show ?thesis unfolding funpow_dist_def proof (rule Least_Suc2) show "(f ^^ n) x = y" by fact then show "(f ^^ n') (f x) = y" by (simp add: funpow_swap1) show "(f ^^ 0) x \<noteq> y" using \<open>x \<noteq> y\<close> by simp show "\<forall>k. ((f ^^ Suc k) x = y) = ((f ^^ k) (f x) = y)" by (simp add: funpow_swap1) qed qed lemma funpow_dist1_prop: assumes "y \<in> orbit f x" shows "(f ^^ funpow_dist1 f x y) x = y" by (metis assms funpow.simps(1) funpow_dist_0 funpow_dist_prop funpow_simp_l funpow_swap1 id_apply orbit_step) (*XXX simplify? *) lemma funpow_neq_less_funpow_dist: assumes "y \<in> orbit f x" "m \<le> funpow_dist f x y" "n \<le> funpow_dist f x y" "m \<noteq> n" shows "(f ^^ m) x \<noteq> (f ^^ n) x" proof (rule notI) assume A: "(f ^^ m) x = (f ^^ n) x" define m' n' where "m' = min m n" and "n' = max m n" with A assms have A': "m' < n'" "(f ^^ m') x = (f ^^ n') x" "n' \<le> funpow_dist f x y" by (auto simp: min_def max_def) have "y = (f ^^ funpow_dist f x y) x" using \<open>y \<in> _\<close> by (simp only: funpow_dist_prop) also have "\<dots> = (f ^^ ((funpow_dist f x y - n') + n')) x" using \<open>n' \<le> _\<close> by simp also have "\<dots> = (f ^^ ((funpow_dist f x y - n') + m')) x" by (simp add: funpow_add \<open>(f ^^ m') x = _\<close>) also have "(f ^^ ((funpow_dist f x y - n') + m')) x \<noteq> y" using A' by (intro funpow_dist_least) linarith finally show "False" by simp qed (* XXX reduce to funpow_neq_less_funpow_dist? *) lemma funpow_neq_less_funpow_dist1: assumes "y \<in> orbit f x" "m < funpow_dist1 f x y" "n < funpow_dist1 f x y" "m \<noteq> n" shows "(f ^^ m) x \<noteq> (f ^^ n) x" proof (rule notI) assume A: "(f ^^ m) x = (f ^^ n) x" define m' n' where "m' = min m n" and "n' = max m n" with A assms have A': "m' < n'" "(f ^^ m') x = (f ^^ n') x" "n' < funpow_dist1 f x y" by (auto simp: min_def max_def) have "y = (f ^^ funpow_dist1 f x y) x" using \<open>y \<in> _\<close> by (simp only: funpow_dist1_prop) also have "\<dots> = (f ^^ ((funpow_dist1 f x y - n') + n')) x" using \<open>n' < _\<close> by simp also have "\<dots> = (f ^^ ((funpow_dist1 f x y - n') + m')) x" by (simp add: funpow_add \<open>(f ^^ m') x = _\<close>) also have "(f ^^ ((funpow_dist1 f x y - n') + m')) x \<noteq> y" using A' by (intro funpow_dist1_least) linarith+ finally show "False" by simp qed lemma inj_on_funpow_dist: assumes "y \<in> orbit f x" shows "inj_on (\<lambda>n. (f ^^ n) x) {0..funpow_dist f x y}" using funpow_neq_less_funpow_dist[OF assms] by (intro inj_onI) auto lemma orbit_conv_funpow_dist1: assumes "x \<in> orbit f x" shows "orbit f x = (\<lambda>n. (f ^^ n) x) ` {0..<funpow_dist1 f x x}" (is "?L = ?R") using funpow_dist1_prop[OF assms] by (auto simp: orbit_altdef_bounded[where n="funpow_dist1 f x x"]) lemma funpow_dist1_prop1: assumes "(f ^^ n) x = y" "0 < n" shows "(f ^^ funpow_dist1 f x y) x = y" proof - from assms have "y \<in> orbit f x" by (auto simp: orbit_altdef) then show ?thesis by (rule funpow_dist1_prop) qed lemma funpow_dist1_dist: assumes "funpow_dist1 f x y < funpow_dist1 f x z" assumes "{y,z} \<subseteq> orbit f x" shows "funpow_dist1 f x z = funpow_dist1 f x y + funpow_dist1 f y z" (is "?L = ?R") proof - have x_z: "(f ^^ funpow_dist1 f x z) x = z" using assms by (blast intro: funpow_dist1_prop) have x_y: "(f ^^ funpow_dist1 f x y) x = y" using assms by (blast intro: funpow_dist1_prop) have "(f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) y = (f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) ((f ^^ funpow_dist1 f x y) x)" using x_y by simp also have "\<dots> = z" using assms x_z by (simp del: funpow.simps add: funpow_add_app) finally have y_z_diff: "(f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) y = z" . then have "(f ^^ funpow_dist1 f y z) y = z" using assms by (intro funpow_dist1_prop1) auto then have "(f ^^ funpow_dist1 f y z) ((f ^^ funpow_dist1 f x y) x) = z" using x_y by simp then have "(f ^^ (funpow_dist1 f y z + funpow_dist1 f x y)) x = z" by (simp del: funpow.simps add: funpow_add_app) show ?thesis proof (rule antisym) from y_z_diff have "(f ^^ funpow_dist1 f y z) y = z" using assms by (intro funpow_dist1_prop1) auto then have "(f ^^ funpow_dist1 f y z) ((f ^^ funpow_dist1 f x y) x) = z" using x_y by simp then have "(f ^^ (funpow_dist1 f y z + funpow_dist1 f x y)) x = z" by (simp del: funpow.simps add: funpow_add_app) then have "funpow_dist1 f x z \<le> funpow_dist1 f y z + funpow_dist1 f x y" using funpow_dist1_least not_less by fastforce then show "?L \<le> ?R" by presburger next have "funpow_dist1 f y z \<le> funpow_dist1 f x z - funpow_dist1 f x y" using y_z_diff assms(1) by (metis not_less zero_less_diff funpow_dist1_least) then show "?R \<le> ?L" by linarith qed qed lemma funpow_dist1_le_self: assumes "(f ^^ m) x = x" "0 < m" "y \<in> orbit f x" shows "funpow_dist1 f x y \<le> m" proof (cases "x = y") case True with assms show ?thesis by (auto dest!: funpow_dist1_least) next case False have "(f ^^ funpow_dist1 f x y) x = (f ^^ (funpow_dist1 f x y mod m)) x" using assms by (simp add: funpow_mod_eq) with False \<open>y \<in> orbit f x\<close> have "funpow_dist1 f x y \<le> funpow_dist1 f x y mod m" by auto (metis funpow_dist_least funpow_dist_prop funpow_dist_step funpow_simp_l not_less) with \<open>m > 0\<close> show ?thesis by (auto intro: order_trans) qed subsection \<open>Permutation Domains\<close> definition has_dom :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a set \<Rightarrow> bool" where "has_dom f S \<equiv> \<forall>s. s \<notin> S \<longrightarrow> f s = s" lemma permutes_conv_has_dom: "f permutes S \<longleftrightarrow> bij f \<and> has_dom f S" by (auto simp: permutes_def has_dom_def bij_iff) section \<open>Segments\<close> inductive_set segment :: "('a \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> 'a set" for f a b where base: "f a \<noteq> b \<Longrightarrow> f a \<in> segment f a b" | step: "x \<in> segment f a b \<Longrightarrow> f x \<noteq> b \<Longrightarrow> f x \<in> segment f a b" lemma segment_step_2D: assumes "x \<in> segment f a (f b)" shows "x \<in> segment f a b \<or> x = b" using assms by induct (auto intro: segment.intros) lemma not_in_segment2D: assumes "x \<in> segment f a b" shows "x \<noteq> b" using assms by induct auto lemma segment_altdef: assumes "b \<in> orbit f a" shows "segment f a b = (\<lambda>n. (f ^^ n) a) ` {1..<funpow_dist1 f a b}" (is "?L = ?R") proof (intro set_eqI iffI) fix x assume "x \<in> ?L" have "f a \<noteq>b \<Longrightarrow> b \<in> orbit f (f a)" using assms by (simp add: orbit_step) then have *: "f a \<noteq> b \<Longrightarrow> 0 < funpow_dist f (f a) b" using assms using gr0I funpow_dist_0_eq[OF \<open>_ \<Longrightarrow> b \<in> orbit f (f a)\<close>] by (simp add: orbit.intros) from \<open>x \<in> ?L\<close> show "x \<in> ?R" proof induct case base then show ?case by (intro image_eqI[where x=1]) (auto simp: *) next case step then show ?case using assms funpow_dist1_prop less_antisym by (fastforce intro!: image_eqI[where x="Suc n" for n]) qed next fix x assume "x \<in> ?R" then obtain n where "(f ^^ n ) a = x" "0 < n" "n < funpow_dist1 f a b" by auto then show "x \<in> ?L" proof (induct n arbitrary: x) case 0 then show ?case by simp next case (Suc n) have "(f ^^ Suc n) a \<noteq> b" using Suc by (meson funpow_dist1_least) with Suc show ?case by (cases "n = 0") (auto intro: segment.intros) qed qed (*XXX move up*) lemma segmentD_orbit: assumes "x \<in> segment f y z" shows "x \<in> orbit f y" using assms by induct (auto intro: orbit.intros) lemma segment1_empty: "segment f x (f x) = {}" by (auto simp: segment_altdef orbit.base funpow_dist_0) lemma segment_subset: assumes "y \<in> segment f x z" assumes "w \<in> segment f x y" shows "w \<in> segment f x z" using assms by (induct arbitrary: w) (auto simp: segment1_empty intro: segment.intros dest: segment_step_2D elim: segment.cases) (* XXX move up*) lemma not_in_segment1: assumes "y \<in> orbit f x" shows "x \<notin> segment f x y" proof assume "x \<in> segment f x y" then obtain n where n: "0 < n" "n < funpow_dist1 f x y" "(f ^^ n) x = x" using assms by (auto simp: segment_altdef Suc_le_eq) then have neq_y: "(f ^^ (funpow_dist1 f x y - n)) x \<noteq> y" by (simp add: funpow_dist1_least) have "(f ^^ (funpow_dist1 f x y - n)) x = (f ^^ (funpow_dist1 f x y - n)) ((f ^^ n) x)" using n by (simp add: funpow_add_app) also have "\<dots> = (f ^^ funpow_dist1 f x y) x" using \<open>n < _\<close> by (simp add: funpow_add_app) also have "\<dots> = y" using assms by (rule funpow_dist1_prop) finally show False using neq_y by contradiction qed lemma not_in_segment2: "y \<notin> segment f x y" using not_in_segment2D by metis (*XXX move*) lemma in_segmentE: assumes "y \<in> segment f x z" "z \<in> orbit f x" obtains "(f ^^ funpow_dist1 f x y) x = y" "funpow_dist1 f x y < funpow_dist1 f x z" proof from assms show "(f ^^ funpow_dist1 f x y) x = y" by (intro segmentD_orbit funpow_dist1_prop) moreover obtain n where "(f ^^ n) x = y" "0 < n" "n < funpow_dist1 f x z" using assms by (auto simp: segment_altdef) moreover then have "funpow_dist1 f x y \<le> n" by (meson funpow_dist1_least not_less) ultimately show "funpow_dist1 f x y < funpow_dist1 f x z" by linarith qed (*XXX move*) lemma cyclic_split_segment: assumes S: "cyclic_on f S" "a \<in> S" "b \<in> S" and "a \<noteq> b" shows "S = {a,b} \<union> segment f a b \<union> segment f b a" (is "?L = ?R") proof (intro set_eqI iffI) fix c assume "c \<in> ?L" with S have "c \<in> orbit f a" unfolding cyclic_on_alldef by auto then show "c \<in> ?R" by induct (auto intro: segment.intros) next fix c assume "c \<in> ?R" moreover have "segment f a b \<subseteq> orbit f a" "segment f b a \<subseteq> orbit f b" by (auto dest: segmentD_orbit) ultimately show "c \<in> ?L" using S by (auto simp: cyclic_on_alldef) qed (*XXX move*) lemma segment_split: assumes y_in_seg: "y \<in> segment f x z" shows "segment f x z = segment f x y \<union> {y} \<union> segment f y z" (is "?L = ?R") proof (intro set_eqI iffI) fix w assume "w \<in> ?L" then show "w \<in> ?R" by induct (auto intro: segment.intros) next fix w assume "w \<in> ?R" moreover { assume "w \<in> segment f x y" then have "w \<in> segment f x z" using segment_subset[OF y_in_seg] by auto } moreover { assume "w \<in> segment f y z" then have "w \<in> segment f x z" using y_in_seg by induct (auto intro: segment.intros) } ultimately show "w \<in> ?L" using y_in_seg by (auto intro: segment.intros) qed lemma in_segmentD_inv: assumes "x \<in> segment f a b" "x \<noteq> f a" assumes "inj f" shows "inv f x \<in> segment f a b" using assms by (auto elim: segment.cases) lemma in_orbit_invI: assumes "b \<in> orbit f a" assumes "inj f" shows "a \<in> orbit (inv f) b" using assms(1) apply induct apply (simp add: assms(2) orbit_eqI(1)) by (metis assms(2) inv_f_f orbit.base orbit_trans) lemma segment_step_2: assumes A: "x \<in> segment f a b" "b \<noteq> a" and "inj f" shows "x \<in> segment f a (f b)" using A by induct (auto intro: segment.intros dest: not_in_segment2D injD[OF \<open>inj f\<close>]) lemma inv_end_in_segment: assumes "b \<in> orbit f a" "f a \<noteq> b" "bij f" shows "inv f b \<in> segment f a b" using assms(1,2) proof induct case base then show ?case by simp next case (step x) moreover from \<open>bij f\<close> have "inj f" by (rule bij_is_inj) moreover then have "x \<noteq> f x \<Longrightarrow> f a = x \<Longrightarrow> x \<in> segment f a (f x)" by (meson segment.simps) moreover have "x \<noteq> f x" using step \<open>inj f\<close> by (metis in_orbit_invI inv_f_eq not_in_segment1 segment.base) then have "inv f x \<in> segment f a (f x) \<Longrightarrow> x \<in> segment f a (f x)" using \<open>bij f\<close> \<open>inj f\<close> by (auto dest: segment.step simp: surj_f_inv_f bij_is_surj) then have "inv f x \<in> segment f a x \<Longrightarrow> x \<in> segment f a (f x)" using \<open>f a \<noteq> f x\<close> \<open>inj f\<close> by (auto dest: segment_step_2 injD) ultimately show ?case by (cases "f a = x") simp_all qed lemma segment_overlapping: assumes "x \<in> orbit f a" "x \<in> orbit f b" "bij f" shows "segment f a x \<subseteq> segment f b x \<or> segment f b x \<subseteq> segment f a x" using assms(1,2) proof induction case base then show ?case by (simp add: segment1_empty) next case (step x) from \<open>bij f\<close> have "inj f" by (simp add: bij_is_inj) have *: "\<And>f x y. y \<in> segment f x (f x) \<Longrightarrow> False" by (simp add: segment1_empty) { fix y z assume A: "y \<in> segment f b (f x)" "y \<notin> segment f a (f x)" "z \<in> segment f a (f x)" from \<open>x \<in> orbit f a\<close> \<open>f x \<in> orbit f b\<close> \<open>y \<in> segment f b (f x)\<close> have "x \<in> orbit f b" by (metis * inv_end_in_segment[OF _ _ \<open>bij f\<close>] inv_f_eq[OF \<open>inj f\<close>] segmentD_orbit) moreover with \<open>x \<in> orbit f a\<close> step.IH have "segment f a (f x) \<subseteq> segment f b (f x) \<or> segment f b (f x) \<subseteq> segment f a (f x)" apply auto apply (metis * inv_end_in_segment[OF _ _ \<open>bij f\<close>] inv_f_eq[OF \<open>inj f\<close>] segment_step_2D segment_subset step.prems subsetCE) by (metis (no_types, lifting) \<open>inj f\<close> * inv_end_in_segment[OF _ _ \<open>bij f\<close>] inv_f_eq orbit_eqI(2) segment_step_2D segment_subset subsetCE) ultimately have "segment f a (f x) \<subseteq> segment f b (f x)" using A by auto } note C = this then show ?case by auto qed lemma segment_disj: assumes "a \<noteq> b" "bij f" shows "segment f a b \<inter> segment f b a = {}" proof (rule ccontr) assume "\<not>?thesis" then obtain x where x: "x \<in> segment f a b" "x \<in> segment f b a" by blast then have "segment f a b = segment f a x \<union> {x} \<union> segment f x b" "segment f b a = segment f b x \<union> {x} \<union> segment f x a" by (auto dest: segment_split) then have o: "x \<in> orbit f a" "x \<in> orbit f b" by (auto dest: segmentD_orbit) note * = segment_overlapping[OF o \<open>bij f\<close>] have "inj f" using \<open>bij f\<close> by (simp add: bij_is_inj) have "segment f a x = segment f b x" proof (intro set_eqI iffI) fix y assume A: "y \<in> segment f b x" then have "y \<in> segment f a x \<or> f a \<in> segment f b a" using * x(2) by (auto intro: segment.base segment_subset) then show "y \<in> segment f a x" using \<open>inj f\<close> A by (metis (no_types) not_in_segment2 segment_step_2) next fix y assume A: "y \<in> segment f a x " then have "y \<in> segment f b x \<or> f b \<in> segment f a b" using * x(1) by (auto intro: segment.base segment_subset) then show "y \<in> segment f b x" using \<open>inj f\<close> A by (metis (no_types) not_in_segment2 segment_step_2) qed moreover have "segment f a x \<noteq> segment f b x" by (metis assms bij_is_inj not_in_segment2 segment.base segment_step_2 segment_subset x(1)) ultimately show False by contradiction qed lemma segment_x_x_eq: assumes "permutation f" shows "segment f x x = orbit f x - {x}" (is "?L = ?R") proof (intro set_eqI iffI) fix y assume "y \<in> ?L" then show "y \<in> ?R" by (auto dest: segmentD_orbit simp: not_in_segment2) next fix y assume "y \<in> ?R" then have "y \<in> orbit f x" "y \<noteq> x" by auto then show "y \<in> ?L" by induct (auto intro: segment.intros) qed section \<open>Lists of Powers\<close> definition iterate :: "nat \<Rightarrow> nat \<Rightarrow> ('a \<Rightarrow> 'a ) \<Rightarrow> 'a \<Rightarrow> 'a list" where "iterate m n f x = map (\<lambda>n. (f^^n) x) [m..<n]" lemma set_iterate: "set (iterate m n f x) = (\<lambda>k. (f ^^ k) x) ` {m..<n} " by (auto simp: iterate_def) lemma iterate_empty[simp]: "iterate n m f x = [] \<longleftrightarrow> m \<le> n" by (auto simp: iterate_def) lemma iterate_nth[simp]: assumes "k < n - m" shows "iterate m n f x ! k = (f^^(m+k)) x" using assms by (induct k arbitrary: m) (auto simp: iterate_def) lemma iterate_applied: "iterate n m f (f x) = iterate (Suc n) (Suc m) f x" by (induct m arbitrary: n) (auto simp: iterate_def funpow_swap1) end
From iris.algebra Require Import excl. From iris.algebra.lib Require Import excl_auth. From trillium.prelude Require Import finitary. From iris.base_logic.lib Require Import invariants. From iris.proofmode Require Import coq_tactics reduction spec_patterns tactics. From aneris.aneris_lang Require Import lang. From aneris.aneris_lang.lib Require Import inject lock_proof list_proof pers_socket_proto. From aneris.aneris_lang.lib.serialization Require Import serialization_proof. From aneris.aneris_lang.program_logic Require Import aneris_lifting. From aneris.examples.reliable_communication Require Import user_params client_server_code. From aneris.examples.reliable_communication.spec Require Import resources api_spec. From aneris.examples.reliable_communication.resources Require Import prelude. From aneris.examples.reliable_communication.instantiation Require Import instantiation_of_resources. Set Default Proof Using "Type". (* -------------------------------------------------------------------------- *) (** Instantiation of the server side specifications socket and connect. *) (* -------------------------------------------------------------------------- *) From aneris.examples.reliable_communication.proof.server Require Import proof_of_make_server_skt proof_of_server_listen proof_of_accept. Section Server_API_spec_instantiation. Context `{!anerisG Mdl Σ}. Context `{!lockG Σ}. Context `{!chanG Σ}. Context `{!server_ghost_names}. Context `{User_params: !Reliable_communication_service_params}. Lemma make_server_skt_spec_holds : make_server_skt_spec User_params session_resources_instance. Proof. rewrite /make_server_skt_spec. rewrite /SrvInit /session_resources_instance /SrvInitRes /SrvCanListen. iIntros (Φ) "(H1 & H2 & H3 & H4 & H5 & H6 & H7 & H8) HΦ". iApply (make_server_skt_internal_spec with "[$][$HΦ]"). Qed. Lemma server_listen_spec_holds : server_listen_spec User_params session_resources_instance. Proof. rewrite /server_listen_spec. rewrite /SrvCanListen /SrvListens. iIntros (skt Φ) "Hyp HΦ". simpl. iApply (server_listen_internal_spec with "[$][$HΦ]"). Qed. Lemma accept_spec_holds : accept_spec User_params session_resources_instance. Proof. rewrite /server_listen_spec. rewrite /session_resources_instance !/SrvListens. rewrite /chan_mapsto_resource_instance. iIntros (skt Φ) "Hyp HΦ". iApply (accept_internal_spec with "[$Hyp][HΦ]"). iNext. iIntros (γe c clt_addr) "(H1 & H2 & _)". iApply "HΦ". rewrite /SrvListens. iFrame. iExists _; iFrame. Qed. End Server_API_spec_instantiation.
[STATEMENT] lemma select_edge_refine: assumes A: "(s,(p,D,pE))\<in>GS_rel" assumes NE: "p \<noteq> []" shows "select_edge_impl s \<le> \<Down>(Id \<times>\<^sub>r GS_rel) (select_edge (p,D,pE))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. select_edge_impl s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (p, D, pE)) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. select_edge_impl s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (p, D, pE)) [PROOF STEP] from A [PROOF STATE] proof (chain) picking this: (s, p, D, pE) \<in> GS_rel [PROOF STEP] have [simp]: "p=GS.p_\<alpha> s \<and> D=GS.D_\<alpha> s \<and> pE=GS.pE_\<alpha> s" and INV: "GS_invar s" [PROOF STATE] proof (prove) using this: (s, p, D, pE) \<in> GS_rel goal (1 subgoal): 1. p = GS.p_\<alpha> s \<and> D = GS.D_\<alpha> s \<and> pE = GS.pE_\<alpha> s &&& GS_invar s [PROOF STEP] by (auto simp add: GS_rel_def br_def GS_\<alpha>_split) [PROOF STATE] proof (state) this: p = GS.p_\<alpha> s \<and> D = GS.D_\<alpha> s \<and> pE = GS.pE_\<alpha> s GS_invar s goal (1 subgoal): 1. select_edge_impl s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (p, D, pE)) [PROOF STEP] from INV NE [PROOF STATE] proof (chain) picking this: GS_invar s p \<noteq> [] [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: GS_invar s p \<noteq> [] goal (1 subgoal): 1. select_edge_impl s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (p, D, pE)) [PROOF STEP] unfolding select_edge_impl_def [PROOF STATE] proof (prove) using this: GS_invar s p \<noteq> [] goal (1 subgoal): 1. GS.sel_rem_last s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (p, D, pE)) [PROOF STEP] using GS_invar.sel_rem_last_correct[OF INV] NE [PROOF STATE] proof (prove) using this: GS_invar s p \<noteq> [] GS.p_\<alpha> s \<noteq> [] \<Longrightarrow> GS.sel_rem_last s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (GS.p_\<alpha> s, GS.D_\<alpha> s, GS.pE_\<alpha> s)) p \<noteq> [] goal (1 subgoal): 1. GS.sel_rem_last s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (p, D, pE)) [PROOF STEP] by (simp) [PROOF STATE] proof (state) this: select_edge_impl s \<le> \<Down> (Id \<times>\<^sub>r GS_rel) (select_edge (p, D, pE)) goal: No subgoals! [PROOF STEP] qed
module Covid include("Stats.jl") #incluimos los archivos con las funciones include("Utils.jl") end
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.divergence_theorem import analysis.box_integral.integrability /-! # Divergence theorem for Bochner integral In this file we prove the Divergence theorem for Bochner integral on a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`. More precisely, we prove the following theorem. Let `E` be a complete normed space with second countably topology. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriat signs. Moreover, the same is true if the function is not differentiable but continuous at countably many points of `[a, b]`. ## Notations We use the following local notation to make the statement more readable. Note that the documentation website shows the actual terms, not those abbreviated using local notations. * `ℝⁿ`, `ℝⁿ⁺¹`, `Eⁿ⁺¹`: `fin n → ℝ`, `fin (n + 1) → ℝ`, `fin (n + 1) → E`; * `face i`: the `i`-th face of the box `[a, b]` as a closed segment in `ℝⁿ`, namely `[a ∘ fin.succ_above i, b ∘ fin.succ_above i]`; * `e i` : `i`-th basis vector `pi.single i 1`; * `front_face i`, `back_face i`: embeddings `ℝⁿ → ℝⁿ⁺¹` corresponding to the front face `{x | x i = b i}` and back face `{x | x i = a i}` of the box `[a, b]`, respectively. They are given by `fin.insert_nth i (b i)` and `fin.insert_nth i (a i)`. ## TODO * Deduce corollaries about integrals in `ℝ × ℝ` and interval integral. * Add a version that assumes existence and integrability of partial derivatives. ## Tags divergence theorem, Bochner integral -/ open set finset topological_space function box_integral open_locale big_operators classical namespace measure_theory universes u variables {E : Type u} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [second_countable_topology E] [complete_space E] section variables {n : ℕ} local notation `ℝⁿ` := fin n → ℝ local notation `ℝⁿ⁺¹` := fin (n + 1) → ℝ local notation `Eⁿ⁺¹` := fin (n + 1) → E variables (a b : ℝⁿ⁺¹) local notation `face` i := set.Icc (a ∘ fin.succ_above i) (b ∘ fin.succ_above i) local notation `e` i := pi.single i 1 local notation `front_face` i:2000 := fin.insert_nth i (b i) local notation `back_face` i:2000 := fin.insert_nth i (a i) /-- **Divergence theorem** for Bochner integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriat signs. Moreover, the same is true if the function is not differentiable but continuous at countably many points of `[a, b]`. We represent both faces `x i = a i` and `x i = b i` as the box `face i = [a ∘ fin.succ_above i, b ∘ fin.succ_above i]` in `ℝⁿ`, where `fin.succ_above : fin n ↪o fin (n + 1)` is the order embedding with range `{i}ᶜ`. The restrictions of `f : ℝⁿ⁺¹ → Eⁿ⁺¹` to these faces are given by `f ∘ back_face i` and `f ∘ front_face i`, where `back_face i = fin.insert_nth i (a i)` and `front_face i = fin.insert_nth i (b i)` are embeddings `ℝⁿ → ℝⁿ⁺¹` that take `y : ℝⁿ` and insert `a i` (resp., `b i`) as `i`-th coordinate. -/ lemma integral_divergence_of_has_fderiv_within_at_off_countable (hle : a ≤ b) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : countable s) (Hc : ∀ x ∈ s, continuous_within_at f (Icc a b) x) (Hd : ∀ x ∈ Icc a b \ s, has_fderiv_within_at f (f' x) (Icc a b) x) (Hi : integrable_on (λ x, ∑ i, f' x (pi.single i 1) i) (Icc a b)) : ∫ x in Icc a b, ∑ i, f' x (e i) i = ∑ i : fin (n + 1), ((∫ x in face i, f (front_face i x) i) - ∫ x in face i, f (back_face i x) i) := begin simp only [volume_pi, ← set_integral_congr_set_ae measure.univ_pi_Ioc_ae_eq_Icc], by_cases heq : ∃ i, a i = b i, { rcases heq with ⟨i, hi⟩, have hi' : Ioc (a i) (b i) = ∅ := Ioc_eq_empty hi.not_lt, have : pi set.univ (λ j, Ioc (a j) (b j)) = ∅, from univ_pi_eq_empty hi', rw [this, integral_empty, sum_eq_zero], rintro j -, rcases eq_or_ne i j with rfl|hne, { simp [hi] }, { rcases fin.exists_succ_above_eq hne with ⟨i, rfl⟩, have : pi set.univ (λ k : fin n, Ioc (a $ j.succ_above k) (b $ j.succ_above k)) = ∅, from univ_pi_eq_empty hi', rw [this, integral_empty, integral_empty, sub_self] } }, { push_neg at heq, obtain ⟨I, rfl, rfl⟩ : ∃ I : box_integral.box (fin (n + 1)), I.lower = a ∧ I.upper = b, from ⟨⟨a, b, λ i, (hle i).lt_of_ne (heq i)⟩, rfl, rfl⟩, simp only [← box.coe_eq_pi, ← box.face_lower, ← box.face_upper], have A := ((Hi.mono_set box.coe_subset_Icc).has_box_integral ⊥ rfl), have B := has_integral_bot_divergence_of_forall_has_deriv_within_at I f f' s hs Hc Hd, have Hc : continuous_on f I.Icc, { intros x hx, by_cases hxs : x ∈ s, exacts [Hc x hxs, (Hd x ⟨hx, hxs⟩).continuous_within_at] }, rw continuous_on_pi at Hc, refine (A.unique B).trans (sum_congr rfl $ λ i hi, _), refine congr_arg2 has_sub.sub _ _, { have := box.continuous_on_face_Icc (Hc i) (set.right_mem_Icc.2 (hle i)), have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc, exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance }, { have := box.continuous_on_face_Icc (Hc i) (set.left_mem_Icc.2 (hle i)), have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc, exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance } } end end end measure_theory
! written by jxzou at 20191030: transform basis sets in GAMESS format to (Open)Molcas format ! updated by jxzou at 20200326: move lower angular momentum (occurred 2nd time) forward ! This special case happens at, e.g. def2TZVP for Co. The MOs moved forward have been ! considered in fch2inporb. Here the basis sets should be adjusted correspondingly. ! updated by jxzou at 20200402: ECP/PP supported ! updated by jxzou at 20201110: dealing with the extra primitive duplicate, e.g. ! cc-pVDZ for Co. The original way is to both extend column and row. Now the ! trick is to only extend column, thus will not generate the primitive duplicate. ! The primitive duplicate is not allowed in relativistic calculations. ! updated by jxzou at 20201209: move some subroutines to read_gms_inp.f90 ! updated by jxzou at 20210207: add contraction strings into '.....' ! Note: Currently isotopes are not tested. program main use pg, only: iout implicit none integer :: i character(len=4) :: str character(len=240) :: fname ! fname: input file contains basis sets and Cartesian coordinates in GAMESS format logical :: spherical i = iargc() if(i<1 .or. i>2) then write(iout,'(/,A,/)') 'Example1: bas_gms2molcas a.inp (generate an a.input file)' write(iout,'(A,/)') "Example2: bas_gms2molcas a.inp -sph (without 'Cartesian all')" stop end if str = ' ' fname = ' ' spherical = .false. call getarg(1, fname) call require_file_exist(fname) if(i == 2) then call getarg(2,str) if(str == '-sph') then spherical = .true. else write(iout,'(A)') 'ERROR in subroutine bas_gms2molcas: wrong command line arguments!' write(iout,'(A)') "The 2nd argument can only be '-sph'. But got '"//str//"'" stop end if end if call bas_gms2molcas(fname, spherical) stop end program main ! Transform the basis sets in GAMESS format to those in (Open)Molcas format subroutine bas_gms2molcas(fort7, spherical) use pg, only: iout, natom, ram, ntimes, elem, coor, prim_gau, all_ecp, ecp_exist implicit none integer :: i, nline, rc, rel, charge, mult, fid1, fid2 character(len=240), intent(in) :: fort7 character(len=240) :: buf, input ! input is the (Open)Molcas .input file character(len=1) :: stype character(len=21) :: str1, str2 logical, intent(in) :: spherical logical :: uhf, X2C ! initialization buf = ' ' input = ' ' i = index(fort7, '.', back=.true.) input = fort7(1:i-1)//'.input' call read_natom_from_gms_inp(fort7, natom) allocate(ram(natom), elem(natom), coor(3,natom), ntimes(natom)) call read_elem_nuc_coor_from_gms_inp(fort7, natom, elem, ram, coor) ! ram cannot be deallocated here since subroutine prt_prim_gau will use it call calc_ntimes(natom, elem, ntimes) call read_charge_and_mult_from_gms_inp(fort7, charge, mult, uhf, ecp_exist) call read_all_ecp_from_gms_inp(fort7) ! find the $DATA section open(newunit=fid1,file=TRIM(fort7),status='old',position='rewind') do while(.true.) read(fid1,'(A)',iostat=rc) buf if(rc /= 0) exit if(buf(2:2) == '$') then call upper(buf(3:6)) if(buf(3:6) == 'DATA') exit end if end do ! for while if(rc /= 0) then write(iout,'(A)') 'ERROR in subroutine bas_gms2molcas: No $DATA section found& & in file '//TRIM(fort7)//'.' close(fid1) stop end if ! skip 2 lines: the Title line and the Point Group line read(fid1,'(A)') buf read(fid1,'(A)') buf open(newunit=fid2,file=TRIM(input),status='replace') write(fid2,'(A)') "&GATEWAY" ! write(fid2,'(A)') 'Expert' ! initialization: clear all primitive gaussians call clear_prim_gau() do i = 1, natom, 1 read(fid1,'(A)',iostat=rc) buf if(rc /= 0) exit ! 'buf' contains the element, ram and coordinates write(fid2,'(A)') 'Basis set' ! deal with primitive gaussians do while(.true.) read(fid1,'(A)') buf if(LEN_TRIM(buf) == 0) exit read(buf,*) stype, nline call read_prim_gau(stype, nline, fid1) end do ! for while if(all_ecp(i)%ecp) then write(fid2,'(A)',advance='no') TRIM(elem(i))//'.ECP..' else write(fid2,'(A)',advance='no') TRIM(elem(i))//'...' end if call gen_contracted_string(prim_gau(:)%nline,prim_gau(:)%ncol,str1,str2) write(fid2,'(A)') TRIM(str1)//'.'//TRIM(str2)//'. / inline' ! print basis sets and ECP/PP (if any) of this atom in Molcas format call prt_prim_gau(i, fid2) write(fid2,'(A,I0,3(2X,F15.8),A)') TRIM(elem(i)), ntimes(i), & coor(1:3,i),' Angstrom' if(.not. spherical) write(fid2,'(A)') 'Cartesian all' write(fid2,'(A)') 'End of basis set' ! clear all primitive gaussians for next cycle call clear_prim_gau() end do ! for i close(fid1) ! now ram can be deallocated deallocate(ram, elem, ntimes, coor, all_ecp) if(rc /= 0) then write(iout,'(A)') "ERROR in subroutine bas_gms2molcas: it seems the '$DATA'& & has no corresponding '$END'." write(iout,'(A)') 'Incomplete file '//TRIM(fort7) close(fid2,status='delete') stop end if call check_X2C_in_gms_inp(fort7, X2C) if(X2C) write(fid2,'(A)') 'RX2C' write(fid2,'(/,A)') "&SEWARD" call check_DKH_in_gms_inp(fort7, rel) select case(rel) case(-2) ! nothing case(-1) ! RESC write(iout,'(A)') 'ERROR in subroutine bas_gms2molcas: RESC keywords detected.' write(iout,'(A)') 'But RESC is not supported in (Open)Molcas.' stop case(0,1,2,4) ! DKH0/1/2/4 if(.not. X2C) write(fid2,'(A,I2.2,A)') 'Relativistic = R',rel,'O' !if(.not. X2C) write(fid2,'(A,I2.2,A)') 'R',rel,'O' case default write(iout,'(A)') 'ERROR in subroutine bas_gms2molcas: rel out of range!' write(iout,'(A,I0)') 'rel=', rel close(fid2,status='delete') stop end select write(fid2,'(/,A)') "&SCF" if(uhf) write(fid2,'(A)') 'UHF' write(fid2,'(A,I0)') 'Charge = ', charge write(fid2,'(A,I0)') 'Spin = ', mult i = INDEX(fort7, '.', back=.true.) input = fort7(1:i-1)//'.INPORB' write(fid2,'(A)') 'FILEORB = '//TRIM(input) if((.not.uhf) .and. (mult/=1)) then ! ROHF write(fid2,'(A)') "* ROHF is not directly supported in (Open)Molcas. You& & need to write &RASSCF module to realize ROHF." end if close(fid2) return end subroutine bas_gms2molcas
module Test.Spec import Specdris.Spec import Text.Parse.Tibetan import Text.Show.Tibetan export specSuite : IO () specSuite = do spec $ do describe "readTest" $ do it "should parse Latin numerals" $ do readTest "126" `shouldBe` Right 126 --readBo "༡༢༦" `shouldBe` Right 126 describe "showTest" $ do it "should display numerals" $ do showTest 123 `shouldBe` "123" --showBo 123 `shouldBe` "༡༢༣"
function out = get_scale_sample(im, pos, base_target_sz, scaleFactors, scale_window, scale_model_sz) % out = get_scale_sample(im, pos, base_target_sz, scaleFactors, scale_window, scale_model_sz) % % Extracts a sample for the scale filter at the current % location and scale. nScales = length(scaleFactors); for s = 1:nScales patch_sz = floor(base_target_sz * scaleFactors(s)); xs = floor(pos(2)) + (1:patch_sz(2)) - floor(patch_sz(2)/2); ys = floor(pos(1)) + (1:patch_sz(1)) - floor(patch_sz(1)/2); % check for out-of-bounds coordinates, and set them to the values at % the borders xs(xs < 1) = 1; ys(ys < 1) = 1; xs(xs > size(im,2)) = size(im,2); ys(ys > size(im,1)) = size(im,1); % extract image im_patch = im(ys, xs, :); % resize image to model size im_patch_resized = imResample(im_patch, scale_model_sz); % extract scale features temp_hog = fhog(single(im_patch_resized), 4); temp = temp_hog(:,:,1:31); if s == 1 out = zeros(numel(temp), nScales, 'single'); end % window out(:,s) = temp(:) * scale_window(s); end
The $\sigma$-algebra generated by a single set $A$ is $\{\emptyset, A\}$.
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial.derivative /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - sum of finitely many functions - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space big_operators filter ennreal open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝[s] x) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := fderiv_within 𝕜 f s x 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := fderiv 𝕜 f x 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp lemma has_deriv_within_at.has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x := has_deriv_within_at_iff_has_fderiv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp lemma has_strict_deriv_at_iff_has_strict_fderiv_at : has_strict_deriv_at f f' x ↔ has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x := iff.rfl alias has_strict_deriv_at_iff_has_strict_fderiv_at ↔ has_strict_deriv_at.has_strict_fderiv_at _ /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x := iff.rfl alias has_deriv_at_iff_has_fderiv_at ↔ has_deriv_at.has_fderiv_at _ lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right, simp only [(∘)], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s \ {x}] x) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s] x) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[{x}ᶜ] x) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope @[simp] lemma has_deriv_within_at_diff_singleton : has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x := by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem] @[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] : has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x := by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Ioi_iff_Ici ↔ has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici @[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] : has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x := by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Iio_iff_Iic ↔ has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at.unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ h₀.has_fderiv_at.unique h₁ lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := h.differentiable_at.has_deriv_at.unique h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) : deriv_within f s x = deriv f x := by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl } section congr /-! ### Congruence properties of derivatives -/ theorem filter.eventually_eq.has_deriv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := h₀.has_fderiv_at_filter_iff hx (by simp [h₁]) lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa hL.has_deriv_at_filter_iff hx rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x := h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx) lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw hL.fderiv_within_eq hs hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x := by { unfold deriv, rwa filter.eventually_eq.fderiv_eq } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 := deriv_id x lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) protected lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter protected lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at protected lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter protected lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] protected lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv protected lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) protected lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter protected lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at protected lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter protected lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] protected lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv protected lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section analytic variables {p : formal_multilinear_series 𝕜 𝕜 F} {r : ℝ≥0∞} protected lemma has_fpower_series_at.has_strict_deriv_at (h : has_fpower_series_at f p x) : has_strict_deriv_at f (p 1 (λ _, 1)) x := h.has_strict_fderiv_at.has_strict_deriv_at protected lemma has_fpower_series_at.has_deriv_at (h : has_fpower_series_at f p x) : has_deriv_at f (p 1 (λ _, 1)) x := h.has_strict_deriv_at.has_deriv_at protected lemma has_fpower_series_at.deriv (h : has_fpower_series_at f p x) : deriv f x = p 1 (λ _, 1) := h.has_deriv_at.deriv end analytic section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_add_const hxs] lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x := by simp only [deriv, fderiv_add_const] theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c + f y) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_const_add hxs] lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x := by simp only [deriv, fderiv_const_add] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section pi /-! ### Derivatives of functions `f : 𝕜 → Π i, E i` -/ variables {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_group (E' i)] [Π i, normed_space 𝕜 (E' i)] {φ : 𝕜 → Π i, E' i} {φ' : Π i, E' i} @[simp] lemma has_strict_deriv_at_pi : has_strict_deriv_at φ φ' x ↔ ∀ i, has_strict_deriv_at (λ x, φ x i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_deriv_at_filter_pi : has_deriv_at_filter φ φ' x L ↔ ∀ i, has_deriv_at_filter (λ x, φ x i) (φ' i) x L := has_fderiv_at_filter_pi' lemma has_deriv_at_pi : has_deriv_at φ φ' x ↔ ∀ i, has_deriv_at (λ x, φ x i) (φ' i) x:= has_deriv_at_filter_pi lemma has_deriv_within_at_pi : has_deriv_within_at φ φ' s x ↔ ∀ i, has_deriv_within_at (λ x, φ x i) (φ' i) s x:= has_deriv_at_filter_pi lemma deriv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (λ x, φ x i) s x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within φ s x = λ i, deriv_within (λ x, φ x i) s x := (has_deriv_within_at_pi.2 (λ i, (h i).has_deriv_within_at)).deriv_within hs lemma deriv_pi (h : ∀ i, differentiable_at 𝕜 (λ x, φ x i) x) : deriv φ x = λ i, deriv (λ x, φ x i) x := (has_deriv_at_pi.2 (λ i, (h i).has_deriv_at)).deriv end pi section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply] lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_sub_const hxs] lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x := by simp only [deriv, fderiv_sub_const] theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c - f y) s x = -deriv_within f s x := by simp [deriv_within, fderiv_within_const_sub hxs] lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x := by simp only [← deriv_within_univ, deriv_within_const_sub unique_diff_within_at_univ] end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h protected theorem has_deriv_at.continuous_on {f f' : 𝕜 → F} (hderiv : ∀ x ∈ s, has_deriv_at f (f' x) x) : continuous_on f s := λ x hx, (hderiv x hx).continuous_at.continuous_within_at end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := by simpa using (hg.comp x hh).has_deriv_at_filter theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg $ hh.continuous_within_at.tendsto_nhds_within hst) hh /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g ∘ h) (h' • g') x := by simpa using (hg.comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of a scalar and vector functions -/ theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) {L : filter E} (hh₁ : has_deriv_at_filter h₁ h₁' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (h₁ ∘ f) (h₁' • f') x L := by { convert has_fderiv_at_filter.comp x hh₁ hf, ext x, simp [mul_comm] } theorem has_strict_deriv_at.comp_has_strict_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) (hh₁ : has_strict_deriv_at h₁ h₁' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (h₁ ∘ f) (h₁' • f') x := by { rw has_strict_deriv_at at hh₁, convert hh₁.comp x hf, ext x, simp [mul_comm] } theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (h₁ ∘ f) (h₁' • f') x := (hh₁.mono hf.continuous_at).comp_has_fderiv_at_filter x hf theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (hh₁.mono hf.continuous_within_at).comp_has_fderiv_at_filter x hf theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s t} (x) (hh₁ : has_deriv_within_at h₁ h₁' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : maps_to f s t) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (has_deriv_at_filter.mono hh₁ $ hf.continuous_within_at.tendsto_nhds_within hst).comp_has_fderiv_at_filter x hf /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_strict_deriv_at.comp (hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) : has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_deriv_at_filter (f^[n]) (f'^n) x L := begin have := hf.iterate hL hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_deriv_at (f^[n]) (f'^n) x := begin have := has_fderiv_at.iterate hf hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_deriv_within_at (f^[n]) (f'^n) s x := begin have := has_fderiv_within_at.iterate hf hx hs n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_deriv_at (f^[n]) (f'^n) x := begin have := hf.iterate hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and a function on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝕜) : has_strict_deriv_at (λ y, c y * d) (c' * d) x := begin convert hc.mul (has_strict_deriv_at_const x d), rw [mul_zero, add_zero] end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end theorem has_strict_deriv_at.const_mul (c : 𝕜) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c * d y) (c * d') x := begin convert (has_strict_deriv_at_const _ _).mul hd, rw [zero_mul, zero_add] end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) (λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono (mem_nhds_sets (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) (hx : d x ≠ 0) : has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} : differentiable_within_at 𝕜 (λx, c x / d) s x := by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc] @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : differentiable_at 𝕜 (λ x, c x / d) x := by simpa only [div_eq_mul_inv] using (hc.has_deriv_at.mul_const d⁻¹).differentiable_at lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} : differentiable_on 𝕜 (λx, c x / d) s := by simp [div_eq_inv_mul, differentiable_on.const_mul, hc] @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} : differentiable 𝕜 (λx, c x / d) := by simp [div_eq_inv_mul, differentiable.const_mul, hc] lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : deriv (λx, c x / d) x = (deriv c x) / d := by simp [div_eq_inv_mul, deriv_const_mul, hc] end division theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has a nonzero derivative `f'` at `f.symm a` in the strict sense, then `f.symm` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_strict_deriv_at f f' (f.symm a)) : has_strict_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an nonzero derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) : has_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := (has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne ⟨∥f'∥⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩ theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a) (hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) : ¬differentiable_within_at 𝕜 g s a := begin intro hg, have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha, simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _) end theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) : ¬differentiable_at 𝕜 g a := begin intro hg, have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm, simpa using this.unique (has_deriv_at_id a) end end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) x := p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) := (p.has_fderiv_within_at x).fderiv_within hxs end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_C_mul_X_pow], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, nat.sub_zero, nat.cast_one] }, { simp only [function.iterate_succ_apply', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_assoc, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [gpow_coe_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, gpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div, inv_inv', smul_eq_mul] at this, convert this using 1, rw [sq, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, gpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_fpow m hx).has_deriv_at theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = (∏ i in finset.range k, (m - i) : ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [function.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], exact filter.eventually_eq.deriv_eq (eventually.mono (mem_nhds_sets is_open_ne hx) @ihk) } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in 𝓝[s \ {x}] x, (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in 𝓝[s] x, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r := (hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently, refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
## Example script for constant-strength source panel method using LinearAlgebra using Base.Iterators using Seaborn using AeroMDAO ## Airfoil airfoil = Foil(naca4((0,0,1,2), 81; sharp_trailing_edge = true)) V, α = 1., 0. ρ = 1.225 uniform = Uniform2D(V, α) num_pans = 80 panels = paneller(airfoil, num_pans); ## Constant-strength source panel A = @time constant_source_matrix(panels) b = @time constant_source_boundary_condition(panels, velocity(uniform)) σs = A \ b ## sum(σs) ## Pressure coefficient pts = collocation_point.(panels); panel_vels = [ velocity(uniform) .+ sum(source_velocity.(σs, panels, Ref(panel_i))) for panel_i in panels ] qts = @. dot(panel_vels, panel_tangent(panels)) cps = @. 1 - qts^2 / uniform.mag^2 ## upper, lower = get_surface_values(panels, cps) lower = [ upper[end]; lower; upper[1] ] plot(first.(upper), last.(upper), label = "Upper") plot(first.(lower), last.(lower), label = "Lower") ylim(maximum(cps), minimum(cps)) xlabel("(x/c)") ylabel("Cp") # legend() show() ## Plotting x_domain, y_domain = (-1, 2), (-1, 1) grid_size = 50 x_dom, y_dom = range(x_domain..., length = grid_size), range(y_domain..., length = grid_size) grid = product(x_dom, y_dom) pts = panel_points(panels); source_vels = [ velocity(uniform) .+ sum(source_velocity.(σs, panels, x, y)) for (x, y) in grid ] speeds = @. sqrt(first(source_vels)^2 + last(source_vels)^2) cps = @. 1 - speeds^2 / uniform.mag^2 contourf(first.(grid), last.(grid), cps) CB1 = colorbar(label = "Pressure Coefficient (Cp)") # quiver(first.(grid), last.(grid), first.(source_vels), last.(source_vels), speeds) streamplot(first.(grid)', last.(grid)', first.(source_vels)', last.(source_vels)', color = speeds', cmap = "coolwarm", density = 3) CB2 = colorbar(orientation="horizontal", label = "Relative Airspeed (U/U∞)") fill(first.(pts), last.(pts), color = "black", zorder = 3) tight_layout() show()
lemma pred_intros_countable_bounded[measurable (raw)]: fixes X :: "'i :: countable set" shows "(\<And>i. i \<in> X \<Longrightarrow> pred M (\<lambda>x. x \<in> N x i)) \<Longrightarrow> pred M (\<lambda>x. x \<in> (\<Inter>i\<in>X. N x i))" "(\<And>i. i \<in> X \<Longrightarrow> pred M (\<lambda>x. x \<in> N x i)) \<Longrightarrow> pred M (\<lambda>x. x \<in> (\<Union>i\<in>X. N x i))" "(\<And>i. i \<in> X \<Longrightarrow> pred M (\<lambda>x. P x i)) \<Longrightarrow> pred M (\<lambda>x. \<forall>i\<in>X. P x i)" "(\<And>i. i \<in> X \<Longrightarrow> pred M (\<lambda>x. P x i)) \<Longrightarrow> pred M (\<lambda>x. \<exists>i\<in>X. P x i)"
Formal statement is: lemma measure_Diff: assumes finite: "emeasure M A \<noteq> \<infinity>" and measurable: "A \<in> sets M" "B \<in> sets M" "B \<subseteq> A" shows "measure M (A - B) = measure M A - measure M B" Informal statement is: If $A$ and $B$ are measurable sets with $B \subseteq A$ and $A$ has finite measure, then $A - B$ has measure $m(A) - m(B)$.
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro ! This file was ported from Lean 3 source module data.nat.size ! leanprover-community/mathlib commit c3291da49cfa65f0d43b094750541c0731edc932 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Data.Nat.Pow import Mathbin.Data.Nat.Bits /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Lemmas about `size`. -/ namespace Nat /-! ### `shiftl` and `shiftr` -/ #print Nat.shiftl_eq_mul_pow /- theorem shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n | 0 => (Nat.mul_one _).symm | k + 1 => show bit0 (shiftl m k) = m * (2 * 2 ^ k) by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm, mul_comm 2] #align nat.shiftl_eq_mul_pow Nat.shiftl_eq_mul_pow -/ #print Nat.shiftl'_tt_eq_mul_pow /- theorem shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' true m n + 1 = (m + 1) * 2 ^ n | 0 => by simp [shiftl, shiftl', pow_zero, Nat.one_mul] | k + 1 => by change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k) rw [bit1_val] change 2 * (shiftl' tt m k + 1) = _ rw [shiftl'_tt_eq_mul_pow, mul_left_comm, mul_comm 2] #align nat.shiftl'_tt_eq_mul_pow Nat.shiftl'_tt_eq_mul_pow -/ #print Nat.one_shiftl /- theorem one_shiftl (n) : shiftl 1 n = 2 ^ n := (shiftl_eq_mul_pow _ _).trans (Nat.one_mul _) #align nat.one_shiftl Nat.one_shiftl -/ #print Nat.zero_shiftl /- @[simp] theorem zero_shiftl (n) : shiftl 0 n = 0 := (shiftl_eq_mul_pow _ _).trans (Nat.zero_mul _) #align nat.zero_shiftl Nat.zero_shiftl -/ #print Nat.shiftr_eq_div_pow /- theorem shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n | 0 => (Nat.div_one _).symm | k + 1 => (congr_arg div2 (shiftr_eq_div_pow k)).trans <| by rw [div2_val, Nat.div_div_eq_div_mul, mul_comm] <;> rfl #align nat.shiftr_eq_div_pow Nat.shiftr_eq_div_pow -/ #print Nat.zero_shiftr /- @[simp] theorem zero_shiftr (n) : shiftr 0 n = 0 := (shiftr_eq_div_pow _ _).trans (Nat.zero_div _) #align nat.zero_shiftr Nat.zero_shiftr -/ #print Nat.shiftl'_ne_zero_left /- theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n <;> simp [bit_ne_zero, shiftl', *] #align nat.shiftl'_ne_zero_left Nat.shiftl'_ne_zero_left -/ #print Nat.shiftl'_tt_ne_zero /- theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' true m n ≠ 0 | 0, h => absurd rfl h | succ n, _ => Nat.bit1_ne_zero _ #align nat.shiftl'_tt_ne_zero Nat.shiftl'_tt_ne_zero -/ /-! ### `size` -/ #print Nat.size_zero /- @[simp] theorem size_zero : size 0 = 0 := by simp [size] #align nat.size_zero Nat.size_zero -/ #print Nat.size_bit /- @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := by rw [size] conv => lhs rw [binary_rec] simp [h] rw [div2_bit] #align nat.size_bit Nat.size_bit -/ #print Nat.size_bit0 /- @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit false n (Nat.bit0_ne_zero h) #align nat.size_bit0 Nat.size_bit0 -/ #print Nat.size_bit1 /- @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit true n (Nat.bit1_ne_zero n) #align nat.size_bit1 Nat.size_bit1 -/ #print Nat.size_one /- @[simp] theorem size_one : size 1 = 1 := show size (bit1 0) = 1 by rw [size_bit1, size_zero] #align nat.size_one Nat.size_one -/ #print Nat.size_shiftl' /- @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := by induction' n with n IH <;> simp [shiftl'] at h⊢ rw [size_bit h, Nat.add_succ] by_cases s0 : shiftl' b m n = 0 <;> [skip, rw [IH s0]] rw [s0] at h⊢ cases b; · exact absurd rfl h have : shiftl' tt m n + 1 = 1 := congr_arg (· + 1) s0 rw [shiftl'_tt_eq_mul_pow] at this obtain rfl := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩) rw [one_mul] at this obtain rfl : n = 0 := Nat.eq_zero_of_le_zero (le_of_not_gt fun hn => ne_of_gt (pow_lt_pow_of_lt_right (by decide) hn) this) rfl #align nat.size_shiftl' Nat.size_shiftl' -/ #print Nat.size_shiftl /- @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) #align nat.size_shiftl Nat.size_shiftl -/ #print Nat.lt_size_self /- theorem lt_size_self (n : ℕ) : n < 2 ^ size n := by rw [← one_shiftl] have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := by simp apply binary_rec _ _ n · apply this rfl intro b n IH by_cases bit b n = 0 · apply this h rw [size_bit h, shiftl_succ] exact bit_lt_bit0 _ IH #align nat.lt_size_self Nat.lt_size_self -/ #print Nat.size_le /- theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2 ^ n := ⟨fun h => lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right (by decide) h), by rw [← one_shiftl]; revert n apply binary_rec _ _ m · intro n h simp · intro b m IH n h by_cases e : bit b m = 0 · simp [e] rw [size_bit e] cases' n with n · exact e.elim (Nat.eq_zero_of_le_zero (le_of_lt_succ h)) · apply succ_le_succ (IH _) apply lt_imp_lt_of_le_imp_le (fun h' => bit0_le_bit _ h') h⟩ #align nat.size_le Nat.size_le -/ #print Nat.lt_size /- theorem lt_size {m n : ℕ} : m < size n ↔ 2 ^ m ≤ n := by rw [← not_lt, Decidable.iff_not_comm, not_lt, size_le] #align nat.lt_size Nat.lt_size -/ #print Nat.size_pos /- theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw [lt_size] <;> rfl #align nat.size_pos Nat.size_pos -/ #print Nat.size_eq_zero /- theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n <;> simp [pos_iff_ne_zero] at this <;> exact Decidable.not_iff_not.1 this #align nat.size_eq_zero Nat.size_eq_zero -/ #print Nat.size_pow /- theorem size_pow {n : ℕ} : size (2 ^ n) = n + 1 := le_antisymm (size_le.2 <| pow_lt_pow_of_lt_right (by decide) (lt_succ_self _)) (lt_size.2 <| le_rfl) #align nat.size_pow Nat.size_pow -/ #print Nat.size_le_size /- theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 <| lt_of_le_of_lt h (lt_size_self _) #align nat.size_le_size Nat.size_le_size -/ #print Nat.size_eq_bits_len /- theorem size_eq_bits_len (n : ℕ) : n.bits.length = n.size := by induction' n using Nat.binaryRec' with b n h ih; · simp rw [size_bit, bits_append_bit _ _ h] · simp [ih] · simpa [bit_eq_zero_iff] #align nat.size_eq_bits_len Nat.size_eq_bits_len -/ end Nat
#define BOOST_TEST_MODULE "C++ Unit Tests" #include <boost/test/included/unit_test.hpp>
#ifndef PARALLEL_PROCESSING_H_2FVRLMCH #define PARALLEL_PROCESSING_H_2FVRLMCH #include <chrono> #include <gsl/gsl> #include <iomanip> #include <ios> #include <iostream> #include <sens_loc/util/console.h> #include <sens_loc/util/progress_bar_observer.h> #include <taskflow/taskflow.hpp> #include <type_traits> namespace sens_loc::apps { /// Helper function that processes a range of files based on index. /// The boolean function \c f is applied to each function. Error handling /// and reporting is done if \c f returns \c false. /// /// \tparam BoolFunction Apply this functor for each index. /// \param start,end inclusive range of integers for the files /// \param f functor that is applied for each index template <typename BoolFunction> bool parallel_indexed_file_processing(int start, int end, BoolFunction f) noexcept { static_assert(std::is_nothrow_invocable_r_v<bool, BoolFunction, int>, "Functor needs to be noexcept callable and return bool!"); try { if (start > end) std::swap(start, end); int total_tasks = end - start + 1; tf::Executor executor; executor.make_observer<util::progress_bar_observer>(total_tasks); tf::Taskflow tf; bool batch_success = true; int fails = 0; tf.parallel_for( start, end + 1, 1, [&batch_success, &fails, &f](int idx) { const bool success = f(idx); if (!success) { auto s = synced(); fails++; std::cerr << util::err{}; std::cerr << "Could not process index \"" << rang::style::bold << idx << "\"" << rang::style::reset << "!" << std::endl; batch_success = false; } }); const auto before = std::chrono::steady_clock::now(); executor.run(tf).wait(); const auto after = std::chrono::steady_clock::now(); const auto dur_deci_seconds = std::chrono::duration_cast<std::chrono::duration<long, std::centi>>( after - before); std::cout << std::endl; Ensures(fails >= 0); using namespace std::chrono; { auto s = synced(); std::cerr << util::info{}; std::cerr << "Processing " << rang::style::bold << std::abs(end - start) + 1 - fails << rang::style::reset << " images took " << rang::style::bold << std::fixed << std::setprecision(2) << (dur_deci_seconds.count() / 100.) << rang::style::reset << " seconds!\n"; } if (fails > 0) { auto s = synced(); std::cerr << util::warn{} << "Encountered " << rang::style::bold << fails << rang::style::reset << " problematic files!\n"; } return batch_success; } catch (...) { auto s = synced(); std::cerr << util::err{} << "System error in batch processing!\n"; return false; } } } // namespace sens_loc::apps #endif /* end of include guard: PARALLEL_PROCESSING_H_2FVRLMCH */
C C $Id: gtnumb.f,v 1.4 2008-07-27 00:17:21 haley Exp $ C C Copyright (C) 2000 C University Corporation for Atmospheric Research C All Rights Reserved C C The use of this Software is governed by a License Agreement. C C C============================================================ C GTNUMB C============================================================ SUBROUTINE GTNUMB (IDPC,N,II,NUM) C C C EXTRACTS AN OCTAL NUMBER NUM FROM CHARACTER STRING IDPC. C C ON ENTRY: C IDPC - A CHARACTER STRING C N - THE NUMBER OF CHARACTERS IN THE CHARACTER STRING IDPC C II - A NUMBER REPRESENTING A POINTER TO THE II-TH CHARACTER IN THE C CHARACTER STRING IDPC C THE II-TH CHARACTER HAS TO BE A DIGIT BETWEEN 0 AND 7 C NUM - CAN HAVE ANY VALUE C C ON EXIT: C IDPC - UNCHANGED C N - UNCHANGED C NUM - 1) IF THE II-TH CHARACTER IN IDPC IS THE FIRST CHARACTER C IN A SUBSTRING REPRESENTING AN UNSIGNED INTEGER, THEN THE C VALUE OF THIS UNSIGNED INTEGER TAKEN TO THE BASE 8 C (NOTICE THE DIFFERENCE FROM SUBROUTINE GTNUM) C 2) OTHERWISE 0 C II - 1)IF AN UNSIGNED INTEGER WAS FOUND THEN II REPRESENTS A POINT C TO THE CHARACTER SUCCEEDING THE LAST CHARACTER OF THE C UNSIGNED INTEGER C 2) OTHERWISE UNCHANGED C C CALLS C GTDGTS C C CALLED BY C PWRITX C C C ASSUMPTION C THE REPRESENTATION OF DIGITS IN THE MACHINE IS ORDERED AND COMPACT. C C CHARACTER IDPC*(*) C C C ********************************************************************** C C LOCAL VARIABLES C C ID - A character representing the base of the number to be extracted C C ********************************************************************** C C C THE BASE OF THE NUMBER TO BE EXTRACTED. C CHARACTER*1 ID ID = '8' C CALL GTDGTS(IDPC,II,N,ID,NUM) C Convert digit string beginning at II in IDPC C to an integer, base ID. C RETURN END
filter : (p : a -> Bool) -> List a -> List a filter p [] = [] filter p (x :: xs) with (p x) _ | True = x :: filter p xs _ | False = filter p xs filterFilter : (p : a -> Bool) -> (xs : List a) -> filter p (filter p xs) === filter p xs filterFilter p [] = Refl filterFilter p (x :: xs) with (p x) proof eq _ | False = filterFilter p xs _ | True with (p x) _ | True = cong (x ::) (filterFilter p xs)
The large sentiment charm goes with our wide cuff leather bracelets. The charm easily hooks on the the leather bracelet's lobster hooks. The 2 1/4" X 1 1/2" lead free cast metal charm is inscribed with: Tell me, what it is you plan to do with this wild and precious life?
### Computing for Mathematics - Mock individual coursework This jupyter notebook contains questions that will resemble the questions in your individual coursework. **Important** Do not delete the cells containing: ``` ### BEGIN SOLUTION ### END SOLUTION ``` write your solution attempts in those cells. **If you would like to** submit this notebook: - Change the name of the notebook from `main` to: `<student_number>`. For example, if your student number is `c1234567` then change the name of the notebook to `c1234567`. - Write all your solution attempts in the correct locations; - Save the notebook (`File>Save As`); - Follow the instructions given in class/email to submit. #### Question 1 Output the evaluation of the following expressions exactly. a. \\(\frac{(9a^2bc^4) ^ {\frac{1}{2}}}{6ab^{\frac{3}{2}}c}\\) ```python ### BEGIN SOLUTION import sympy as sym a, b, c = sym.Symbol("a"), sym.Symbol("b"), sym.Symbol("c") sym.expand((9 * a ** 2 * b * c ** 4) ** (sym.S(1) / 2) / (6 * a * b ** (sym.S(3) / 2) * c)) ### END SOLUTION ``` $\displaystyle \frac{\sqrt{a^{2} b c^{4}}}{2 a b^{\frac{3}{2}} c}$ b. \\((2 ^ {\frac{1}{2}} + 2) ^ 2 - 2 ^ {\frac{5}{2}}\\) ```python ### BEGIN SOLUTION sym.expand((sym.S(2) ** (sym.S(1) / 2) + 2) ** 2 - 2 ** (sym.S(5) / 2)) ### END SOLUTION ``` $\displaystyle 6$ 3. \\((\frac{1}{8}) ^ {\frac{4}{3}}\\) ```python ### BEGIN SOLUTION (sym.S(1) / 8) ** (sym.S(4) / 3) ### END SOLUTION ``` $\displaystyle \frac{1}{16}$ ### Question 2 Write a function `expand` that takes a given mathematical expression and returns the expanded expression. ```python def expand(expression): ### BEGIN SOLUTION """ Take a symbolic expression and expands it. """ return sym.expand(expression) ### END SOLUTION ``` ### Question 3 The matrix \\(D\\) is given by \\(D = \begin{pmatrix} 1& 2 & a\\ 3 & 1 & 0\\ 1 & 1 & 1\end{pmatrix}\\) where \\(a\ne 2\\). a. Create a variable `D` which has value the matrix \\(D\\). ```python ### BEGIN SOLUTION a = sym.Symbol("a") D = sym.Matrix([[1, 2, a], [3, 1, 0], [1, 1, 1]]) ### END SOLUTION ``` b. Create a variable `D_inv` with value the inverse of \\(D\\). ```python ### BEGIN SOLUTION D_inv = D.inv() ### END SOLUTION ``` c. Using `D_inv` **output** the solution of the following system of equations: \\[ \begin{array}{r} x + 2y + 4z = 3\\ 3x + y = 4\\ x + y + z = 1\\ \end{array} \\] ```python ### BEGIN SOLUTION b = sym.Matrix([[3], [4], [1]]) sym.simplify(D.inv() @ b).subs({a: 4}) ### END SOLUTION ``` $\displaystyle \left[\begin{matrix}\frac{7}{3}\\-3\\\frac{5}{3}\end{matrix}\right]$ ### Question 4 During a game of frisbee between a handler and their dog the handler chooses to randomly select if they throw using a backhand or a forehand: 25% of the time they will throw a backhand. Because of the way their dog chooses to approach a flying frisbee they catch it with the following probabilities: - 80% of the time when it is thrown using a backhand - 90% of the time when it is thrown using a forehand a. Write a function `sample_experiment()` that simulates a given throw and returns the throw type (as a string with value `"backhand"` or `"forehand"`) and whether it was caught (as a boolean: either `True` or `False`). ```python import random def sample_experiment(): """ Returns the throw type and whether it was caught """ ### BEGIN SOLUTION if random.random() < .25: throw = "backhand" probability_of_catch = .8 else: throw = "forehand" probability_of_catch = .9 caught = random.random() < probability_of_catch ### END SOLUTION return throw, caught ``` b. Using 1,000,000 samples create a variable `probability_of_catch` which has value an estimate for the probability of the frisbee being caught. ```python ### BEGIN SOLUTION number_of_repetitions = 1_000_000 random.seed(0) samples = [sample_experiment() for repetition in range(number_of_repetitions)] probability_of_catch = sum(catch is True for throw, catch in samples) / number_of_repetitions ### END SOLUTION ``` c. Using the above, create a variable `probability_of_forehand_given_drop` which has value an estimate for the probability of the frisbee being thrown with a forehand given that it was not caught. ```python ### BEGIN SOLUTION samples_with_drop = [(throw, catch) for throw, catch in samples if catch is False] number_of_drops = len(samples_with_drop) probability_of_forehand_given_drop = sum(throw == "forehand" for throw, catch in samples_with_drop) / number_of_drops ### END SOLUTION ```
## %PREDICTMD_GENERATED_BY% import PredictMDExtra PredictMDExtra.import_all() import PredictMD PredictMD.import_all() # PREDICTMD IF INCLUDE TEST STATEMENTS import CSVFiles import DataFrames import FileIO import RDatasets import Random import Test # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS # PREDICTMD IF INCLUDE TEST STATEMENTS logger = Base.CoreLogging.current_logger_for_env(Base.CoreLogging.Debug, Symbol(splitext(basename(something(@__FILE__, "nothing")))[1]), something(@__MODULE__, "nothing")) if isnothing(logger) logger_stream = devnull else logger_stream = logger.stream end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ### Begin project-specific settings DIRECTORY_CONTAINING_THIS_FILE = @__DIR__ PROJECT_DIRECTORY = dirname( joinpath(splitpath(DIRECTORY_CONTAINING_THIS_FILE)...) ) PROJECT_OUTPUT_DIRECTORY = joinpath( PROJECT_DIRECTORY, "output", ) mkpath(PROJECT_OUTPUT_DIRECTORY) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "data")) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "models")) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "plots")) # PREDICTMD IF INCLUDE TEST STATEMENTS @debug("PROJECT_OUTPUT_DIRECTORY: ", PROJECT_OUTPUT_DIRECTORY,) if PredictMD.is_travis_ci() PredictMD.cache_to_path!( ; from = ["cpu_examples", "boston_housing", "output",], to = [PROJECT_OUTPUT_DIRECTORY], ) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ### End project-specific settings ### Begin Knet neural network regression code Random.seed!(999) trainingandtuning_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "trainingandtuning_features_df.csv", ) trainingandtuning_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "trainingandtuning_labels_df.csv", ) testing_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "testing_features_df.csv", ) testing_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "testing_labels_df.csv", ) training_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "training_features_df.csv", ) training_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "training_labels_df.csv", ) tuning_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "tuning_features_df.csv", ) tuning_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "tuning_labels_df.csv", ) trainingandtuning_features_df = DataFrames.DataFrame( FileIO.load( trainingandtuning_features_df_filename; type_detect_rows = 100, ) ) trainingandtuning_labels_df = DataFrames.DataFrame( FileIO.load( trainingandtuning_labels_df_filename; type_detect_rows = 100, ) ) testing_features_df = DataFrames.DataFrame( FileIO.load( testing_features_df_filename; type_detect_rows = 100, ) ) testing_labels_df = DataFrames.DataFrame( FileIO.load( testing_labels_df_filename; type_detect_rows = 100, ) ) training_features_df = DataFrames.DataFrame( FileIO.load( training_features_df_filename; type_detect_rows = 100, ) ) training_labels_df = DataFrames.DataFrame( FileIO.load( training_labels_df_filename; type_detect_rows = 100, ) ) tuning_features_df = DataFrames.DataFrame( FileIO.load( tuning_features_df_filename; type_detect_rows = 100, ) ) tuning_labels_df = DataFrames.DataFrame( FileIO.load( tuning_labels_df_filename; type_detect_rows = 100, ) ) categorical_feature_names_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "categorical_feature_names.jld2", ) continuous_feature_names_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "continuous_feature_names.jld2", ) categorical_feature_names = FileIO.load( categorical_feature_names_filename, "categorical_feature_names", ) continuous_feature_names = FileIO.load( continuous_feature_names_filename, "continuous_feature_names", ) feature_names = vcat(categorical_feature_names, continuous_feature_names) single_label_name = :MedV continuous_label_names = Symbol[single_label_name] categorical_label_names = Symbol[] label_names = vcat(categorical_label_names, continuous_label_names) knet_mlp_predict_function_source = """ function knetmlp_predict( w, x0::AbstractArray, ) x1 = Knet.relu.( w[1]*x0 .+ w[2] ) x2 = w[3]*x1 .+ w[4] return x2 end """ knet_mlp_loss_function_source = """ function knetmlp_loss( predict_function::Function, modelweights, x::AbstractArray, ytrue::AbstractArray; L1::Real = Float64(0), L2::Real = Float64(0), ) loss = Statistics.mean( abs2, ytrue - predict_function( modelweights, x, ), ) if L1 != 0 loss += L1 * sum(sum(abs, w_i) for w_i in modelweights[1:2:end]) end if L2 != 0 loss += L2 * sum(sum(abs2, w_i) for w_i in modelweights[1:2:end]) end return loss end """ feature_contrasts = PredictMD.generate_feature_contrasts(training_features_df, feature_names) knetmlp_modelweights = Any[ Float64.( 0.1f0*randn(Float64,10,feature_contrasts.num_array_columns_without_intercept) ), Float64.( fill(Float64(0),10,1) ), Float64.( 0.1f0*randn(Float64,1,10) ), Float64.( fill(Float64(0),1,1), ), ] knetmlp_losshyperparameters = Dict() knetmlp_losshyperparameters[:L1] = Float64(0.0) knetmlp_losshyperparameters[:L2] = Float64(0.0) knetmlp_optimizationalgorithm = :Adam knetmlp_optimizerhyperparameters = Dict() knetmlp_minibatchsize = 48 knet_mlp_regression = PredictMD.single_labeldataframeknetregression( feature_names, single_label_name; package = :Knet, name = "Knet MLP", predict_function_source = knet_mlp_predict_function_source, loss_function_source = knet_mlp_loss_function_source, losshyperparameters = knetmlp_losshyperparameters, optimizationalgorithm = knetmlp_optimizationalgorithm, optimizerhyperparameters = knetmlp_optimizerhyperparameters, minibatchsize = knetmlp_minibatchsize, modelweights = knetmlp_modelweights, maxepochs = 100, printlosseverynepochs = 10, feature_contrasts = feature_contrasts, ) PredictMD.parse_functions!(knet_mlp_regression) PredictMD.fit!( knet_mlp_regression, training_features_df, training_labels_df, tuning_features_df, tuning_labels_df, ) PredictMD.set_max_epochs!(knet_mlp_regression, 200) PredictMD.fit!( knet_mlp_regression, training_features_df, training_labels_df, tuning_features_df, tuning_labels_df, ) # PREDICTMD IF INCLUDE TEST STATEMENTS test_knet_mlp_regression = PredictMD.single_labeldataframeknetregression( feature_names, single_label_name; package = :Knet, name = "Knet MLP", predict_function_source = knet_mlp_predict_function_source, loss_function_source = knet_mlp_loss_function_source, losshyperparameters = knetmlp_losshyperparameters, optimizationalgorithm = knetmlp_optimizationalgorithm, optimizerhyperparameters = knetmlp_optimizerhyperparameters, minibatchsize = knetmlp_minibatchsize, modelweights = knetmlp_modelweights, maxepochs = 5, printlosseverynepochs = 1, feature_contrasts = feature_contrasts, ) # PredictMD.fit!( # knet_mlp_regression, # training_features_df, # training_labels_df, # nothing, # nothing, # ) test_knet_mlp_regression = PredictMD.single_labeldataframeknetregression( feature_names, single_label_name; package = :Knet, name = "Knet MLP", predict_function_source = knet_mlp_predict_function_source, loss_function_source = knet_mlp_loss_function_source, losshyperparameters = knetmlp_losshyperparameters, optimizationalgorithm = knetmlp_optimizationalgorithm, optimizerhyperparameters = knetmlp_optimizerhyperparameters, minibatchsize = knetmlp_minibatchsize, modelweights = knetmlp_modelweights, maxepochs = 5, printlosseverynepochs = 1, feature_contrasts = feature_contrasts, ) # PredictMD.fit!( # knet_mlp_regression, # training_features_df, # training_labels_df, # nothing, # tuning_labels_df, # ) test_knet_mlp_regression = PredictMD.single_labeldataframeknetregression( feature_names, single_label_name; package = :Knet, name = "Knet MLP", predict_function_source = knet_mlp_predict_function_source, loss_function_source = knet_mlp_loss_function_source, losshyperparameters = knetmlp_losshyperparameters, optimizationalgorithm = knetmlp_optimizationalgorithm, optimizerhyperparameters = knetmlp_optimizerhyperparameters, minibatchsize = knetmlp_minibatchsize, modelweights = knetmlp_modelweights, maxepochs = 5, printlosseverynepochs = 1, feature_contrasts = feature_contrasts, ) # PredictMD.fit!( # knet_mlp_regression, # training_features_df, # training_labels_df, # tuning_features_df, # nothing, # ) PredictMD.get_underlying(test_knet_mlp_regression) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS knet_learningcurve_lossvsepoch = PredictMD.plotlearningcurve( knet_mlp_regression, :loss_vs_epoch; ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "knet_learningcurve_lossvsepoch", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, knet_learningcurve_lossvsepoch) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(knet_learningcurve_lossvsepoch) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "knet_learningcurve_lossvsepoch.pdf", ), knet_learningcurve_lossvsepoch, ) knet_learningcurve_lossvsepoch_skip10epochs = PredictMD.plotlearningcurve( knet_mlp_regression, :loss_vs_epoch; startat = 10, endat = :end, ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "knet_learningcurve_lossvsepoch_skip10epochs", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, knet_learningcurve_lossvsepoch_skip10epochs) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(knet_learningcurve_lossvsepoch_skip10epochs) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "knet_learningcurve_lossvsepoch_skip10epochs.pdf", ), knet_learningcurve_lossvsepoch_skip10epochs, ) knet_learningcurve_lossvsiteration = PredictMD.plotlearningcurve( knet_mlp_regression, :loss_vs_iteration; window = 50, sampleevery = 10, ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "knet_learningcurve_lossvsiteration", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, knet_learningcurve_lossvsiteration) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(knet_learningcurve_lossvsiteration) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "knet_learningcurve_lossvsiteration.pdf", ), knet_learningcurve_lossvsiteration, ) knet_learningcurve_lossvsiteration_skip100iterations = PredictMD.plotlearningcurve( knet_mlp_regression, :loss_vs_iteration; window = 50, sampleevery = 10, startat = 100, endat = :end, ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "knet_learningcurve_lossvsiteration_skip100iterations", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, knet_learningcurve_lossvsiteration_skip100iterations) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(knet_learningcurve_lossvsiteration_skip100iterations) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "knet_learningcurve_lossvsiteration_skip100iterations.pdf", ), knet_learningcurve_lossvsiteration_skip100iterations, ) knet_mlp_regression_plot_training = PredictMD.plotsinglelabelregressiontrueversuspredicted( knet_mlp_regression, training_features_df, training_labels_df, single_label_name, ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "knet_mlp_regression_plot_training", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, knet_mlp_regression_plot_training) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(knet_mlp_regression_plot_training) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "knet_mlp_regression_plot_training.pdf", ), knet_mlp_regression_plot_training, ) knet_mlp_regression_plot_testing = PredictMD.plotsinglelabelregressiontrueversuspredicted( knet_mlp_regression, testing_features_df, testing_labels_df, single_label_name, ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "knet_mlp_regression_plot_testing", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, knet_mlp_regression_plot_testing) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(knet_mlp_regression_plot_testing) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "knet_mlp_regression_plot_testing.pdf", ), knet_mlp_regression_plot_testing, ) show( logger_stream, PredictMD.singlelabelregressionmetrics( knet_mlp_regression, training_features_df, training_labels_df, single_label_name, ); allrows = true, allcols = true, splitcols = false, ) show( logger_stream, PredictMD.singlelabelregressionmetrics( knet_mlp_regression, testing_features_df, testing_labels_df, single_label_name, ); allrows = true, allcols = true, splitcols = false, ) knet_mlp_regression_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "knet_mlp_regression.jld2", ) PredictMD.save_model(knet_mlp_regression_filename, knet_mlp_regression) # PREDICTMD IF INCLUDE TEST STATEMENTS knet_mlp_regression = nothing Test.@test isnothing(knet_mlp_regression) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ### End Knet neural network regression code # PREDICTMD IF INCLUDE TEST STATEMENTS if PredictMD.is_travis_ci() PredictMD.path_to_cache!( ; to = ["cpu_examples", "boston_housing", "output",], from = [PROJECT_OUTPUT_DIRECTORY], ) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ## %PREDICTMD_GENERATED_BY%
State Before: α : Type ?u.19210 M₀ : Type ?u.19213 G₀ : Type u_1 M₀' : Type ?u.19219 G₀' : Type ?u.19222 F : Type ?u.19225 F' : Type ?u.19228 inst✝ : GroupWithZero G₀ a✝ b c g h✝ x : G₀ h : b ≠ 0 a : G₀ ⊢ a * (b⁻¹ * b) = a State After: no goals Tactic: simp [h]
[STATEMENT] lemma wordinterval_CIDR_split1_snd: "wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow> u = wordinterval_setminus r (prefix_to_wordinterval s)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. wordinterval_CIDR_split1 r = (Some s, u) \<Longrightarrow> u = wordinterval_setminus r (prefix_to_wordinterval s) [PROOF STEP] unfolding wordinterval_CIDR_split1_def Let_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (case wordinterval_lowest_element r of None \<Rightarrow> (None, r) | Some a \<Rightarrow> case largest_contained_prefix a r of None \<Rightarrow> (None, r) | Some m \<Rightarrow> (Some m, wordinterval_setminus r (prefix_to_wordinterval m))) = (Some s, u) \<Longrightarrow> u = wordinterval_setminus r (prefix_to_wordinterval s) [PROOF STEP] by(clarsimp split: option.splits)
module Test import API
```python import sys from __future__ import division ``` ```python import numpy as np from phasor.utilities.ipynb.displays import * #from YALL.utilities.tabulate import tabulate import declarative from declarative.bunch import ( DeepBunch ) import phasor.math.dispatched as dmath #import phasor.math.dispatch_sympy ``` Populating the interactive namespace from numpy and matplotlib ```python import phasor.utilities.version as version print(version.foundations_version()) from phasor.utilities.np import logspaced from phasor.utilities.ipynb.sympy import * from phasor import optics from phasor import base from phasor import signals from phasor import system from phasor import readouts from phasor import mechanical ``` b'2017-09-22 09:45:51 -0400 (a76310c5d4476904171a3f1b18117db454719432)' Sympy version: 1.0 ```python d = sympy.var('d') N = sympy.var('N') l = sympy.var('l') A = sympy.var('A') s = sympy.var('s') k = sympy.var('k') F = sympy.var('F') epsilon = sympy.var('epsilon') epsilon_0 = sympy.var('epsilon_0') d_l = sympy.var('l_delta') V = sympy.var('V') I = sympy.var('I') C = sympy.var('C') Z_e = sympy.var('Z_e', real = True) Z_m = sympy.var('Z_m', real = True) k_e = sympy.sqrt(1/sympy.re(Z_e)) k_m = sympy.sqrt(1/sympy.im(Z_m)) k_e = sympy.var('k_e', real = True) k_m = sympy.var('k_m', real = True) k_e = sympy.sympify(1) k_m = sympy.sympify(1) expr1 = d * F - I/s + C * V display(expr1) expr2 = -d_l * k + F + k * d * V display(expr2) rel = sympy.Matrix([[C, -1/s, d, 0],[d*k, 0, 1, -k]]) var = sympy.Matrix([V, I, F, d_l]) rel * var ``` ```python trans = sympy.Matrix([ [k_e/2, k_e/2 * Z_e , 0, 0], [k_e/2, -k_e/2 * Z_e.conjugate(), 0, 0], [0, 0, k_m/2, k_m/2 * Z_m ], [0, 0, k_m/2, -k_m/2 * Z_m.conjugate()], ]) trans * var ``` ```python rel_ab = rel * trans**-1 rel_a = rel_ab[:,::2] rel_b = rel_ab[:,1::2] ``` ```python rel_b ``` ```python rel_atob = -rel_b**-1 * rel_a rel_atob.simplify() rel_atob ``` ```python from sympy.utilities.lambdify import lambdastr ``` ```python e = rel_atob[1,1] def pyval(expr): sym = list(expr.free_symbols) return lambdastr(sym, expr).split(':')[1].strip() ``` ```python pyval(rel_atob[0,0]) ``` '((C*Z_e*Z_m*s + C*Z_e*k*s - Z_e*Z_m*d**2*k*s - Z_m - k)/(-C*Z_e*Z_m*s - C*Z_e*k*s + Z_e*Z_m*d**2*k*s - Z_m - k))' ```python pyval(rel_atob[1,1]) ``` '((Z_e*Z_m*d**2*k*s - (Z_m - k)*(C*Z_e*s + 1))/(-Z_e*Z_m*d**2*k*s + Z_m*(C*Z_e*s + 1) + k*(C*Z_e*s + 1)))' ```python pyval(rel_atob[0,1]) ``` '(2*Z_e*d*k*s/(-C*Z_e*Z_m*s - C*Z_e*k*s + Z_e*Z_m*d**2*k*s - Z_m - k))' ```python pyval(rel_atob[1,0]) ``` '(2*Z_m*d*k/(-C*Z_e*Z_m*s - C*Z_e*k*s + Z_e*Z_m*d**2*k*s - Z_m - k))' ```python ```
%!TEX root = ../../thesis.tex %!TEX enableSynctex = true %******************************************************************************* %****************************** Third Chapter ********************************** %******************************************************************************* % **************************** Define Graphics Path ************************** \ifpdf{} \graphicspath{{Chapters/flopt/Figs/Raster/}{Chapters/flopt/Figs/PDF/}{Chapters/flopt/Figs/}} \else \graphicspath{{Chapters/flopt/Figs/Vector/}{Chapters/flopt/Figs/}} \fi \makeatletter \renewcommand*\env@matrix[1][*\c@MaxMatrixCols c]{% \hskip -\arraycolsep \let\@ifnextchar\new@ifnextchar \array{#1}} \makeatother \chapter{Frame localisation optical projection tomography}\label{chapter:flopt} % \epigraph{\emph{Pascale Sauvage}}{--- Pablo Vallejo} In the previous chapters, volumetric imaging was achieved using \gls{wide-field} imaging and a relative scanning motion between the system's focal plane and the sample. Volumetric imaging can also be achieved by rotating a sample and %reconstructing tomographically. tomographically reconstructing the \gls{3D} distribution of a signal (scattering, absorption or luminosity) within the specimen. %Orthogonal imaging schema can be replaced with pass through imaging provide samples are sufficiently transparent. %Instead of scanning these samples laterally one can rotate their sample and reconstruct a full three dimensional image. %As tomographic technology has been shrunk to the millimeter scale, errors induced by hardware become apparent. Accurate %reconstructions of volumes rely on tomographic reconstruction relies heavily on precision movement and rotation. %This chapter addresses a key downside in traditional approaches to performing full three dimensional reconstructions tomographically. Here an algorithm will be presented that relies exclusively on multiple (4+) tracked fiducial beads to enable accurate reconstruction even with systematic mechanical drift. It will be demonstrated on ground truth simulated testcard image data with motion errors compounded onto the tomographic rotation. These motion errors will include systematic mechanical drift, giving a spiral path; and angular drift giving precession. The projective mathematics introduced in Chapter~\ref{chapter:homography} is part of a field of mathematics used in computer vision to to localise (in \gls{3D}) points in space as projected onto multiple view points. The algorithm presented in this chapter will use an extension of this projective mathematics to reconstruct \gls{OPT} volumes from the set of rotational projections. Considerations were made to combine \gls{OPT} and \gls{light-sheet} imaging within the system constructed in Chapter~\ref{chapter:design}, though this was never realised during this thesis. \emph{It should be noted that, due to conventions within the field of computer vision, all lab frame or \glslink{world point}{world coordinates} will be represented as capital letters (ex.~\gls{X}, \gls{X_c}) and image frame coordinates will be represented in image plane coordinates (ex.~\gls{x}) in this chapter, shown in \figurename~\ref{fig:coordinate_system_flopt}.} \pagebreak \section{Rotational computer tomography in microscopy} \begin{figure} \centering \begin{subfigure}[t]{0.48\textwidth} \centering \includegraphics{coordinate_system} \caption[Coordinate system]{Coordinate system used in this chapter describing a camera with an associated \gls{image plane} one focal distance \(f\) away, imaging an object at point \(\gls{X}\). }\label{fig:coordinate_system_flopt} \end{subfigure}\hfill \begin{subfigure}[t]{0.48\textwidth} \centering \includegraphics{Chapters/flopt/Figs/PDF/OPT_digram} \caption[Principle of OPT]{From an angle \(\theta \), an object \(f(X,Y)\) and its projection \(P_\theta(t)\) are known.}\label{fig:OPT_digram} %{Principle of \gls{OPT}, a respective rotation between the sample and the detector illumination pair is iterated. % The volumetric image is later reconstructed from the set of detections (1/2D).} \end{subfigure} \caption[Coordinates and \gls{OPT}]{\gls{X_c} = \((X_c,Y_c,Z_c)\) is the camera-centered coordinate point in \gls{3D} space. \gls{X} = \((X,Y,Z)\) is the world coordinate point in \gls{3D} space. \gls{p} = \((x,y,f)\) is the ray vector to point of \gls{image plane}. \gls{x} = \((x,y)\) is the \gls{image plane} coordinates. \gls{w} = \((u,v)\) is the pixel coordinates (not shown) corresponding to the point \gls{x}. The optical axis travels along the \(Z_c\) axis through the \gls{image plane}.} % \label{fig:aa} \end{figure} %Well establishjed %Three-dimensional imaging of anatomy in thick biological samples provides valuable data for developmental biology studies. %Tomographic techniques that generate 3D reconstructions from 2D images such as computed tomography (CT) and magnetic resonance imaging (MRI) are essential in medical applications to visualize morphology in large tissues and organs. %CT and especially micro-CT can achieve micron-scale resolution using certain contrast agents, however the high doses of radiation used make this unsuitable for repeated experiments on a biological sample. %Micro-MRI can also achieve resolution in the micron scale, however the cost and size of MRI instruments can be prohibitive for many applications[21]. %Furthermore, neither of these techniques can exploit the plethora of information that can be extracted through fluorescence microscopy. Sharpe~\emph{et.al} proposed \gls{OPT} in 2002~\cite{sharpeOpticalProjectionTomography2002} using visible light to image transparent or translucent mesoscopic samples, with micrometer resolution. \gls{OPT} addresses a scale gap between photographic techniques (for samples typically larger than \SI{10}{\milli\meter}), and light microscopy techniques (samples smaller than \SI{1}{\milli\meter}) to image biological samples in the \SIrange{1}{10}{\milli\meter} regime. %Optical Projection Tomography was first proposed by Sharpe in 2002 [30]; it uses visible light to image and create volumetric data of transparent (naturally or artificially) mesoscopic objects (1 - 10 mm) at micron-level resolution. \gls{OPT} is based on computerised tomography techniques~\cite{kakPrinciplesComputerizedTomographic2001} in which a set of projections of a specimen are imaged as the specimen travels through a full rotation. Algorithms exist to then transform this set of images into a %n \(xyz \) image stack. \gls{3D} image stack in Cartesian (\(X,Y,Z\)) coordinates. %A cross-sectional stack of slices from the original object is reconstructed using a back-projection algorithm from the projection images. \gls{OPT} is non-invasive optically but may require specialist invasive preparation for its samples. There are two imaging modalities for \gls{OPT}, \gls{eOPT} and \gls{tOPT}. In \gls{eOPT}, a fluorescent sample is excited using an illumination source off axis to the detection, similar to \gls{light-sheet} but the entire \gls{depth of field} of the detection of objective is illuminated. % without the excitation being shaped into a sheet. Scattered illumination photons are rejected at the detector using an appropriate filter. In tOPT, a white-light source with a diffuser and a collimator is placed along the optical axis to provide near-collimated, uniform illumination onto the sample for transmission to a detector opposite (see \figurename~\ref{fig:OPT_digram}). Each \gls{photosite} at the detector corresponds to a ray that has passed through the sample and been attenuated by the sample. The \gls{eOPT} and \gls{tOPT} modes can work in unison to provide contextual information, with the transmission images indicating overall structure (optical density of absorption or scattering) which can be supplemented by the fluorescent signal from a label of interest. % % \begin{figure} % \centering % \includegraphics{Chapters/flopt/Figs/PDF/OPT_digram} % \caption[Principle of OPT]{Principle of \gls{OPT}, a respective rotation between the sample and the detector illumination pair is iterated. % The volumetric image is later reconstructed from the set of detections (1/2D).} % \label{fig:OPT_digram} % \end{figure} \subsection{Reconstruction} As the sample is rotated each detector pixel collects an intensity \(I(\theta) = I_{0}e^{-k(\theta)}\) at discrete (\(n\)) angles through a full rotation of the sample; where \(I_{0}\) is the unattenuated radiation intensity from the source to the detector, \(k\) is the attenuation caused by the sample along a detected ray, and \(I(\theta)\) is the measured intensity, see \figurename~\ref{fig:OPT_digram}. Rays from the sample to the detector approximate straight lines, and so the the rays reaching the detector with a line integrals. A projection is then the resulting intensity profile at the detector for a rotation angle, and the integral transform that results in \(P_\theta(v)\) % \(f(I_i,\theta_n) \) is the \gls{Radon transform}. % This is defined mathematically as: \begin{align} \intertext{The equation of a set of parallel rays from a source passing through the specimen to a point \(v\) along the detector is:} &X\cos(\theta) + Y\sin(\theta) - v = 0 \\ \intertext{Projecting many such rays through a sample with structure \(f(X,Y)\) gives:} P_\theta(v) = &\int_{\infty}^{\infty} \int_{\infty}^{\infty} f(X,Y)\delta (x\cos(\theta)+y \sin(\theta)-v)dX dY \end{align} % \begin{figure} % \centering % \includegraphics{coordinate_system} % \caption{Coordinate system} % \label{fig:coordinate_system_flopt} % \end{figure} Where \(P_\theta(v)\) is the \gls{Radon transform} of \(f(X,Y)\) which represents the contrast image of \gls{2D} slice of the specimen. The \gls{Radon transform} of an image produces a \gls{sinugram} as in \figurename~\ref{fig:rawinputs} \begin{figure} \centering \hspace*{\fill} \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.75\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/rawinput_colour}}; \node[below=of img] {\(X\)}; \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption{Ground truth image for \gls{OPT} simulations, Lena (\(f(X, Y)\)).}\label{fig:raw_input} \end{subfigure}\hfill \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/sinugram_stretch}}; \node[below=of img] {\(v\)\vphantom{\(X\)}}; \node[left=of img,rotate=90,yshift=0.2cm] {\(\theta\)}; \end{tikzpicture} \caption{Image of Lena (\figurename~\ref{fig:raw_input}) after rotation and projection in 2D, giving the \gls{sinugram} (\(P_{\theta}(v)\)). }\label{fig:sinugram_stretch} \end{subfigure} \hspace*{\fill} \caption{Reference images for \gls{OPT} reconstruction.}\label{fig:rawinputs} \end{figure} % A parallel projection is then just the combination of line integrals \(f(I) \) for a constant. % for a constant. An inverse \gls{Radon transform} is used to recover the original object from the projection data; which is achieved by taking the \gls{Fourier transform} of each projection measurement, then reordering the information from the sample into the respective position in Fourier space. This is valid due to the Fourier Slice theorem~\cite{bracewellStripIntegrationRadio1956} (see Appendix~\ref{appendix:fourierslice} for a derivation), which states that the \gls{Fourier transform} of a parallel projection is equivalent to a 2D slice of the Fourier transform of the original sample. %A high pass filter such as a ramp filter is commonly used to counter the blurring caused by this oversampling. % \gls{FBP} can be thought of as smearing the projection data across the image plane, and is expressed in equation form as: \begin{align} f_{\text{fpb}}(X,Y) = \int_{0}^{\pi} Q_\theta (X\cos(\theta)+Y\sin(\theta),\theta)dXdY \end{align} Where \(Q_\theta \) is the filtered projection data, and \(f_{\text{fpb}}(X,Y)\) is the back-projected image. A spatial filtering step is applied during back-projection to avoid spatial frequency oversampling during the object’s rotation (see \figurename~\ref{fig:iradon_filter}) a high pass filter is commonly used to compensate for the perceived blurring. The blurring arises as \(Q_\theta \) is back-projected (smeared) across the \gls{image plane} for each angle of reconstruction; which means that not only does the back-projection contribute at the line it is intended to (along line \(C\) in \figurename~\ref{fig:coordinate_system_flopt}), but all other points along the back-projecting ray. % The blurring occurs as \(Q_\theta\) makes the same contribution to the reconstruction for each angle % will make the same contribution to the reconstruction at all of these points. Therefore, one could say that in the reconstruction process each filtered projection, Qe, is smeared back, or backprojected, over the image plane. \subsubsection{Aim} The \gls{Radon transform} relies heavily on the assumption of circular motion with constant angular steps about a vertical axis. This chapter presents an improved reconstruction method which explains, some of the techniques used in stereoscopic imaging to register back projections rather than relying on line integrals. The algorithm proposed here is therefore robust to mechanical drifts across acquisitions as well as inconsistent angular steps \section{Stereoscopic imaging} %\subsection{Projective geometry} %Camera imaging is governed by projective geometry %Parallel lines project onto a camera will have a vanishing point at the horizon. %\subsection{Camera projections} %\todo{Camera projections \ lecture notes 3} Imaging scenes in stereo allows for the triangulation of individual features in three dimensional space (know as \gls{world point}s) when the features or fiducial markers in one detector are uniquely identifiable (such as fluorescent beads). Triangulation requires each feature % in both images to be the same to be detected in both images of a stereo imaging system, and for these detections to be correctly associated with one another: this is known as the correspondence problem. Many methods exist to ensure that features are % % known and confidently the same detected from image data and accurately associated % image data from between two cameras or views. Properties of scale independent features and their surrounding pixel environment in one image can be matched to a similar feature in the second image. Now, suppose we know the relative positions of the two cameras and their respective intrinsic parameters, such as magnification and pixel offset. For a single camera and given the camera parameters, we can translate pixel coordinates, \(\gls{w} = (u, v)\), into the coplanar \gls{image plane} coordinates \(\gls{x}=(x, y)\): \begin{align} u &= u_0 + k_u x \\ v &= v_0 + k_v y \end{align} Knowing the focal length (\(f\)) of the imaging system, \gls{image plane} coordinates may be projected into a ray in \gls{3D}. The ray can be defined by using the point \gls{p} in camera-centred coordinates, where it crosses the \gls{image plane}. \begin{align} \mathbf{p} = \begin{bmatrix} x\\y\\z \end{bmatrix} \end{align} From the definition of a \gls{world point}, as observed through an image, we can construct a dual-view model of \gls{world point}s in space as in \figurename~\ref{fig:epi-polar-geom}. Using a model of a system with two views allows for the triangulation of rays based on image correspondences, this is an important part of stereo-vision. The most important matching constraint which can be used is the \emph{epipolar constraint}, and follows directly from the fact that the rays must intersect in 3D space. Epipolar constraints facilitate the search for correspondences, they constrain the search to a 1D line in each image. To derive general epipolar constraints, one should consider the epipolar geometry of two cameras as seen in \figurename~\ref{fig:epi-polar-geom} The \textbf{baseline} (\(OO'\))is defined as the line joining the optical centres of each view. An \textbf{epipole} is the point of intersection of the baseline with the image plan and there are two epipoles per feature, one for each camera. An \textbf{epipolar line} is a line of intersection of the epipolar plane (\(0\gls{X}O'\)with an image plane. It is the image in one camera of the ray from the other camera’s optical centre to the \gls{world point} (\gls{X}). For different \gls{world point}s, the epipolar plane rotates about the baseline. All epipolar lines intersect the epipole. The epipolar line constrains the search for correspondence from a region to a line. If a point feature is observed at \gls{x} in one image frame, then its location \gls{x'} in the other image frame must lie on the epipolar line. We can derive an expression for the epipolar line. The two camera-centered coordinate systems \gls{X_c'} and \gls{X_c} are related by a rotation, \gls{R} and translation, \gls{T} (see in \figurename~\ref{fig:epi-polar-geom}) as follows: \begin{align} \gls{X_c'} &= \gls{R}\gls{X_c} + \gls{T} \\ \intertext{Taking the vector product with \(\gls{T}\), we obtain} \gls{T} \times \gls{X_c'} &= \gls{T} \times \gls{R}\gls{X_c}+ \gls{T} \times \gls{T} \\ \gls{T} \times \gls{X_c'} &= \gls{T} \times \gls{R}\gls{X_c}\label{eq:Xprime = RTX} \end{align} \begin{figure} \centering \includegraphics{Chapters/flopt/Figs/PDF/epi-polar-geom} \caption[Epi-polar geometry described for two adjacent views]{ Epi-polar geometry described for two adjacent views (or cameras of a scene). Coordinates as expressed in \figurename~\ref{fig:coordinate_system_flopt} with prime notation (\('\)) denoting the additional right camera view. Transforming from right to left camera-centered coordinates (\gls{X_c'} to \gls{X_c}) requires a rotation (\gls{R}) and a translation (\gls{T}). }\label{fig:epi-polar-geom} \end{figure} \subsection{The Essential matrix} Taking the scalar product of \eqref{eq:Xprime = RTX} with \(\gls{X_c'}\), we obtain: \begin{align} \gls{X_c'} \cdot (\gls{T} \times \gls{X_c}) &= \gls{X_c'}\cdot (\gls{T} \times \gls{R} \gls{X_c'}) \\ \gls{X_c'} \cdot (\gls{T} \times \gls{R} \gls{X_c}) &= 0 \intertext{A vector product can be expressed as a matrix multiplication:} \gls{T} \times \gls{X_c} &= \gls{T_x} \gls{X_c} \intertext{where} \gls{T_x} &=\begin{bmatrix} 0 & -T_z & T_y\\ T_z & 0 & -T_x\\ -T_y & T_x & 0 \end{bmatrix} \end{align} So equation~\eqref{eq:Xprime = RTX} can be rewritten as: \begin{align} \gls{X_c'} \cdot (\gls{T_x} \gls{R}\gls{X_c}) = 0 \\ \gls{X_c'}^T \gls{Essential} \gls{X_c}= 0 \\ \intertext{where} \gls{Essential} = \gls{T_x} \gls{R} \end{align} \gls{Essential} is a \(3 \times 3\) matrix known as the \emph{\gls{essential matrix}}. The constraint also holds for rays \gls{p}, which are parallel to the camera-centered position vectors \gls{X_c}: \begin{align} \gls{p'}^T \gls{Essential} \gls{p} = 0 \label{eq:pEp} \end{align} This is the epipolar constraint. If a point \gls{p} is observed in one image, then its position \gls{p'} in the other image must lie on the line defined by Equation~\eqref{eq:pEp}. The \gls{essential matrix} can convert from pixels on the detector to rays \gls{p} in the world, assuming a calibrated camera (intrinsic properties are known), and pixel coordinates can then be converted to \gls{image plane} coordinates using: \begin{align} \begin{bmatrix} u\\ v\\ 1 \end{bmatrix} &= \begin{bmatrix} k_u & 0 & u_0 \\ 0 & k_v & v_0 \\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x\\ y\\ 1 \end{bmatrix} \intertext{We can modify this to derive a relationship between pixel coordinates and rays:} \begin{bmatrix} u\\ v\\ 1 \end{bmatrix} &= \begin{bmatrix} \frac{k_u}{f} & 0 & \frac{u_0}{f} \\ 0 & \frac{k_v}{f} & \frac{v_0}{f} \\ 0 & 0 & \frac{1}{f} \end{bmatrix} \begin{bmatrix} x\\ y\\ f \end{bmatrix} \intertext{\(\widetilde{\gls{K}}\) is defined as follows:} \widetilde{\gls{K}} &= \begin{bmatrix} f k_u & 0 & u_0 \\ 0 & f k_v & v_0 \\ 0 & 0 & 1 \end{bmatrix} \intertext{then we can write pixel coordinates in homogenous coordinates:} \widetilde{\gls{w}} &= \widetilde{\gls{K}} \gls{p} \end{align} \subsection{The Fundamental matrix} \begin{align} \intertext{From~\eqref{eq:pEp} the epipolar constraint becomes} % \mathbf{p'}^T E \mathbf{p} &= 0 \\ \widetilde{\gls{w'}} ^T \widetilde{\gls{K}}^{-T} \gls{Essential} \widetilde{\gls{K}}^{-1} \widetilde{\gls{w}} &= 0 \\ \widetilde{\gls{w'}} ^T \gls{F} \widetilde{\gls{w}} &= 0 \end{align} %\subsubsection{Two views} %\paragraph{Mapping from one camera to another} %\subsubsection{Three and more views} The (\(3\times3)\) matrix \gls{F}, is the called the \emph{\gls{fundamental matrix}}. With intrinsically calibrated cameras, structure can be recovered by triangulation. First, the two projection matrices are obtained via a \gls{SVD} of the essential matrix. The \gls{SVD} of the \gls{essential matrix} is given by: \begin{align} \gls{Essential} &= \gls{K'}^T \gls{F} \gls{K} = \gls{T_x} \gls{R} = \mathbf{U}\Lambda \mathbf{V}^T\\%\gls{R} = U\LambdaV^T\\ \intertext{It can be shown that} \hat{\gls{T_x}} &= U \begin{bmatrix} 0 & 1 & 0 \\ -1 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix} U^T \intertext{ and } \gls{R} &= U \begin{bmatrix} 0 & -1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix} V^T \intertext{Then, aligning the left camera and world coordinate systems gives the projection matrices:} \mathbf{P} &= \gls{K} \begin{bmatrix}[c|c] \mathbf{I} & \mathbf{0} \end{bmatrix} \intertext{ and } \mathbf{P}' &= \gls{K'} \begin{bmatrix}[c|c] \gls{R} & \gls{T} \end{bmatrix} \end{align} Where \( \begin{bmatrix}[c|c] \mathbf{I} & \mathbf{0} \end{bmatrix}\) is the identity matrix augmented column-wise with a zero matrix, and the two projection matrices (\(\mathbf{P}\) and \(\mathbf{P}'\)) project from camera pixel coordinates to world coordinates. Given these projection matrices, scene structure can be recovered (only up to scale, since only the magnitude of \gls{T} (|\gls{T}|) is unknown) using least squares fitting. Ambiguities in \gls{T} and \gls{R} are resolved by ensuring that visible points lie in front of the two cameras. As with the \gls{essential matrix}, the \gls{fundamental matrix} can be factorised into a skew-symmetric matrix corresponding to translation and a \(3 \times 3\) non-singular matrix corresponding to rotation. \section{The proposed algorithm} %The rotation may also not be orthogonal to the plane of detection. The shift of a camera or a camera pair around a scene separated by a transformation matrix (\( \begin{bmatrix}[c|c] \gls{R} & \gls{T} \end{bmatrix}\)) is analogous to a transforming the sample in the fixed view of an imaging detector, as in \gls{OPT}. During a typical \gls{OPT} acquisition, a marker will appear to follow an elliptical path in the \(xy\) camera plane. In the following volume reconstruction there will then be a fitting step to recover the path of the fiducial marker, to then apply a correction before applying a \gls{Radon transform}. This type of reconstruction not only ignores any mechanical jitter of the sample but also any affine, systematic, mechanical drift (in \(X,Y,Z,\theta,\phi,\psi \)). We have seen that using two adjacent images, of a scene separated by some rotation and translation, world points in \gls{3D} space may be triangulated within the scene given the rotational and translational matrices of the respect camera views. The inverse is also possible, given a sufficient number of known fiducial points in a scene the translation and rotation matrices can be recovered. The recovery of a more exact description of the motion of the scene can eliminate any need for a fitting and may recover and correct for drift, as well as eliminate any mechanical jitter. Errors may however then be introduced from fiducial markers mechanically slipping and localisation errors. Fiducial markers in this sense refer to an accurately locatable marker common through different views in a sample. Once a sufficient amount of fiducial markers are reliably tracked from the first to the second image, the \glslink{fundamental matrix}{fundamental}, \glslink{essential matrix}{essential} and \Gls{homography} matrices can be computed. Using the factorisation one of these matrixes, between each adjacent view of a rotating scene, the translation and rotational matrices may be recovered. Here we will discuss a reconstruction using \gls{F} but the same principle applies for \gls{Essential} and \gls{H}. \begin{figure} \centering \includegraphics{Chapters/flopt/Figs/PDF/flOPT_principle} \caption[Principles of the proposed algorithm]{Principles of the proposed algorithm. Each successive frame of \gls{OPT} image data will have an associated \gls{R} and \gls{T} (shown here in augmented form using homogenous coordinates), these matrices can be recovered from comparing the fiducial marker positions in each frame (\(n\)) and its successor (\(n+1\)).} \end{figure} Here are two ways of reconstructing using the \gls{fundamental matrix} as described above. The first method involves computing \gls{F} for two neighbouring images with 5 or more fiducial markers; having additional beads helps to remove ambiguity and increase confidence in \gls{F}. Once \gls{F} is calculated \gls{F} is then decomposed into \(\gls{R}_n\) and \(\gls{T}_n\) between each view \(n\) and \(n+1\). The image at view \(n+1\) is then back projected along the virtual optical axis within a virtual volume where the sample will be reconstructed. The size of this back projection and virtual volume is chosen to be suitably large (so that important data is not lost). Then, all the prior rotation and translation matrices are serially multiplied from \(\begin{bmatrix}[c|c] \gls{R}_0&\gls{T}_0 \end{bmatrix}\) until \(\begin{bmatrix}[c|c] \gls{R}_n&\gls{T}_n \end{bmatrix}\) % \([R_n|T_n] \) , this final matrix is inverted and applied to the back projected volume. The matrix inversion step is important as it realigns the back projection in the volume to where it originally was compared respective of the first projection. This process is repeated for every angle and the back projected volume from each step is summed with every other step. Finally the remaining volume is filtered using a high-pass filter; here a \gls{Ram-Lak filter} is used \footnote{Linear real (amplitude) ramp filter in Fourier space}. %: \(|v|\)} By producing a series of transformation matrices from adjacent acquisitions, errors compound and the reconstruction of volumes degrades with more projections, see \figurename~\ref{fig:irandons}. \begin{figure} \centering \hspace*{\fill} \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/iradon_nofilter}}; \node[below=of img] {\(X\)}; \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption[Unfiltered iRadon]{This is the unfiltered reconstruction of the object using the \gls{Radon transform}}\label{fig:iradon_nofilter}%TODO equation??? \end{subfigure}\hfill \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/iradon_filter}}; \node[below=of img] {\(v\)\vphantom{\(X\)}}; \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption[Filtered iRadon]{Ram-lak (Fourier ramp) filter applied to \figurename~\ref{fig:iradon_nofilter}.}\label{fig:iradon_filter} \end{subfigure} \hspace*{\fill} \caption[Effects of filtering the result of a inverse Radon transform reconstruction]{ The result of a tomographic reconstruction (using equally spaced angular steps and no translation between frames) requires Fourier filtering to normalise spatial contrast.}\label{fig:irandons}%TODO simulations with no drift and skew and use equation \end{figure} % % % % \begin{figure} % \centering % \hspace*{\fill} % \begin{subfigure}[t]{0.3\textwidth} % \includegraphics[width=\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/iradon_nofilter} % \caption[Unfiltered iRadon]{This is the unfiltered reconstruction of the object using the \gls{Radon transform}}%TODO equation??? % \label{fig:iradon_nofilter} % \end{subfigure}\hfill % \begin{subfigure}[t]{0.3\textwidth} % \includegraphics[width=\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/iradon_filter} % \caption[Filtered iRadon]{Ram-lak (Fourier ramp) filter applied to \figurename~\ref{fig:iradon_nofilter}.} % \label{fig:iradon_filter} % \end{subfigure} % \hspace*{\fill} % % \label{fig:irandons} % \caption{The result of a tomographic reconstruction (using equally spaced angular steps and no translation between frames) requires Fourier filtering to normalise spatial contrast.}\label{fig:irandons}%TODO simulations with no drift and skew and use equation % \end{figure} The second approach is less prone to compound errors but relies on precise identification and tracking of fiducial markers. % distinction and tracking fiducials. Instead of calculating \gls{F} between neighbouring images, \gls{F} is calculated between the current projection and the very first projection. \gls{F} is then decomposed and the transformation matrix is inverted and applied to the back projected volume. The reoriented back projected volumes are summed and finally filtered to remove the additional spatial frequencies imparted from rotating the sample. \begin{figure} \centering \begin{subfigure}[t]{\textwidth} \centering \includegraphics{flopt_algorithm_forward} \caption{Forward model}\label{fig:flopt_algorithm_forward} \end{subfigure}\\\vspace{\abovecaptionskip} \begin{subfigure}[t]{\textwidth} \centering \includegraphics{flopt_algorithm} \caption{Reconstruction method, solving the inverse problem.}\label{fig:flopt_algorithm_inverse} \end{subfigure} \caption[Simulation of \gls{OPT} data incorporating rotational and translational offsets, and the proposed reconstruction algorithm]{ % Two dimensional representation of the reconstruction algorithm. This figure illustrates the simulation of \gls{OPT} data incorporating rotational and translational offsets, and the proposed reconstruction algorithm. (\subref{fig:flopt_algorithm_forward}): The \(n\) projections of the object (\(\Sigma \)), at rotation (\(\gls{R}_1\) to \(\gls{R}_n\)) and translation (\(\gls{T}_1\) to \(\gls{T}_n\)), produces \(n\) frames of image data. During the \gls{OPT} measurement, \(n\) projections of the object \(\Sigma \) are observed with rotations \(\gls{R}_1\) to \(\gls{R}_n\) and corresponding translations \(\gls{T}_1\) to \(\gls{T}_n\) where the translations account for imperfect alignment. (\subref{fig:flopt_algorithm_inverse}): In the reconstruction algorithm, the rotational and translational matrices are recovered (\(\gls{R}_1'\) to \(\gls{R}_n'\) and \(\gls{T}_1'\) to \(\gls{T}_n'\)) from triangulation of the fiducial markers. These transformation matrices are then used to obtain a contribution to the volumetric reconstruction from each observed frame and the summated reconstruction is assembled from the \(n\) frames. The now realigned back projections are summed to produce an unfiltered back projection. % and inversely applied % to align back project the datasets, The transformation matrices are shown in augmented form using homogenous coordinates. }\label{fig:flopt_algorithm} %TODO tidy \end{figure} The second approach is robust against compound errors but an additional programatic step is needed to know which beads in the first image correspond to beads in the \(n^{\text{th}}\) image. This can be is achieved using tracking and momentum particle tracking algorithms, though confounding issues can arise i.e.~if a particle orbits too far away from the imaging plane or occlusions occur. In both cases a decomposed \gls{F} matrix will produce four possible transformation pairs (\gls{R},\gls{T}; \gls{R},-\gls{T}; -\gls{R},\gls{T}; -\gls{R},-\gls{T}). %TODO look this up. Once the transformation matrix between the first view and the second view is calculated the proceeding transformation matrices are then easily chosen by similarity and general direction of motion. An example of this type of selection would be: \begin{align} \min_{I(n)}\left[I(n) = \left(\begin{bmatrix}[c|c] \gls{R}_n&\gls{T}_n \end{bmatrix} - \begin{bmatrix}[c|c] \gls{R}_{n-1}&\gls{T}_{n-1} \end{bmatrix}\right)^2\right] \end{align} The first two views are more difficult to choose the correct decomposition for, but it is possible if a suitable ideal matrix is given as a comparison. Such an ideal matrix is composed using \emph{a priori} knowledge of the likely angle of rotation of the system's imaging properties. \section{Verification of the proposed algorithm} To verify that the proposed algorithm successfully reconstructs the specimen%as theorised , it was applied to simulated data. The image of Lena \footnote{Standard reference image data % The image of Lena is used as a reference to a very early full colour digital scanner. % The researchers in question realised that their presentation of the scanner's capabilities at a conference lacked a test image. % The nearest image to hand was a Playboy magazine with Lena Söderberg as the centrefold. } is used here as a test image to verify the validity of each reconstruction. Superimposed on Lena are fiducial beads to track the rotation of the image, see \figurename~\ref{fig:raw_input}. The reference image was then rotated through \SI{128} angles over \(2\pi \) radians and projected along the \(Y\) axis and a slice in (\(X,Y\)) was taken to create a single line projection, shown three dimensionally in \figurename~\ref{fig:recon_iterative}. This is repeated for each angle with each line projection stacked to create a sinugram, see \figurename~\ref{fig:sinugram_stretch}. % \begin{figure} % \centering % \hfill % \begin{subfigure}[t]{0.3\textwidth} % \includegraphics[width=\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/rawinput_colour} % \caption{Raw input for OPT simulations, Lena.} % \label{fig:raw_input} % \end{subfigure}\hfill % \begin{subfigure}[t]{0.3\textwidth} % \includegraphics[width=\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/sinugram_stretch} % \caption{Image of Lena (\figurename~\ref{fig:raw_input}) after rotation and projection in 2D, giving the sinugram.} % \label{fig:sinugram_stretch} % \end{subfigure} % \hfill % \label{fig:rawinputs} % \caption{Reference images for OPT reconstruction.} % \end{figure} \begin{figure} % \begin{subfigure}[t]{\linewidth} \centering \includegraphics{/ortho_3d_correct} \caption{Ground truth \gls{3D} object for reconstruction, based on the Cameraman and Lena testcard images.}\label{fig:ortho_3d_correct} % \end{subfigure} \end{figure} \begin{figure} % \ContinuedFloat{} \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/0/xy}\caption{Raw\\Frame (\(n\)): 0\\View: (\(X,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/0/xy_recon}\caption{Reconstructed\\Frame (\(n\)): 0\\View: (\(X,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/0/zx}\caption{Raw\\Frame (\(n\)): 0\\View: (\(Z,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/0/zx_recon}\caption{Reconstructed\\Frame (\(n\)): 0\\View: (\(Z,Y\))} \end{subfigure} \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/1/xy}\caption{Raw\\Frame (\(n\)): 1\\View: (\(X,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/1/xy_recon}\caption{Reconstructed\\Frame (\(n\)): 1\\View: (\(X,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/1/zx}\caption{Raw\\Frame (\(n\)): 1\\View: (\(Z,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/1/zx_recon}\caption{Reconstructed\\Frame (\(n\)): 1\\View: (\(Z,Y\))} \end{subfigure} \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/dots/xy}%\caption{Raw data. Frame (\(n\)): , View: \(xy\)} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/dots/xy_recon}%\caption{Reconstructed\\Frame (\(n\)):0, View:\(xy\)} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/dots/zx}%\caption{Raw data. Frame (\(n\)): , View: \(zy\)} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/dots/zx}%\caption{Reconstructed\\Frame (\(n\)):, View:\(zx\)} \end{subfigure} \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/31/xy}\caption{Raw\\Frame (\(n\)): 31\\View: (\(X,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/31/xy_recon}\caption{Reconstructed\\Frame (\(n\)): 31\\View: (\(X,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/31/zx}\caption{Raw\\Frame (\(n\)): 31\\View: (\(Z,Y\))} \end{subfigure}\hfill \begin{subfigure}[t]{0.2\linewidth} \centering \includegraphics[width=\textwidth]{/results/3D_python/no_drift/31/zx_recon}\caption{Reconstructed\\Frame (\(n\)): 31\\View: (\(Z,Y\))} \end{subfigure} \caption[A \gls{3D} test-volume of two orthogonal and different testcard images, was used to verify the reconstructive capabilities of the proposed algorithm]{ A \gls{3D} test-volume of two orthogonal and different testcard images, from \figurename~\ref{fig:ortho_3d_correct}, was used to verify the reconstructive capabilities of the proposed algorithm. The projected image data (b),~(h),~(j) and (d),~(h),~(l), were used to iteratively generate reconstructions where the \(n^\text{th}\) reconstruction incorporates all the information from observation 0 to \(n\). The results are unfiltered for clarity of demonstrating the iterative reconstruction, which is applied in \figurename~\ref{fig:flopt_filter}. }\label{fig:recon_iterative} %TODO use different filters. \end{figure} \begin{figure} \centering \hspace*{\fill} \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/flopt_camerman}}; \node[below=of img] {\(Z\)}; \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption{Filtered reconstruction Cameraman testcard} \end{subfigure}\hfill \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/no_helix/flopt_filter}}; \node[below=of img] {\(X\)}; \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption{Filtered reconstruction of Lena testcard} \end{subfigure} \hspace*{\fill} \caption[Filtered reconstruction of the ground truth reference image using the new proposed algorithm.]{ Filtered reconstruction of the ground truth reference image from \figurename~\ref{fig:recon_iterative} using the new proposed algorithm. }\label{fig:flopt_filter} \end{figure} In the standard approach for \gls{OPT} reconstruction, the \gls{sinugram} undergoes the inverse \gls{Radon transform}, as shown in \figurename~\ref{fig:iradon_nofilter} and then post-filtering, see \figurename~\ref{fig:iradon_filter}. This step is substituted for the proposed algorithm; in \figurename~\ref{fig:flopt_comparison_line_profile} the two techniques are compared for ideal conditions of smooth, predictable rotation. The proposed algorithm produces %(see ) a faithful reconstruction on the original image, as shown in \figurename~\ref{fig:flopt_filter} %with some minor deviations. Both techniques lose some of the original contrast of the object due to under-sampling of rotations. When taking the histogram of the absolute pixel-wise difference between the original source image to the images produced by the new algorithm and the \gls{Radon transform}, % there is good overlap between the two, see \figurename~\ref{fig:flopt_histogram}. The mean square errors (\gls{MSE}, see Equation~\eqref{eq:mse}) of the new algorithm and the \gls{Radon transform} are \SI{15.01}{\percent} and \SI{14.84}{\percent} respectively, see \figurename~\ref{fig:flopt_histogram} for a histogram of a pixel-wise comparison. This suggests that the new algorithm is producing an accurate reconstruction of the object, similar to the standard \gls{Radon transform}. %, see \figurename~\ref{fig:flopt_histogram} \begin{align} \operatorname{\gls{MSE}}=\frac{1}{n}\sum_{i=1}^n{(Y_i-\hat{Y_i})}^2 \label{eq:mse} % \intertext{Where \(\hat{Y_i}\) is the ith value and Y_i } \end{align} \begin{figure} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/comparison_line_profile} \caption[Line profile comparison of the standard and new algorithms]{Line profile comparison of the reconstruction of a reference image computationally rotated, projected and reconstructed using the standard \gls{Radon transform} and the new proposed algorithm.}\label{fig:flopt_comparison_line_profile} \end{figure} \begin{figure} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/flopt_histogram} \caption[Histogram of of pixel values compared between reconstructions using flOPT and the \gls{Radon transform}]{Histogram of of pixel values compared between reconstructions using flOPT and the \gls{Radon transform}. The shift of the histogram to towards overall lower deviance from the source image suggests the flOPT algorithm out performs the \gls{Radon transform}}\label{fig:flopt_histogram} \end{figure} %However, the proposed algorithm fairs worse in terms of contrast compared to a \gls{Radon transform}. The more challenging case of a sample drifting, with a constant velocity, systematically along the \(X\) axis was then considered; this produced a helical path of a single fiducial within the sample, see \figurename~\ref{fig:flopt_helix_sinugram}. In \figurename~\ref{fig:unfilttered_reconstruction_helix_iradon}, the \gls{Radon transform} entirely fails to produce a recognisable reproduction of the test image with the addition of a slight helicity to the rotation. The proposed algorithm produces an equivalent result to that of a sample rotating without any systematic drift, see \figurename~\ref{fig:iradon_filter}. In \figurename~\ref{fig:helical_comparison} the respective images from each algorithm were compared, as before, while the helical shift was incremented. See \figurename~\ref{fig:flopt_helix_sinugram} for a \gls{sinugram} of a sample whereby a helical shift has been induced. When using correlation as a metric of reproduction quality, at zero helicity, the new algorithm fairs slightly worse at \SI{94}{\percent} correlation compared to the \gls{Radon transform} at \SI{96}{\percent}. As expected, the \gls{Radon transform} rapidly deteriorates once a systematic drift is applied; whereas the new algorithm maintains the quality of the reconstruction, see \figurename~\ref{fig:helical_comparison}. % % \begin{figure} % \centering % \hspace*{\fill} % \begin{subfigure}[t]{0.3\textwidth} % \begin{tikzpicture}[node distance=0cm] % \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/helix/topdown_bead_paths}}; % \node[below=of img] {\(X\)}; % \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; % \end{tikzpicture} % \caption{Top down views (\(X,Y\)) of the source image with the fiducial paths marked.}\label{fig:topdown_bead_paths} % \end{subfigure}\hfill % \begin{subfigure}[t]{0.3\textwidth} % \begin{tikzpicture}[node distance=0cm] % \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/helix/sinugram_stretch}}; % \node[below=of img] {\(v\)\vphantom{\(X\)}}; % \node[left=of img,rotate=90,yshift=0.2cm] {\(n\)}; % \end{tikzpicture} % \caption{Sinugram (\(v,n\)) of a sample whose axis of rotation has a systematic drift}\label{fig:flopt_helix_sinugram} % \end{subfigure} % \hspace*{\fill} % \caption{Comparison of the two reconstructions under sample imaging with a systematic drift, in 3D though represented here in 2D.}\label{fig:flopts} % \end{figure} \begin{figure} \centering \hspace*{\fill} \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/helix/topdown_bead_paths}}; \node[below=of img] {\(X\)}; \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption{Top down views (\(X,Y\)) of the source image with the fiducial paths marked.}\label{fig:topdown_bead_paths} \end{subfigure}\hfill \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/helix/sinugram_stretch}}; \node[below=of img] {\(v\)\vphantom{\(X\)}}; \node[left=of img,rotate=90,yshift=0.2cm] {\(n\)}; \end{tikzpicture} \caption{Sinugram (\(v,n\)) of a sample whose axis of rotation has a systematic drift}\label{fig:flopt_helix_sinugram} \end{subfigure}\hspace*{\fill} \\\vspace{\abovecaptionskip} \hspace*{\fill} \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/helix/unfilttered_reconstruction_helix_iradon}}; \node[below=of img] {\(X\)}; \node[left=of img,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption{Reconstruction using a \gls{Radon transform}.}\label{fig:unfilttered_reconstruction_helix_iradon} \end{subfigure}\hfill \begin{subfigure}[t]{0.3\textwidth} \begin{tikzpicture}[node distance=0cm] \node (img1) {\includegraphics[width=0.8\textwidth]{Chapters/flopt/Figs/PDF/results/helix/filtered_recon_helix}}; \node[below=of img1] {\(v\)\vphantom{\(X\)}}; \node[left=of img1,rotate=90,yshift=0.2cm] {\(Y\)}; \end{tikzpicture} \caption{Reconstruction using the new algorithm.}\label{fig:filtered_recon_helix} \end{subfigure} \hspace*{\fill} % \caption{} \caption{Comparison of the two reconstructions under sample imaging with a systematic drift, in 3D though represented here in 2D.}\label{fig:flopts} \end{figure} \begin{figure} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/correlation_helicity} \caption[Comparison of standard and proposed OPT reconstruction algorithms for acquisitions with drift]{%2D correlation of the source image shows that flOPT does not degrade under systematic drift compared to s. Comparison of standard and proposed \gls{OPT} reconstruction algorithms for acquisitions with drift. 2D image correlation of the ground truth and the reconstruction shows that the proposed flOPT algorithm does not degrade with systematic drift, whereas reconstruction using the standard \gls{Radon transform} is severely degraded. }\label{fig:helical_comparison} \end{figure} \subsection{Recovery of R and T using matrix decomposition} To quantitatively verify that the matrix decomposition technique was valid and robust, the accuracy of the reproduction of \gls{R} and \gls{T} was tested directly. The original \gls{R} and \gls{T} matrices were computed and compared to \gls{R} and \gls{T} generated from matrix decomposition, this absolute difference was computed element-wise in each matrix and then an average for each matrix was taken. Overall, the worst case scenario produced a percentage error of \SI{2}{\percent} (see \figurename~\ref{fig:pc_sum_decompose} for full statistics). The accuracy of the calculated \gls{R} and \gls{T} did deteriorate when adding in additional degrees of combined movement, but with no correlation between the degree of helicity and the error produced. % but the severity of this movement appeared to no trending effect. Consistently the translational matrix (\gls{T}) was more accurately reproduced, this is likely due to there being fewer of degrees of freedom for errors to spread over. %The images produced are a more faithful reproduction of the source image as the degree of helicity is increased. %This effect may be due to the additional sampling induced by adding another degree of movement, that is the systematic drift. %Textwidth is \the\textwidth \begin{figure} \centering \begin{subfigure}[t]{0.5\textwidth} \captionsetup{width=0.8\textwidth} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/helix/decompose/pc_sum_rot_alpha} \caption{Rotation matrix, with angular drift in \(\alpha \)}\label{fig:pc_sum_rot_alpha} \end{subfigure}\hfill \begin{subfigure}[t]{0.5\textwidth} \captionsetup{width=0.8\textwidth} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/helix/decompose/pc_sum_trans_alpha} \caption{Translation matrix, with angular drift in \(\alpha \)}\label{fig:pc_sum_trans_alpha} \end{subfigure} \bigskip \begin{subfigure}[t]{0.5\textwidth} \captionsetup{width=0.8\textwidth} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/helix/decompose/pc_sum_rot_tx} \caption{Rotation matrix, with helical drift in \(x\) only}\label{fig:pc_sum_rot_tx} \end{subfigure}\hfill \begin{subfigure}[t]{0.5\textwidth} \captionsetup{width=0.8\textwidth} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/helix/decompose/pc_sum_trans_tx} \caption{Translation matrix, with helical drift in \(x\) only}\label{fig:pc_sum_trans_tx} \end{subfigure} \bigskip \begin{subfigure}[t]{0.5\textwidth} \captionsetup{width=0.8\textwidth} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/helix/decompose/pc_sum_rot_both} \caption{Rotation matrix, with angular drift in \(\alpha \) and helical drift in \(x\)}\label{fig:pc_sum_rot_both} \end{subfigure}\hfill \begin{subfigure}[t]{0.5\textwidth} \captionsetup{width=0.8\textwidth} \centering \includegraphics{Chapters/flopt/Figs/PDF/results/helix/decompose/pc_sum_trans_both} \caption{Translation matrix, with angular drift in \(\alpha \) and helical drift in \(X\)}\label{fig:pc_sum_trans_both} \end{subfigure} \caption[Box plots demonstrating that the rotational and translations matrices can be recovered accurately from fiducial marker positions]{Box plots demonstrating that the rotational and translations matrices can be recovered accurately from fiducial marker positions. Panels~(\subref{fig:pc_sum_rot_alpha}) and~(\subref{fig:pc_sum_trans_alpha}) introduce an angular drift during rotation, to an observer at the detector this would appear as a tip of the sample towards them, causing precession. Panels~(\subref{fig:pc_sum_rot_tx}) and~(\subref{fig:pc_sum_trans_tx}) introduce a lateral drift in \(X\) causing a helical path to be drawn out. Panels~(\subref{fig:pc_sum_rot_both}) and~(\subref{fig:pc_sum_trans_both}) combine the two effects. In all cases the percentage error introduced by the the addition of undesirable additional movements was on the order of \SI{<2}{\percent}. }\label{fig:pc_sum_decompose} \end{figure} \section{Discussion} A new algorithm for reconstructing OPT data has been demonstrated. The new algorithm uses multiple fiducial markers to recover the matrix which describes the rotation and translation of the sample. The quality of the reconstructions when compared to a standard \gls{Radon transform} shows a slight improvement, with a great effect when a systematic drift is introduced. To measure the accuracy of the decomposition of \gls{F} into \gls{R} and \gls{T} they were compared to the ground truth matrices. The element-wise absolute difference \(\left(\frac{x-y}{2(x+y)}\right)\) of each matrix was averaged across the matrix for \gls{R} and \gls{T}. In the worst case scenario a maximum of \SI{2}{\percent} average absolute difference was found between ground truth and recovered matrices, % When comparing the % expected matrices to the recovered matrices a % ground truth matrices to the recovered matrices were compared using the average of the element-wise using square differences % peak of \SI{2}{\percent} difference is found between the two when considering worst case scenarios; suggesting the technique is robust to various forms of drift and general instability. Such an algorithm could be used to help in minimising ghosting effects seen in real samples; particularly in samples where slipping is likely to occur such as in gels or in cheaper \gls{OPT} systems which tend to be more mechanically unstable and imprecise. \section{Future work} \subsection{Bead tracking} The work presented here is, so far, is a proof-of-concept demonstrated by simulation and reconstruction from ground-truth testcard objects, and requires several further steps in order apply it to real \gls{OPT} data. Firstly, a bead-tracking algorithm~\cite{crockerMethodsDigitalVideo1996} will need to be created to reliably track multiple beads, concurrently, in an image series. A sensible approach would be to have a user select the fiducial markers in the image on the first frame and template match in a small window around the selection; this is similar to the algorithm described in Chapter~\ref{chapter:spt}. Template matching is robust to occlusions provided the fiducial is not fully eclipsed. If two fiducial markers occlude each other however, this algorithm may switch their identities or both tracking windows may follow one bead. This is a common problem in particle tracking algorithms, but is solved by using a weighted likelihood based on momentum\cite{chenouardMultipleHypothesisTracking2013}. The likelihood of a bead occlusion occurring will increase with he introduction of additional beads into the sample. As such occluded beads may need to be omitted. % and possibly interpolated for. % Egregious outliers may be found by tracking a \emph{confidence} estimator as the bead rotates as in % A primitive estimator would be the pixel-wise sum of intensities in the result of a correlative template matching. % Whilst this confidence value itself has no physical interpretation, any stark changes in the derivative will be suggestive of an occlusion or mis-tracking of some variety, see \figurename~\ref{fig:confidence_bead_tracking}. % \begin{figure} % \centering % \includegraphics{Chapters/flopt/Figs/PDF/results/confidence_bead_tracking} % \caption{A plot of the confidence value of a single fiducial bead being tracking \emph{in vivo}. % Sharp changes in the confidence value occur when the fiducial bead is occluded. % The image at the origin shows the fiducial being tracked well in the first frame. % (Images courtesy of Pedro Vallejo) % } % \label{fig:confidence_bead_tracking} % \end{figure} \subsection{Multiple views tracking} The theory backing the proposed algorithm relies on triangulation between two view points. In this work the two view points refer to the image at frames \(n\) and \(n+1\). However, it is possible to use three separate views (frames \(n\), \(n+1\) and \(n+2\)) to reconstruct a scene, one such approach being quaternion tensors. Working with tensors is computationally and mathematically more challenging, but a future iteration of the algorithm presented here may benefit from using three views to provide a more accurate transformation matrix. Beyond three views there currently is no mathematical framework at present for four or more views. If such tools did exist, it may be possible to make the algorithm described above as non-iterative and essentially a single shot reconstruction from pixels to voxels. \subsection{Fiducial free reconstruction} In computer vision, scenes often do not contain known fiducial marks and so such marks are found between views. To find such a correspondences, points with similar local texture are found and matched in between each image. %, many of these such correspondences are found This technique is only valid for views with small angles between them, as would be found in \gls{OPT}. A similar method could be introduced into the algorithm presented here, as each image should have sufficient texture, particularly when using \gls{tOPT}. The following chapter will move from improvements in registration using projective matrices and into improvements in resolution using on-camera slit-scanning. %A future version of this algorithm may be able to use 3 views to produce a more faithful transformation matrix. %The mathematics for more than three views currently does not exist.
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.intervals.basic import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Projection of a line onto a closed interval Given a linearly ordered type `α`, in this file we define * `set.proj_Icc (a b : α) (h : a ≤ b)` to be the map `α → [a, b]` sending `(-∞, a]` to `a`, `[b, ∞)` to `b`, and each point `x ∈ [a, b]` to itself; * `set.Icc_extend {a b : α} (h : a ≤ b) (f : Icc a b → β)` to be the extension of `f` to `α` defined as `f ∘ proj_Icc a b h`. We also prove some trivial properties of these maps. -/ namespace set /-- Projection of `α` to the closed interval `[a, b]`. -/ def proj_Icc {α : Type u_1} [linear_order α] (a : α) (b : α) (h : a ≤ b) (x : α) : ↥(Icc a b) := { val := max a (min b x), property := sorry } theorem proj_Icc_of_le_left {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) {x : α} (hx : x ≤ a) : proj_Icc a b h x = { val := a, property := iff.mpr left_mem_Icc h } := sorry @[simp] theorem proj_Icc_left {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) : proj_Icc a b h a = { val := a, property := iff.mpr left_mem_Icc h } := proj_Icc_of_le_left h le_rfl theorem proj_Icc_of_right_le {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) {x : α} (hx : b ≤ x) : proj_Icc a b h x = { val := b, property := iff.mpr right_mem_Icc h } := sorry @[simp] theorem proj_Icc_right {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) : proj_Icc a b h b = { val := b, property := iff.mpr right_mem_Icc h } := proj_Icc_of_right_le h le_rfl theorem proj_Icc_of_mem {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) {x : α} (hx : x ∈ Icc a b) : proj_Icc a b h x = { val := x, property := hx } := sorry @[simp] theorem proj_Icc_coe {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) (x : ↥(Icc a b)) : proj_Icc a b h ↑x = x := subtype.cases_on x fun (x_val : α) (x_property : x_val ∈ Icc a b) => proj_Icc_of_mem h x_property theorem proj_Icc_surj_on {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) : surj_on (proj_Icc a b h) (Icc a b) univ := fun (x : ↥(Icc a b)) (_x : x ∈ univ) => Exists.intro ↑x { left := subtype.property x, right := proj_Icc_coe h x } theorem proj_Icc_surjective {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) : function.surjective (proj_Icc a b h) := fun (x : ↥(Icc a b)) => Exists.intro (↑x) (proj_Icc_coe h x) @[simp] theorem range_proj_Icc {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) : range (proj_Icc a b h) = univ := function.surjective.range_eq (proj_Icc_surjective h) theorem monotone_proj_Icc {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) : monotone (proj_Icc a b h) := fun (x y : α) (hxy : x ≤ y) => max_le_max le_rfl (min_le_min le_rfl hxy) theorem strict_mono_incr_on_proj_Icc {α : Type u_1} [linear_order α] {a : α} {b : α} (h : a ≤ b) : strict_mono_incr_on (proj_Icc a b h) (Icc a b) := sorry /-- Extend a function `[a, b] → β` to a map `α → β`. -/ def Icc_extend {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) (f : ↥(Icc a b) → β) : α → β := f ∘ proj_Icc a b h @[simp] theorem Icc_extend_range {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) (f : ↥(Icc a b) → β) : range (Icc_extend h f) = range f := sorry theorem Icc_extend_of_le_left {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) {x : α} (f : ↥(Icc a b) → β) (hx : x ≤ a) : Icc_extend h f x = f { val := a, property := iff.mpr left_mem_Icc h } := congr_arg f (proj_Icc_of_le_left h hx) @[simp] theorem Icc_extend_left {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) (f : ↥(Icc a b) → β) : Icc_extend h f a = f { val := a, property := iff.mpr left_mem_Icc h } := Icc_extend_of_le_left h f le_rfl theorem Icc_extend_of_right_le {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) {x : α} (f : ↥(Icc a b) → β) (hx : b ≤ x) : Icc_extend h f x = f { val := b, property := iff.mpr right_mem_Icc h } := congr_arg f (proj_Icc_of_right_le h hx) @[simp] theorem Icc_extend_right {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) (f : ↥(Icc a b) → β) : Icc_extend h f b = f { val := b, property := iff.mpr right_mem_Icc h } := Icc_extend_of_right_le h f le_rfl theorem Icc_extend_of_mem {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) {x : α} (f : ↥(Icc a b) → β) (hx : x ∈ Icc a b) : Icc_extend h f x = f { val := x, property := hx } := congr_arg f (proj_Icc_of_mem h hx) @[simp] theorem Icc_extend_coe {α : Type u_1} {β : Type u_2} [linear_order α] {a : α} {b : α} (h : a ≤ b) (f : ↥(Icc a b) → β) (x : ↥(Icc a b)) : Icc_extend h f ↑x = f x := congr_arg f (proj_Icc_coe h x) end set theorem monotone.Icc_extend {α : Type u_1} {β : Type u_2} [linear_order α] [preorder β] {a : α} {b : α} (h : a ≤ b) {f : ↥(set.Icc a b) → β} (hf : monotone f) : monotone (set.Icc_extend h f) := monotone.comp hf (set.monotone_proj_Icc h) theorem strict_mono.strict_mono_incr_on_Icc_extend {α : Type u_1} {β : Type u_2} [linear_order α] [preorder β] {a : α} {b : α} (h : a ≤ b) {f : ↥(set.Icc a b) → β} (hf : strict_mono f) : strict_mono_incr_on (set.Icc_extend h f) (set.Icc a b) := strict_mono.comp_strict_mono_incr_on hf (set.strict_mono_incr_on_proj_Icc h)
import .sqe .qfree .wf --..equiv ..num .sqe open list def atom.unified (a : atom) : Prop := head_coeff a = -1 ∨ head_coeff a = 0 ∨ head_coeff a = 1 def unified (p : formula) : Prop := ∀ a ∈ p.atoms, (atom.unified a) lemma eval_subst_iff {i ks xs} : ∀ {p}, nqfree p → ((subst i ks p).eval xs ↔ p.eval ((i + znum.dot_prod ks xs)::xs)) | ⊤' _ := by refl | ⊥' _ := by refl | (A' (atom.le i ks')) _ := begin simp [subst, formula.map], cases ks' with k' ks'; simp [asubst, eval_le], simp [znum.comp_add_dot_prod, znum.dot_prod, mul_add, znum.map_mul_dot_prod], end | (A' (atom.ndvd d i ks')) _ := begin simp [subst, formula.map], cases ks' with k' ks'; simp [asubst, eval_ndvd], simp [znum.comp_add_dot_prod, znum.dot_prod, mul_add, znum.map_mul_dot_prod], end | (A' (atom.dvd d i ks')) _ := begin simp [subst, formula.map], cases ks' with k' ks'; simp [asubst, eval_dvd], simp [znum.comp_add_dot_prod, znum.dot_prod, mul_add, znum.map_mul_dot_prod] end | (p ∧' q) hf := begin cases hf with hfp hfq, unfold subst, unfold formula.map, repeat {rewrite eval_and}, let ihp := @eval_subst_iff p hfp, unfold subst at ihp, rewrite ihp, let ihq := @eval_subst_iff q hfq, unfold subst at ihq, rewrite ihq end | (p ∨' q) hf := begin cases hf with hfp hfq, unfold subst, unfold formula.map, repeat {rewrite eval_or}, let ihp := @eval_subst_iff p hfp, unfold subst at ihp, rewrite ihp, let ihq := @eval_subst_iff q hfq, unfold subst at ihq, rewrite ihq end | (¬' p) hf := by cases hf | (∃' p) hf := by cases hf lemma inf_minus_prsv (zs) : ∀ (p : formula), ∃ (y : znum), ∀ z, z < y → ((inf_minus p).eval (z::zs) ↔ p.eval (z::zs)) | ⊤' := begin existsi (0 : znum), intros z hz, constructor; intro hc; trivial end | ⊥' := begin existsi (0 : znum), intros z hz, constructor; intro hc; cases hc end | (A' (atom.le i ks)) := begin cases ks with k ks, { existsi (0 : znum), intros z hz, refl }, cases (lt_trichotomy k 0) with hlt heqgt; [ {}, { cases heqgt with heq hgt } ], { existsi (- abs (i - znum.dot_prod ks zs)), intros z hz, simp [inf_minus_le_eq_of_lt hlt], constructor; intro h, { simp [formula.eval, atom.eval, znum.dot_prod], rw sub_le_iff_le_add'.symm, apply calc i - znum.dot_prod ks zs ≤ abs (i - znum.dot_prod ks zs) : le_abs_self _ ... ≤ -z : begin rw lt_neg at hz, apply le_of_lt hz end ... ≤ k * z : begin rw (znum.neg_one_mul_eq_neg).symm, repeat {rw mul_comm _ z}, rw znum.mul_le_mul_iff_le_of_neg_left, apply znum.le_of_lt_add_one, apply hlt, apply lt_of_lt_of_le hz (neg_le_of_neg_le _), have h := abs_nonneg (i - znum.dot_prod ks zs), apply h end }, { trivial } }, { subst heq, simp [inf_minus_le_eq_of_eq] }, { existsi (- abs (i - znum.dot_prod ks zs)), intros z hz, simp [inf_minus_le_eq_of_gt hgt], constructor; intro h, { cases h }, { apply absurd h, simp [formula.eval, atom.eval, znum.dot_prod], rw lt_sub_iff_add_lt'.symm, apply calc k * z ≤ 1 * z : begin repeat {rw (mul_comm _ z)}, rw znum.mul_le_mul_iff_le_of_neg_left, apply znum.add_one_le_of_lt hgt, apply lt_of_lt_of_le hz (neg_le_of_neg_le _), apply abs_nonneg (i - znum.dot_prod ks zs) end ... = z : one_mul _ ... < - abs (i - znum.dot_prod ks zs) : hz ... ≤ i - znum.dot_prod ks zs : begin rw neg_le, apply neg_le_abs_self (i - znum.dot_prod ks zs), end } } end | (A' (atom.dvd d i ks)) := begin simp [inf_minus] end | (A' (atom.ndvd d i ks)) := begin simp [inf_minus] end | (p ∧' q) := begin cases (inf_minus_prsv p) with x hx, cases (inf_minus_prsv q) with y hy, cases (znum.exists_lt_and_lt x y) with z hz, cases hz with hz1 hz2, existsi z, intros w hw, simp [inf_minus, eval_and_o, eval_and, hx w (lt.trans hw hz1), hy w (lt.trans hw hz2)] end | (p ∨' q) := begin cases (inf_minus_prsv p) with x hx, cases (inf_minus_prsv q) with y hy, cases (znum.exists_lt_and_lt x y) with z hz, cases hz with hz1 hz2, existsi z, intros w hw, simp [inf_minus, eval_or_o, eval_or, hx w (lt.trans hw hz1), hy w (lt.trans hw hz2)] end | (¬' p) := begin simp [inf_minus] end | (∃' p) := begin simp [inf_minus] end lemma divisors_lcm_pos {p : formula} : formula.wf p → 0 < divisors_lcm p := begin intro hn, apply znum.lcms_pos, intros z hz, rewrite list.mem_map at hz, cases hz with a ha, cases ha with ha1 ha2, subst ha2, unfold formula.atoms_dep_0 at ha1, rw (@mem_filter _ dep_0 _ a (p.atoms)) at ha1, rewrite wf_iff_wf_alt at hn, rewrite iff.symm normal_iff_divisor_nonzero, apply hn, apply ha1^.elim_left end lemma divisors_lcm_dvd_eq {d i k : znum} {ks : list znum} : k ≠ 0 → divisors_lcm (A' (atom.dvd d i (k::ks))) = abs d := begin intro h, simp [divisors_lcm, formula.atoms_dep_0, formula.atoms, dep_0, filter, head_coeff], rw if_pos, simp [map, divisor, znum.lcms, znum.lcm, num.lcm, znum.abs_eq_abs_to_znum, num.to_znum, znum.abs_one, num.gcd_one_right, num.div_one], apply h end lemma divisors_lcm_ndvd_eq {d i k : znum} {ks : list znum} : k ≠ 0 → divisors_lcm (A' (atom.ndvd d i (k::ks))) = abs d := begin intro h, simp [divisors_lcm, formula.atoms_dep_0, formula.atoms, dep_0, filter, head_coeff], rw if_pos, simp [map, divisor, znum.lcms, znum.lcm, num.lcm, znum.abs_eq_abs_to_znum, num.to_znum, znum.abs_one, num.gcd_one_right, num.div_one], apply h end lemma divisors_lcm_and_eq (p q) : divisors_lcm (p ∧' q) = znum.lcm (divisors_lcm p) (divisors_lcm q) := begin apply znum.lcms_distrib, apply list.equiv.trans, apply list.map_equiv_map_of_equiv, simp [formula.atoms_dep_0, formula.atoms], apply equiv.refl, simp [map_append, formula.atoms_dep_0], apply equiv.symm union_equiv_append, end lemma divisors_lcm_or_eq (p q) : divisors_lcm (p ∨' q) = znum.lcm (divisors_lcm p) (divisors_lcm q) := begin apply znum.lcms_distrib, apply list.equiv.trans, apply list.map_equiv_map_of_equiv, simp [formula.atoms_dep_0, formula.atoms], apply equiv.refl, simp [map_append, formula.atoms_dep_0], apply equiv.symm union_equiv_append, end lemma inf_minus_mod {k z zs} : ∀ {p}, nqfree p → (has_dvd.dvd (divisors_lcm p) k) → ( (inf_minus p).eval (z % k :: zs) ↔ (inf_minus p).eval (z :: zs) ) | ⊤' _ _ := begin constructor; intro h; trivial end | ⊥' _ _ := begin constructor; intro hc; cases hc end | (A' (atom.le i [])) hf hdvd := begin simp [inf_minus, eval_le] end | (A' (atom.le i (k'::ks'))) hf hdvd := begin cases (lt_trichotomy k' 0) with hlt heqgt; [ {}, { cases heqgt with heq hgt } ], { simp [inf_minus_le_eq_of_lt hlt], trivial }, { subst heq, simp [inf_minus_le_eq_of_eq, eval_le, znum.dot_prod] }, { simp [inf_minus_le_eq_of_gt hgt], trivial }, end | (A' (atom.dvd d i [])) hf hdvd := begin simp [inf_minus, eval_dvd] end | (A' (atom.dvd d i (k::ks))) hf hdvd := begin simp [inf_minus], by_cases hkz : k = 0, { subst hkz, simp [eval_dvd, znum.dot_prod] }, { apply eval_mod_dvd, simp [divisors_lcm_dvd_eq hkz] at hdvd, rw znum.abs_dvd at hdvd, assumption } end | (A' (atom.ndvd d i [])) hf hdvd := begin simp [inf_minus, eval_ndvd] end | (A' (atom.ndvd d i (k::ks))) hf hdvd := begin simp [inf_minus], by_cases hkz : k = 0, { subst hkz, simp [eval_ndvd, znum.dot_prod] }, { apply eval_mod_ndvd, simp [divisors_lcm_ndvd_eq hkz] at hdvd, rw znum.abs_dvd at hdvd, assumption } end | (p ∧' q) hf hdvd := begin cases hf with hfp hfq, simp [inf_minus, eval_and_o], rw [@inf_minus_mod p, @inf_minus_mod q]; try {assumption}; apply dvd.trans _ hdvd; rw [divisors_lcm_and_eq], apply znum.dvd_lcm_right, apply znum.dvd_lcm_left, end | (p ∨' q) hf hdvd := begin cases hf with hfp hfq, simp [inf_minus, eval_or_o], rw [@inf_minus_mod p, @inf_minus_mod q]; try {assumption}; apply dvd.trans _ hdvd; rw [divisors_lcm_or_eq], apply znum.dvd_lcm_right, apply znum.dvd_lcm_left, end | (¬' p) hf _ := by cases hf | (∃' p) hf _ := by cases hf lemma no_lb_inf_minus {p : formula} (hf : nqfree p) (hn : formula.wf p) (z : znum) (zs) : (inf_minus p).eval (z::zs) → ∀ y, ∃ x, (x < y ∧ (inf_minus p).eval (x::zs)) := begin intros h y, have hlt : z - ((abs z + abs y + 1) * divisors_lcm p) < y, { simp [add_mul], repeat {rw (add_assoc _ _ _).symm}, rw (add_comm z), apply calc -divisors_lcm p + z + -(abs z * divisors_lcm p) + -(abs y * divisors_lcm p) < -(abs y * divisors_lcm p) : begin apply add_lt_of_neg_of_le, { rw add_assoc, apply add_neg_of_neg_of_nonpos, { rw neg_lt, apply divisors_lcm_pos hn }, { rw le_sub_iff_add_le.symm, rw [zero_sub, neg_neg], apply le_trans (le_abs_self z), rw mul_comm, apply znum.le_mul_of_pos_left (abs_nonneg _), apply divisors_lcm_pos hn } }, { apply le_refl (-(abs y * divisors_lcm p)) } end ... ≤ -(abs y) * 1: begin rw [neg_mul_eq_neg_mul], apply @mul_le_mul_of_nonpos_left _ _ _ _ (-abs y), apply @znum.add_one_le_of_lt 0 (divisors_lcm p), apply divisors_lcm_pos hn, rw neg_le, apply abs_nonneg y end ... = -(abs y): mul_one _ ... ≤ y : begin rw neg_le, apply neg_le_abs_self y end }, existsi (z - (abs z + abs y + 1) * divisors_lcm p), constructor, assumption, rw (inf_minus_mod hf (dvd_refl _)).symm, rw (inf_minus_mod hf (dvd_refl _)).symm at h, have heq : (z - (abs z + abs y + 1) * divisors_lcm p) % divisors_lcm p = z % divisors_lcm p, { rw [sub_eq_add_neg, neg_mul_eq_neg_mul], apply znum.add_mul_mod_self }, rw heq, assumption, end lemma nqfree_inf_minus_of_nqfree : ∀ {p}, nqfree p → nqfree (inf_minus p) | ⊤' h := h | ⊥' h := h | (A' a) h := begin cases a with i ks d i ks di ks; cases ks with k ks; unfold inf_minus, apply ite.rec; intro _, trivial, apply ite.rec; intro _; trivial end | (p ∧' q) h := begin cases h with h1 h2, unfold inf_minus, apply cases_and_o, trivial, repeat {apply nqfree_inf_minus_of_nqfree, assumption}, apply and.intro; apply nqfree_inf_minus_of_nqfree; assumption end | (p ∨' q) h := begin cases h with h1 h2, unfold inf_minus, apply cases_or_o, trivial, repeat {apply nqfree_inf_minus_of_nqfree, assumption}, apply and.intro; apply nqfree_inf_minus_of_nqfree; assumption end | (¬' p) h := by cases h | (∃' p) h := by cases h lemma ex_iff_inf_or_bnd (P : znum → Prop) : (∃ z, P z) ↔ ((∀ y, ∃ x, x < y ∧ P x) ∨ (∃ y, (P y ∧ ∀ x, x < y → ¬ P x))) := begin apply iff.intro; intro h1, { rw @or_iff_not_imp_left _ _ (classical.dec _), intro h2, rw (@not_forall _ _ (classical.dec _) (classical.dec_pred _)) at h2, cases h1 with w hw, cases h2 with lb hlb, simp at hlb, apply znum.exists_min_of_exists_lb hw hlb }, { cases h1 with hinf hbnd, cases (hinf 0) with z hz, existsi z, apply hz^.elim_right, cases hbnd with z hz, existsi z, apply hz^.elim_left } end lemma mod_znum.mem_range : ∀ {x y}, (0 ≠ y) → x % y ∈ znum.range y := begin intros x y hy, apply znum.mem_range', apply znum.mod_nonneg _ hy.symm, apply znum.mod_lt _ hy.symm, end lemma unified_and_iff (p q : formula) : unified (p ∧' q) ↔ (unified p ∧ unified q) := begin unfold unified, unfold formula.atoms, apply list.forall_mem_append end lemma unified_or_iff (p q : formula) : unified (p ∨' q) ↔ (unified p ∧ unified q) := begin unfold unified, unfold formula.atoms, apply list.forall_mem_append end lemma bnd_points_and_equiv {p q} : bnd_points (p ∧' q) ≃ (bnd_points p ∪ bnd_points q) := begin simp [bnd_points, formula.atoms_dep_0, dep_0, formula.atoms, filter_map_append_eq], apply equiv.symm union_equiv_append, end lemma bnd_points_or_equiv {p q} : bnd_points (p ∨' q) ≃ (bnd_points p ∪ bnd_points q) := begin simp [bnd_points, formula.atoms_dep_0, dep_0, formula.atoms, filter_map_append_eq], apply equiv.symm union_equiv_append, end lemma eval_sqe_core_iff_aux {z : znum} {zs : list znum} : ∀ {p : formula}, nqfree p → formula.wf p → unified p → ∀ {k}, 0 < k → (has_dvd.dvd (divisors_lcm p) k) → ¬ p.eval (z :: zs) → p.eval ((z + k)::zs) → ∃ iks, iks ∈ bnd_points p ∧ ∃ (d : znum), (0 ≤ d ∧ d < k ∧ z + k = (d + (prod.fst iks) - znum.dot_prod ((iks.snd)) zs)) | ⊤' hf hn hu k _ hk h1 h2 := by trivial | ⊥' hf hn hu k _ hk h1 h2 := by trivial | (A' (atom.le i ks)) hf hn hu k hkp hk h1 h2 := begin have hex : ∃ ks', ks = (1::ks'), { simp [formula.eval, atom.eval, znum.dot_prod] at *, have hlt := lt_of_lt_of_le h1 h2, cases ks with k' ks', { exfalso, cases hlt }, { cases (hu _ (or.inl rfl)) with hk' hk' hk'; simp [head_coeff] at hk', { exfalso, subst hk', simp [znum.dot_prod, lt_neg, neg_zero] at hlt, apply znum.lt_irrefl _ (lt.trans hlt hkp) }, { cases hk', { exfalso, subst hk', simp [znum.dot_prod] at hlt, apply znum.lt_irrefl _ hlt }, { subst hk', constructor, refl } } } }, cases hex with xs hxs, subst hxs, existsi (i,xs), constructor, { rw bnd_points_le_eq, apply or.inl rfl, apply zero_lt_one }, { simp, existsi (z + k - (i - (znum.dot_prod xs zs))), constructor, { simp [formula.eval, atom.eval, znum.dot_prod] at h2, rw [le_sub_iff_add_le, add_sub, sub_le_iff_le_add, zero_add, add_assoc], assumption, }, { constructor, { simp [formula.eval, atom.eval, znum.dot_prod] at h1, rw [sub_lt_iff_lt_add', add_lt_add_iff_right, lt_sub_iff_add_lt], assumption }, { simp } } } end | (A' (atom.ndvd d i ks)) hf hn hu k hkp hk h1 h2 := begin exfalso, simp [formula.eval, atom.eval, znum.dot_prod] at h1 h2, have h3 : (d ∣ i + znum.dot_prod ks (z :: zs)) ↔ (d ∣ i + znum.dot_prod ks ((z + k) :: zs)), { cases ks with x ks; simp [znum.dot_prod], by_cases hx : x = 0, { subst hx, simp }, { simp [mul_add], rw (add_assoc _ (x*z) _).symm, rw (add_assoc i _ (x*k)).symm, apply dvd_add_iff_left, apply dvd_mul_of_dvd_right, rw [divisors_lcm_ndvd_eq hx] at hk, rw znum.abs_dvd at hk, assumption } }, rw h3 at h1, apply h2 h1 end | (A' (atom.dvd d i ks)) hf hn hu k hkp hk h1 h2 := begin exfalso, simp [formula.eval, atom.eval, znum.dot_prod] at h1 h2, have h3 : (d ∣ i + znum.dot_prod ks (z :: zs)) ↔ (d ∣ i + znum.dot_prod ks ((z + k) :: zs)), { cases ks with x ks; simp [znum.dot_prod], by_cases hx : x = 0, { subst hx, simp }, { simp [mul_add], rw (add_assoc _ (x*z) _).symm, rw (add_assoc i _ (x*k)).symm, apply dvd_add_iff_left, apply dvd_mul_of_dvd_right, rw [divisors_lcm_dvd_eq hx] at hk, rw znum.abs_dvd at hk, assumption } }, rw h3 at h1, apply h1 h2 end | (p ∨' q) hf hn hu k hkp hk h1 h2 := begin simp [eval_or, not_or_distrib] at h1, simp [eval_or] at h2, cases h1 with hp hq, cases hn with hnp hnq, cases hf with hfp hfq, rw unified_or_iff at hu, cases hu with hup huq, rw divisors_lcm_or_eq at hk, have hdp := dvd.trans (znum.dvd_lcm_left _ _) hk, have hdq := dvd.trans (znum.dvd_lcm_right _ _) hk, cases h2 with h2 h2; [ {cases (@eval_sqe_core_iff_aux p _ _ _ _ hkp _ _ _) with iks hiks}, {cases (@eval_sqe_core_iff_aux q _ _ _ _ hkp _ _ _) with iks hiks} ]; try {assumption}; `[cases hiks with hm h, existsi iks, apply and.intro, rw mem_iff_mem_of_equiv (bnd_points_or_equiv) ], apply mem_union_left hm, assumption, apply mem_union_right _ hm, assumption end | (p ∧' q) hf hn hu k hkp hk h1 h2 := begin rw [eval_and] at h1, rw [@not_and_distrib' _ _ (classical.dec _)] at h1, simp [eval_and] at h2, cases h2 with hp hq, cases hn with hnp hnq, cases hf with hfp hfq, rw unified_and_iff at hu, cases hu with hup huq, rw divisors_lcm_and_eq at hk, have hdp := dvd.trans (znum.dvd_lcm_left _ _) hk, have hdq := dvd.trans (znum.dvd_lcm_right _ _) hk, cases h1 with h1 h1; [ {cases (@eval_sqe_core_iff_aux p _ _ _ _ hkp _ _ _) with iks hiks}, {cases (@eval_sqe_core_iff_aux q _ _ _ _ hkp _ _ _) with iks hiks} ]; try {assumption}; `[ cases hiks with hm h, existsi iks, apply and.intro, rw mem_iff_mem_of_equiv (bnd_points_and_equiv) ], apply mem_union_left hm, assumption, apply mem_union_right _ hm, assumption end | (¬' p) hf hn hu k _ hk h1 h2 := by cases hf | (∃' p) hf hn hu k _ hk h1 h2 := by cases hf lemma eval_sqe_core_iff : ∀ (p : formula), nqfree p → formula.wf p → unified p → ∀ (bs : list znum), (sqe_core p).eval bs ↔ ∃ (b : znum), p.eval (b :: bs) := begin intros p hf hn hu zs, constructor; intro h, { simp [sqe_core, sqe_inf, sqe_bnd, eval_or_o, eval_disj_map] at h, cases h with h h; cases h with z hz, { cases hz with hz1 hz2, rw eval_subst_iff at hz2, { simp [znum.nil_dot_prod, @add_zero znum] at hz2, cases (inf_minus_prsv zs p) with lb hlb, cases (no_lb_inf_minus hf hn z zs hz2 lb) with x hx, cases hx with hx1 hx2, rw hlb _ hx1 at hx2, existsi x, assumption }, { apply nqfree_inf_minus_of_nqfree hf } }, { cases hz with zs hzs, cases hzs with hzs1 hzs2, cases hzs2 with k hk, cases hk with hk1 hk2, rw (eval_subst_iff hf) at hk2, constructor, apply hk2, } }, { simp [sqe_core, eval_or_o], rewrite ex_iff_inf_or_bnd at h, cases h with h h, { apply or.inl, simp [sqe_inf], rw eval_disj_map, have hw : ∃ w, formula.eval (w :: zs) (inf_minus p), { cases (inf_minus_prsv zs p) with lb hlb, cases h lb with w h, cases h with h1 h2, existsi w, rw (hlb _ h1), assumption }, cases hw with w hw, have hwm : formula.eval ((w % divisors_lcm p)::zs) (inf_minus p), { rw inf_minus_mod; try {assumption}, apply dvd_refl }, existsi (w % divisors_lcm p), constructor, { apply mod_znum.mem_range, apply ne.symm, apply znum.nonzero_of_pos, apply divisors_lcm_pos hn }, { rw eval_subst_iff, simp [znum.dot_prod_nil, @zero_add znum], apply hwm, apply nqfree_inf_minus_of_nqfree hf } }, { cases h with lb hlb, cases hlb with hlb1 hlb2, apply or.inr, have h := @eval_sqe_core_iff_aux (lb - (divisors_lcm p)) zs p hf hn hu (divisors_lcm p) (divisors_lcm_pos hn) (dvd_refl _) (begin apply hlb2, rewrite sub_lt_self_iff, apply divisors_lcm_pos hn, end) (begin simp, apply hlb1 end), cases h with iks h, cases h with hiks h, cases h with k' h, cases h with h1 h, cases h with h2 h3, simp at h3, subst h3, simp [sqe_bnd, eval_disj_map], existsi iks.fst, existsi iks.snd, apply and.intro, { cases iks, simp, apply hiks }, { existsi k', constructor, { apply znum.mem_range h1 h2 }, { rw [eval_subst_iff, znum.map_neg_dot_prod], rw (add_comm iks.fst), rw add_assoc, apply hlb1, apply hf } } } } end
If you are a patient using oxygen concentrator (portable oxygen concentrator) or using any kind of respiratory equipment to help you breathe, then you should try and use our super 7 foot long soft nasal cannulas (oxygen cannulas). Buy high-quality extra super soft yet cheap & economical oxygen nasal cannula from us now. Indeed, there are many companies selling nasal cannula and they make it look cheap and economical price. However, the quality of such cheap nasal cannula (cheap oxygen cannula) is not so good and you end up having the irritational sensation which will make patient using oxygen concentrator (portable oxygen concentrator) uncomfortable. Try our high quality and yet economical nasal cannula now. Our oxygen nasal cannulas are super cheap and economical however at the same time, they are extra soft, high quality and comfortable.
[GOAL] A B : ModuleCat ℤ f : (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj A ⟶ (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj B n : ℤ x : ↑A ⊢ AddHom.toFun { toFun := ↑f, map_add' := (_ : ∀ (a b : ↑A), ↑(let_fun this := f; this) (a + b) = ↑(let_fun this := f; this) a + ↑(let_fun this := f; this) b) } (n • x) = ↑(RingHom.id ℤ) n • AddHom.toFun { toFun := ↑f, map_add' := (_ : ∀ (a b : ↑A), ↑(let_fun this := f; this) (a + b) = ↑(let_fun this := f; this) a + ↑(let_fun this := f; this) b) } x [PROOFSTEP] convert AddMonoidHom.map_zsmul (show A.carrier →+ B.carrier from f) x n [GOAL] case h.e'_2.h.e'_1.h.e'_4.h.e'_3 A B : ModuleCat ℤ f : (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj A ⟶ (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj B n : ℤ x : ↑A ⊢ SMulZeroClass.toSMul = SubNegMonoid.SMulInt [PROOFSTEP] ext [GOAL] case h.e'_3.h.e'_4.h.e'_3 A B : ModuleCat ℤ f : (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj A ⟶ (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj B n : ℤ x : ↑A ⊢ SMulZeroClass.toSMul = SubNegMonoid.SMulInt [PROOFSTEP] ext [GOAL] case h.e'_2.h.e'_1.h.e'_4.h.e'_3.smul.h.h A B : ModuleCat ℤ f : (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj A ⟶ (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj B n : ℤ x : ↑A x✝¹ : ℤ x✝ : ↑A ⊢ SMul.smul x✝¹ x✝ = SMul.smul x✝¹ x✝ [PROOFSTEP] apply int_smul_eq_zsmul [GOAL] case h.e'_3.h.e'_4.h.e'_3.smul.h.h A B : ModuleCat ℤ f : (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj A ⟶ (forget₂ (ModuleCat ℤ) AddCommGroupCat).obj B n : ℤ x : ↑A x✝¹ : (fun x => ℤ) n x✝ : ↑B ⊢ SMul.smul x✝¹ x✝ = SMul.smul x✝¹ x✝ [PROOFSTEP] apply int_smul_eq_zsmul
import os import numpy as np from sos.data_generation import generate from config.schedule import test_schedule if __name__ == "__main__": for system, _, _, N, std, _, _ in test_schedule: files = os.listdir('./data/experts') filename = system.name + str(N) + '.npz' if any(filename in s for s in files): print('File - ' + filename + ' - already exists.') pass else: data = generate(system.states, system.K @ system.Z, N, std=std) np.savez('data/experts/' + filename, **data)
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl ! This file was ported from Lean 3 source module data.set.countable ! leanprover-community/mathlib commit 1f0096e6caa61e9c849ec2adbd227e960e9dff58 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Set.Finite import Mathlib.Data.Countable.Basic import Mathlib.Logic.Equiv.List /-! # Countable sets -/ noncomputable section open Function Set Encodable Classical universe u v w x variable {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} namespace Set /-- A set is countable if there exists an encoding of the set into the natural numbers. An encoding is an injection with a partial inverse, which can be viewed as a constructive analogue of countability. (For the most part, theorems about `Countable` will be classical and `Encodable` will be constructive.) -/ protected def Countable (s : Set α) : Prop := Nonempty (Encodable s) #align set.countable Set.Countable @[simp] theorem countable_coe_iff {s : Set α} : Countable s ↔ s.Countable := Encodable.nonempty_encodable.symm #align set.countable_coe_iff Set.countable_coe_iff /-- Prove `Set.Countable` from a `Countable` instance on the subtype. -/ theorem to_countable (s : Set α) [Countable s] : s.Countable := countable_coe_iff.mp ‹_› #align set.to_countable Set.to_countable /-- Restate `Set.Countable` as a `Countable` instance. -/ alias countable_coe_iff ↔ _root_.Countable.to_set Countable.to_subtype #align countable.to_set Countable.to_set #align set.countable.to_subtype Set.Countable.to_subtype protected theorem countable_iff_exists_injective {s : Set α} : s.Countable ↔ ∃ f : s → ℕ, Injective f := countable_coe_iff.symm.trans (countable_iff_exists_injective s) #align set.countable_iff_exists_injective Set.countable_iff_exists_injective /-- A set `s : Set α` is countable if and only if there exists a function `α → ℕ` injective on `s`. -/ theorem countable_iff_exists_injOn {s : Set α} : s.Countable ↔ ∃ f : α → ℕ, InjOn f s := Set.countable_iff_exists_injective.trans exists_injOn_iff_injective.symm #align set.countable_iff_exists_inj_on Set.countable_iff_exists_injOn /-- Convert `Set.Countable s` to `Encodable s` (noncomputable). -/ protected def Countable.toEncodable {s : Set α} : s.Countable → Encodable s := Classical.choice #align set.countable.to_encodable Set.Countable.toEncodable section Enumerate /-- Noncomputably enumerate elements in a set. The `default` value is used to extend the domain to all of `ℕ`. -/ def enumerateCountable {s : Set α} (h : s.Countable) (default : α) : ℕ → α := fun n => match @Encodable.decode s h.toEncodable n with | some y => y | none => default #align set.enumerate_countable Set.enumerateCountable theorem subset_range_enumerate {s : Set α} (h : s.Countable) (default : α) : s ⊆ range (enumerateCountable h default) := fun x hx => ⟨@Encodable.encode s h.toEncodable ⟨x, hx⟩, by letI := h.toEncodable simp [enumerateCountable, Encodable.encodek]⟩ #align set.subset_range_enumerate Set.subset_range_enumerate end Enumerate theorem Countable.mono {s₁ s₂ : Set α} (h : s₁ ⊆ s₂) : s₂.Countable → s₁.Countable | ⟨H⟩ => ⟨@ofInj _ _ H _ (embeddingOfSubset _ _ h).2⟩ #align set.countable.mono Set.Countable.mono theorem countable_range [Countable ι] (f : ι → β) : (range f).Countable := surjective_onto_range.countable.to_set #align set.countable_range Set.countable_range theorem countable_iff_exists_subset_range [Nonempty α] {s : Set α} : s.Countable ↔ ∃ f : ℕ → α, s ⊆ range f := ⟨fun h => by inhabit α exact ⟨enumerateCountable h default, subset_range_enumerate _ _⟩, fun ⟨f, hsf⟩ => (countable_range f).mono hsf⟩ #align set.countable_iff_exists_subset_range Set.countable_iff_exists_subset_range /-- A non-empty set is countable iff there exists a surjection from the natural numbers onto the subtype induced by the set. -/ protected theorem countable_iff_exists_surjective {s : Set α} (hs : s.Nonempty) : s.Countable ↔ ∃ f : ℕ → s, Surjective f := countable_coe_iff.symm.trans <| @countable_iff_exists_surjective s hs.to_subtype #align set.countable_iff_exists_surjective Set.countable_iff_exists_surjective alias Set.countable_iff_exists_surjective ↔ Countable.exists_surjective _ #align set.countable.exists_surjective Set.Countable.exists_surjective theorem countable_univ [Countable α] : (univ : Set α).Countable := to_countable univ #align set.countable_univ Set.countable_univ /-- If `s : Set α` is a nonempty countable set, then there exists a map `f : ℕ → α` such that `s = range f`. -/ theorem Countable.exists_eq_range {s : Set α} (hc : s.Countable) (hs : s.Nonempty) : ∃ f : ℕ → α, s = range f := by rcases hc.exists_surjective hs with ⟨f, hf⟩ refine' ⟨(↑) ∘ f, _⟩ rw [hf.range_comp, Subtype.range_coe] #align set.countable.exists_eq_range Set.Countable.exists_eq_range @[simp] theorem countable_empty : (∅ : Set α).Countable := to_countable _ #align set.countable_empty Set.countable_empty @[simp] theorem countable_singleton (a : α) : ({a} : Set α).Countable := to_countable _ #align set.countable_singleton Set.countable_singleton theorem Countable.image {s : Set α} (hs : s.Countable) (f : α → β) : (f '' s).Countable := by rw [image_eq_range] haveI := hs.to_subtype apply countable_range #align set.countable.image Set.Countable.image theorem MapsTo.countable_of_injOn {s : Set α} {t : Set β} {f : α → β} (hf : MapsTo f s t) (hf' : InjOn f s) (ht : t.Countable) : s.Countable := have : Injective (hf.restrict f s t) := (injOn_iff_injective.1 hf').codRestrict _ ⟨@Encodable.ofInj _ _ ht.toEncodable _ this⟩ #align set.maps_to.countable_of_inj_on Set.MapsTo.countable_of_injOn theorem Countable.preimage_of_injOn {s : Set β} (hs : s.Countable) {f : α → β} (hf : InjOn f (f ⁻¹' s)) : (f ⁻¹' s).Countable := (mapsTo_preimage f s).countable_of_injOn hf hs #align set.countable.preimage_of_inj_on Set.Countable.preimage_of_injOn protected theorem Countable.preimage {s : Set β} (hs : s.Countable) {f : α → β} (hf : Injective f) : (f ⁻¹' s).Countable := hs.preimage_of_injOn (hf.injOn _) #align set.countable.preimage Set.Countable.preimage theorem exists_seq_supᵢ_eq_top_iff_countable [CompleteLattice α] {p : α → Prop} (h : ∃ x, p x) : (∃ s : ℕ → α, (∀ n, p (s n)) ∧ (⨆ n, s n) = ⊤) ↔ ∃ S : Set α, S.Countable ∧ (∀ s ∈ S, p s) ∧ supₛ S = ⊤ := by constructor · rintro ⟨s, hps, hs⟩ refine' ⟨range s, countable_range s, forall_range_iff.2 hps, _⟩ rwa [supₛ_range] · rintro ⟨S, hSc, hps, hS⟩ rcases eq_empty_or_nonempty S with (rfl | hne) · rw [supₛ_empty] at hS haveI := subsingleton_of_bot_eq_top hS rcases h with ⟨x, hx⟩ exact ⟨fun _ => x, fun _ => hx, Subsingleton.elim _ _⟩ · rcases(Set.countable_iff_exists_surjective hne).1 hSc with ⟨s, hs⟩ refine' ⟨fun n => s n, fun n => hps _ (s n).coe_prop, _⟩ rwa [hs.supᵢ_comp, ← supₛ_eq_supᵢ'] #align set.exists_seq_supr_eq_top_iff_countable Set.exists_seq_supᵢ_eq_top_iff_countable theorem exists_seq_cover_iff_countable {p : Set α → Prop} (h : ∃ s, p s) : (∃ s : ℕ → Set α, (∀ n, p (s n)) ∧ (⋃ n, s n) = univ) ↔ ∃ S : Set (Set α), S.Countable ∧ (∀ s ∈ S, p s) ∧ ⋃₀ S = univ := exists_seq_supᵢ_eq_top_iff_countable h #align set.exists_seq_cover_iff_countable Set.exists_seq_cover_iff_countable theorem countable_of_injective_of_countable_image {s : Set α} {f : α → β} (hf : InjOn f s) (hs : (f '' s).Countable) : s.Countable := (mapsTo_image _ _).countable_of_injOn hf hs #align set.countable_of_injective_of_countable_image Set.countable_of_injective_of_countable_image theorem countable_unionᵢ {t : ι → Set α} [Countable ι] (ht : ∀ i, (t i).Countable) : (⋃ i, t i).Countable := by haveI := fun a => (ht a).to_subtype rw [unionᵢ_eq_range_psigma] apply countable_range #align set.countable_Union Set.countable_unionᵢ @[simp] theorem countable_unionᵢ_iff [Countable ι] {t : ι → Set α} : (⋃ i, t i).Countable ↔ ∀ i, (t i).Countable := ⟨fun h _ => h.mono <| subset_unionᵢ _ _, countable_unionᵢ⟩ #align set.countable_Union_iff Set.countable_unionᵢ_iff theorem Countable.bunionᵢ_iff {s : Set α} {t : ∀ a ∈ s, Set β} (hs : s.Countable) : (⋃ a ∈ s, t a ‹_›).Countable ↔ ∀ a (ha : a ∈ s), (t a ha).Countable := by haveI := hs.to_subtype rw [bunionᵢ_eq_unionᵢ, countable_unionᵢ_iff, SetCoe.forall'] #align set.countable.bUnion_iff Set.Countable.bunionᵢ_iff theorem Countable.unionₛ_iff {s : Set (Set α)} (hs : s.Countable) : (⋃₀ s).Countable ↔ ∀ a ∈ s, (a : _).Countable := by rw [unionₛ_eq_bunionᵢ, hs.bunionᵢ_iff] #align set.countable.sUnion_iff Set.Countable.unionₛ_iff alias Countable.bunionᵢ_iff ↔ _ Countable.bunionᵢ #align set.countable.bUnion Set.Countable.bunionᵢ alias Countable.unionₛ_iff ↔ _ Countable.unionₛ #align set.countable.sUnion Set.Countable.unionₛ @[simp] theorem countable_union {s t : Set α} : (s ∪ t).Countable ↔ s.Countable ∧ t.Countable := by simp [union_eq_unionᵢ, and_comm] #align set.countable_union Set.countable_union theorem Countable.union {s t : Set α} (hs : s.Countable) (ht : t.Countable) : (s ∪ t).Countable := countable_union.2 ⟨hs, ht⟩ #align set.countable.union Set.Countable.union theorem Countable.of_diff {s t : Set α} (h : (s \ t).Countable) (ht : t.Countable) : s.Countable := (h.union ht).mono (subset_diff_union _ _) @[simp] theorem Countable.insert {s : Set α} (a : α) (h : s.Countable) : (insert a s).Countable := countable_insert.2 h #align set.countable.insert Set.Countable.insert theorem Finite.countable {s : Set α} : s.Finite → s.Countable | ⟨_⟩ => Trunc.nonempty (Fintype.truncEncodable s) #align set.finite.countable Set.Finite.countable @[nontriviality] theorem Countable.of_subsingleton [Subsingleton α] (s : Set α) : s.Countable := (Finite.of_subsingleton s).countable #align set.countable.of_subsingleton Set.Countable.of_subsingleton theorem Subsingleton.countable {s : Set α} (hs : s.Subsingleton) : s.Countable := hs.finite.countable #align set.subsingleton.countable Set.Subsingleton.countable theorem countable_isTop (α : Type _) [PartialOrder α] : { x : α | IsTop x }.Countable := (finite_isTop α).countable #align set.countable_is_top Set.countable_isTop theorem countable_isBot (α : Type _) [PartialOrder α] : { x : α | IsBot x }.Countable := (finite_isBot α).countable #align set.countable_is_bot Set.countable_isBot /-- The set of finite subsets of a countable set is countable. -/ theorem countable_setOf_finite_subset {s : Set α} (hs : s.Countable) : { t | Set.Finite t ∧ t ⊆ s }.Countable := by haveI := hs.to_subtype refine' Countable.mono _ (countable_range fun t : Finset s => Subtype.val '' (t : Set s)) rintro t ⟨ht, hts⟩ lift t to Set s using hts lift t to Finset s using ht.of_finite_image (Subtype.val_injective.injOn _) exact mem_range_self _ #align set.countable_set_of_finite_subset Set.countable_setOf_finite_subset theorem countable_univ_pi {π : α → Type _} [Finite α] {s : ∀ a, Set (π a)} (hs : ∀ a, (s a).Countable) : (pi univ s).Countable := haveI := fun a => (hs a).to_subtype (Countable.of_equiv _ (Equiv.Set.univPi s).symm).to_set #align set.countable_univ_pi Set.countable_univ_pi theorem countable_pi {π : α → Type _} [Finite α] {s : ∀ a, Set (π a)} (hs : ∀ a, (s a).Countable) : { f : ∀ a, π a | ∀ a, f a ∈ s a }.Countable := by simpa only [← mem_univ_pi] using countable_univ_pi hs #align set.countable_pi Set.countable_pi protected theorem Countable.prod {s : Set α} {t : Set β} (hs : s.Countable) (ht : t.Countable) : Set.Countable (s ×ˢ t) := by haveI : Countable s := hs.to_subtype haveI : Countable t := ht.to_subtype exact (Countable.of_equiv _ <| (Equiv.Set.prod _ _).symm).to_set #align set.countable.prod Set.Countable.prod theorem Countable.image2 {s : Set α} {t : Set β} (hs : s.Countable) (ht : t.Countable) (f : α → β → γ) : (image2 f s t).Countable := by rw [← image_prod] exact (hs.prod ht).image _ #align set.countable.image2 Set.Countable.image2 end Set theorem Finset.countable_toSet (s : Finset α) : Set.Countable (↑s : Set α) := s.finite_toSet.countable #align finset.countable_to_set Finset.countable_toSet
REBOL [ require: [ rs-project 'utf8-cp1250 rs-project 'memory-tools ] note: {To find libmagickwand.so location on linux: find / -iname libmagickwand*} usage: [ probe get-image-size %/d/testx.jpg ] ] unless value? 'with [ with: func[obj body][do bind body obj] ] ctx-imagick: context [ unless value? 'debug [ debug: func[msg /print][system/words/print msg] ] ;routine placeholders: MagickWandGenesis: MagickWandTerminus: NewMagickWand: MagickSetOption: MagickQueryConfigureOptions: MagickQueryFonts: MagickPingImage: MagickPingImageBlob: MagickReadImage: MagickReadImageBlob: MagickAddImage: MagickResizeImage: MagickCropImage: MagickWriteImage: MagickWriteImages: ClearMagickWand: CloneMagickWand: DestroyMagickWand: MagickGetException: MagickRelinquishMemory: MagickNewImage: MagickUnsharpMaskImage: MagickSharpenImage: MagickBlurImage: MagickCharcoalImage: MagickTrimImage: MagickGetImageHeight: MagickGetImageWidth: MagickGetImageFormat: MagickSetImageFormat: MagickIdentifyImage: MagickMergeImageLayers: MagickImportImagePixels: MagickExportImagePixels: MagickSetImageCompression: MagickSetImageCompressionQuality: MagickGetImageType: MagickSetImageType: MagickSetImageMatte: MagickSetImageMatteColor: MagickSetImageDepth: MagickGetImageDepth: MagickSetImageBackgroundColor: MagickGetImageBackgroundColor: ClearPixelWand: DestroyPixelWand: NewPixelWand: PixelSetAlpha: PixelGetAlpha: PixelSetColor: PixelSetBlack: PixelGetBlack: PixelGetColorAsString: MagickSetImagePage: none lib_ImageMagickWand: none RedChannel: GrayChannel: CyanChannel: 1 GreenChannel: MagentaChannel: 2 BlueChannel: YellowChannel: 4 AlphaChannel: OpacityChannel: 8 BlackChannel: IndexChannel: 32 AllChannels: 255 *wand: *pixel: none CompressionTypes: [ Undefined No BZip DXT1 DXT3 DXT5 Fax Group4 JPEG JPEG2000 LosslessJPEG LZW RLE Zip ] ctJPEG: 8 ilm_MergeLayer: 13 ilm_FlattenLayer: 14 init-routines: has [make-routine try][ print ["INIT iMagick!"] try: get in system/words 'try either system/version/4 = 3 [ any [ not error? try [lib_ImageMagickWand: load/library dir_imagemagick/CORE_RL_wand_.dll] not error? try [lib_ImageMagickWand: load/library %CORE_RL_wand_.dll] ] ][ any [ not error? try [lib_ImageMagickWand: load/library dir_imagemagick/libMagickWand.so] not error? try [lib_ImageMagickWand: load/library %/usr/lib/libMagickWand.so] ] ] if none? lib_ImageMagickWand [ make error! "IMAGICK: Unable to load the library!" ] make-routine: func[routine specs /local r][ either error? try [ r: make routine! bind specs '*wand lib_ImageMagickWand routine ][ debug/print ["IMAGICK: Cannot create routine:" routine] none ][ :r ] ] MagickWandGenesis: make-routine "MagickWandGenesis" [ "Initializes the MagickWand environment" ] MagickWandTerminus: make-routine "MagickWandTerminus" [ "Terminates the MagickWand environment" ] NewMagickWand: make-routine "NewMagickWand" [ {Returns a wand required for all other methods in the API.} return: [integer!] ] MagickSetOption: make-routine "MagickSetOption" [ {associates one or options with the wand (.e.g MagickSetOption wand "jpeg:perserve" "yes").} *wand [integer!] *key [string!] *value [string!] return: [integer!] ] MagickQueryConfigureOptions: make-routine "MagickQueryConfigureOptions" [ {returns any configure options that match the specified pattern (e.g. "*" for all)} *pattern [string!] *number_options [integer!] return: [string!] ] MagickQueryFonts: make-routine "MagickQueryFonts" [ {returns any font that match the specified pattern (e.g. "*" for all).} *pattern [string!] *number_options [integer!] return: [string!] ] MagickPingImage: make-routine "MagickPingImage" [ "Returns the image width, height, size, and format." *wand [integer!] filename [string!] return: [integer!] ] MagickPingImageBlob: make-routine "MagickPingImageBlob" [ "pings an image or image sequence from a blob." *wand [integer!] *blob [integer!] length [integer!] return: [integer!] ] MagickReadImage: make-routine "MagickReadImage" [ "Reads an image or image sequence." *wand [integer!] filename [string!] return: [integer!] ] MagickReadImageBlob: make-routine "MagickReadImageBlob" [ "reads an image or image sequence from a blob." *wand [integer!] *blob [integer!] length [integer!] return: [integer!] ] MagickAddImage: make-routine "MagickAddImage" [ "adds the specified images at the current image location" *wand [integer!] *add_wand [integer!] return: [integer!] ] MagickResizeImage: make-routine "MagickResizeImage" [ {Associates the next image in the image list with a magick wand.} *wand [integer!] width [integer!] height [integer!] filter [integer!] blur [decimal!] "the blur factor where > 1 is blurry, < 1 is sharp." return: [integer!] ] MagickCropImage: make-routine "MagickCropImage" [ "extracts a region of the image" *wand [integer!] width [integer!] height [integer!] x [integer!] y [integer!] return: [integer!] ] MagickWriteImage: make-routine "MagickWriteImage" [ "Writes an image to the specified filename." *wand [integer!] filename [string!] return: [integer!] ] MagickWriteImages: make-routine "MagickWriteImages" [ "Writes an image to the specified filename." *wand [integer!] filename [string!] return: [integer!] ] ClearMagickWand: make-routine "ClearMagickWand" [ "Clears resources associated with the wand." *wand [integer!] ] CloneMagickWand: make-routine "CloneMagickWand" [ "Makes an exact copy of the specified wand." *wand [integer!] return: [integer!] ] DestroyMagickWand: make-routine "DestroyMagickWand" [ "Deallocates memory associated with an MagickWand." *wand [integer!] ] MagickGetException: make-routine "MagickGetException" [ *wand [integer!] *severity [struct! [i [int]]] return: [integer!] ] MagickRelinquishMemory: make-routine "MagickRelinquishMemory" [ "Relinquishes memory resources" *resource [integer!] return: [long] ] MagickNewImage: make-routine "MagickNewImage" [ {Adds a blank image canvas of the specified size and background color to the wand.} *wand [integer!] columns [integer!] rows [integer!] *pixelWand [integer!] return: [integer!] ] MagickUnsharpMaskImage: make-routine "MagickUnsharpMaskImage" [ {sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and UnsharpMaskImage() selects a suitable radius for you.} *wand [integer!] radius [decimal!] {of the Gaussian, in pixels, not counting the center pixel.} sigma [decimal!] "the standard deviation of the Gaussian, in pixels." amount [decimal!] {the percentage of the difference between the original and the blur image that is added back into the original.} threshold [decimal!] {the threshold in pixels needed to apply the diffence amount.} return: [integer!] ] MagickSharpenImage: make-routine "MagickSharpenImage" [ "sharpens an image." *wand [integer!] radius [decimal!] {of the Gaussian, in pixels, not counting the center pixel.} sigma [decimal!] "the standard deviation of the Gaussian, in pixels." return: [integer!] ] MagickBlurImage: make-routine "MagickBlurImage" [ "blurs an image." *wand [integer!] radius [decimal!] {of the Gaussian, in pixels, not counting the center pixel.} sigma [decimal!] "the standard deviation of the Gaussian, in pixels." return: [integer!] ] MagickCharcoalImage: make-routine "MagickCharcoalImage" [ "Simulates a charcoal drawing." *wand [integer!] radius [double] {of the Gaussian, in pixels, not counting the center pixel.} sigma [double] "the standard deviation of the Gaussian, in pixels." return: [integer!] ] MagickTrimImage: make-routine "MagickTrimImage" [ "remove edges that are the background color from the image" *wand [integer!] fuzz [double] "defines how much tolerance is acceptable to consider two colors as the same" return: [integer!] "*background_color PixelWand" ] MagickGetImageHeight: make-routine "MagickGetImageHeight" [ "Returns the image height." *wand [integer!] return: [integer!] ] MagickGetImageWidth: make-routine "MagickGetImageWidth" [ "Returns the image width." *wand [integer!] return: [integer!] ] MagickGetImageFormat: make-routine "MagickGetImageFormat" [ {Returns the format of a particular image in a sequence.} *wand [integer!] return: [string!] ] MagickSetImageFormat: make-routine "MagickSetImageFormat" [ {sets the format of a particular image in a sequence} *wand [integer!] format [string!] return: [integer!] ] MagickIdentifyImage: make-routine "MagickIdentifyImage" [ *wand [integer!] return: [string!] ] MagickMergeImageLayers: make-routine "MagickMergeImageLayers" [ {composes all the image layers from the current given image onward to produce a single image of the merged layers.} *wand [integer!] method [integer!] return: [integer!] ] MagickImportImagePixels: make-routine "MagickImportImagePixels" [ *wand [integer!] x [integer!] y [integer!] columns [integer!] rows [integer!] map [string!] storage [integer!] *pixels [integer!] return: [integer!] ] MagickExportImagePixels: make-routine "MagickExportImagePixels" [ {extracts pixel data from an image and returns it to you} *wand [integer!] x [integer!] y [integer!] columns [integer!] rows [integer!] map [string!] storage [integer!] *pixels [integer!] return: [integer!] ] MagickSetImageCompression: make-routine "MagickSetImageCompression" [ "sets the image compression type" *wand [integer!] type [integer!] return: [integer!] ] MagickSetImageCompressionQuality: make-routine "MagickSetImageCompressionQuality" [ "sets the image compression quality" *wand [integer!] quality [integer!] return: [integer!] ] MagickGetImageType: make-routine "MagickGetImageType" [ "gets the image type" *wand [integer!] return: [integer!] ] MagickSetImageType: make-routine "MagickSetImageType" [ "sets the image type" *wand [integer!] image_type [integer!] "the image type: UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, or OptimizeType" return: [integer!] ] MagickSetImageMatte: make-routine "MagickSetImageMatte" [ "sets the image matte channel" *wand [integer!] *matte [integer!] "(1/0) - Set to MagickTrue to enable the image matte channel otherwise MagickFalse." return: [integer!] ] MagickSetImageMatteColor: make-routine "MagickSetImageMatteColor" [ "sets the image matte color" *wand [integer!] *matte [integer!] "matte pixel wand" return: [integer!] ] MagickSetImageDepth: make-routine "MagickSetImageDepth" [ "sets the image depth" *wand [integer!] depth [integer!] "the image depth in bits: 8, 16, or 32." return: [integer!] ] MagickGetImageDepth: make-routine "MagickGetImageDepth" [ "gets the image depth." *wand [integer!] return: [integer!] ] MagickSetImageBackgroundColor: make-routine "MagickSetImageBackgroundColor" [ "sets the image background color" *wand [integer!] *background_color [integer!] "the background pixel wand." return: [integer!] "*background_color PixelWand" ] MagickGetImageBackgroundColor: make-routine "MagickGetImageBackgroundColor" [ "returns the image background color" *wand [integer!] return: [integer!] "*background_color PixelWand" ] ClearPixelWand: make-routine "ClearPixelWand" [ "clears resources associated with the wand." *PixelWand [integer!] ] DestroyPixelWand: make-routine "DestroyPixelWand" [ "makes an exact copy of the specified wand." *PixelWand [integer!] return: [integer!] ] NewPixelWand: make-routine "NewPixelWand" [ "returns a new pixel wand." return: [integer!] ] PixelSetAlpha: make-routine "PixelSetAlpha" [ "sets the normalized alpha color of the pixel wand" *PixelWand [integer!] alpha [decimal!] "level of transparency: 1.0 is fully opaque and 0.0 is fully transparent" ] PixelGetAlpha: make-routine "PixelSetAlpha" [ "returns the normalized alpha color of the pixel wand" *PixelWand [integer!] return: [decimal!] ] PixelSetColor: make-routine "PixelSetColor" [ {sets the color of the pixel wand with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.)} *PixelWand [integer!] color [string!] "pixel wand color" return: [integer!] ] PixelSetBlack: make-routine "PixelGetBlack" [ {sets the normalized black color of the pixel wand} *PixelWand [integer!] black [double] ] PixelGetBlack: make-routine "PixelGetBlack" [ {returns the normalized black color of the pixel wand} *PixelWand [integer!] return: [double] ] PixelGetColorAsString: make-routine "PixelGetBlack" [ {returnsd the color of the pixel wand as a string.} *PixelWand [integer!] return: [string!] ] MagickSetImagePage: make-routine "MagickSetImagePage" [ "sets the page geometry of the image." *wand [integer!] width [integer!] height [integer!] x [integer!] y [integer!] return: [integer!] ] unset 'make-routine ctx-imagick/init-routines: none ] ;## Helper functions Exception: make struct! [Severity [integer!]] none s_int: make struct! [value [integer!]] none s_str: make struct! [value [string! ]] none address?: func [ {get the address of a string} s [series!] ][ s_str/value: s change third s_int third s_str s_int/value ] ptr-to-string: func[ {get string from pointer} ptr [integer!] /local m ][ s_int/value: ptr change third s_str third s_int s_str/value ] ;### image-save set 'image-save func[ filename [file! ] image [image!] /local rgba width height *wand p desc errmsg ][ rgba: to-binary image width: image/size/x height: image/size/y if #"/" <> first filename [ insert filename what-dir ] start *pixel: NewPixelWand unless all [ not zero? MagickNewImage *wand width height *pixel not zero? probe MagickImportImagePixels *wand 0 0 width height "BGRO" 1 address? rgba not zero? MagickWriteImages *wand to-local-file filename ][ errmsg: reform [ Exception/Severity "=" ptr-to-string desc: MagickGetException *wand Exception ] MagickRelinquishMemory desc end make error! errmsg ] ClearPixelWand *pixel DestroyPixelWand *pixel end filename ] set 'image-load func [ "Load an image using Imagemagick's library" imgsrc [url! file! string! binary!] "Image file to load or raw binary data" /local tmp *wand width height errmsg ][ MagickWandGenesis *wand: NewMagickWand unless any [url? imgsrc binary? imgsrc] [ if #"/" <> first imgsrc: to-rebol-file imgsrc [ insert imgsrc what-dir ] ] unless all [ not zero? case [ url? imgsrc [ tmp: read/binary imgsrc MagickReadImageBlob *wand address? tmp length? tmp ] binary? imgsrc [ MagickReadImageBlob *wand address? imgsrc length? imgsrc ] true [ MagickReadImage *wand to-local-file imgsrc ] ] width: MagickGetImageWidth *wand height: MagickGetImageHeight *wand tmp: make image! as-pair width height not zero? MagickExportImagePixels *wand 0 0 width height "RGBO" 1 address? tmp ][ errmsg: reform [ Exception/Severity "=" ptr-to-string tmp: MagickGetException *wand Exception ] MagickRelinquishMemory tmp MagickWandTerminus make error! errmsg ] ClearMagickWand *wand DestroyMagickWand *wand MagickWandTerminus tmp ] set 'image-get-pixels func [ img [binary! file! string!] map [string!] "This string reflects the expected ordering of the pixel array. It can be any combination or order of R = red, G = green, B = blue, A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale), P = pad." ;storage [word!] "CharPixel, DoublePixel, FloatPixel, IntegerPixel, LongPixel, QuantumPixel, or ShortPixel" /local width height bytes bin ][ start either binary? img [ try MagickReadImageBlob *wand address? img length? img ][ try MagickReadImage *wand utf8/encode to-local-file img ] width: MagickGetImageWidth *wand height: MagickGetImageHeight *wand bin: make binary! bytes: (width * height * length? map) insert/dup bin #{00} bytes print ["image-get-pixels:" width height mold map length? bin] try MagickExportImagePixels *wand 0 0 width height map 1 address? bin end print length? bin bin ] crop-image: func[src trg width height ofsx ofsy ][ if #"/" <> first src: to-rebol-file src [insert src what-dir] if #"/" <> first trg: to-rebol-file trg [insert trg what-dir] start try MagickReadImage *wand as-string utf8/encode to-local-file src try MagickSetImagePage *wand 0 0 0 0 origw: MagickGetImageWidth *wand origh: MagickGetImageHeight *wand try MagickCropImage *wand width height ofsx ofsy try MagickWriteImages *wand as-string utf8/encode to-local-file trg ClearMagickWand *wand end ] set 'crop-images func[[catch] files x y width height /local origw origh tmp result][ unless block? files [files: reduce [files]] result: none start foreach file files [ try MagickReadImage *wand file: as-string utf8/encode to-local-file file try MagickSetImagePage *wand 0 0 0 0 origw: MagickGetImageWidth *wand origh: MagickGetImageHeight *wand type: MagickGetImageType *wand print ["imagetype:" type] unless any [ all [ any [ origh < height origw < width ] (print ["!! Crop out of bounds!" mold file origh "<" height "or" origw "<" width] break) ] all [ x = 0 y = 0 origh = height origw = width (print ["!! Crop not needed!" mold file] break) ] ][ try MagickCropImage *wand width height x y if default/CompressionQuality [ try MagickSetImageCompressionQuality *wand default/CompressionQuality ] ; if default/ImageType [ ; try MagickSetImageType *wand default/ImageType ; ] try MagickWriteImages *wand result: head insert find/last copy file "." rejoin [%_crop_ x #"x" y #"_" width #"x" height] ] ClearMagickWand *wand ] end result ] set 'resize-image func[[catch] file file-sc percent [block! number!] /local type width height ][ if number? percent [percent: reduce [percent percent]] start try MagickReadImage *wand utf8/encode to-local-file file probe type: MagickGetImageFormat *wand; ask "" width: MagickGetImageWidth *wand height: MagickGetImageHeight *wand try MagickResizeImage *wand round/ceiling(percent/1 * width) round/ceiling(percent/2 * height) 4 1 ;default/blur try MagickUnsharpMaskImage *wand 1 2.0 0.3 .05 if default/CompressionQuality [ try MagickSetImageCompressionQuality *wand default/CompressionQuality ] try MagickSetOption *wand "png:include-chunk" "none" try MagickSetOption *wand "png:exclude-chunk" "bkgd" try MagickWriteImage *wand probe join either probe type = "PNG" ["PNG32:"][""] utf8/encode to-local-file file-sc end ] set 'get-image-size func[[catch] file /local width height ][ start try MagickPingImage *wand utf8/encode to-local-file file width: MagickGetImageWidth *wand height: MagickGetImageHeight *wand end as-pair width height ] query: func[ /options /fonts /local ret res num ][ num: address? third s_int either fonts [ ret: last third :MagickQueryFonts insert clear ret [integer!] MagickQueryFonts "*" num ;this one just to get the number of results insert clear ret [struct!] append/only ret (head insert/dup copy [] [. [string!]] s_int/value) res: MagickQueryFonts "*" num ][ ret: last third :MagickQueryConfigureOptions insert clear ret [integer!] MagickQueryConfigureOptions "*" num insert clear ret [struct!] append/only ret (head insert/dup copy [] [. [string!]] s_int/value) res: MagickQueryConfigureOptions "*" num ] clear ret second res ] info: has [result][ result: copy [] foreach option query [ repend result [ option MagickQueryConfigureOption option ] ] new-line/skip result true 2 ] FilterTypes: [ Bessel Blackman Box Catrom Cubic Gaussian Hanning Hermite Lanczos Mitchell Point Quandratic Sinc Triangle ] default: context [ quality: 80 filter: 5 radius: 1.2 sigma: 1.0 blur: 0.9 CompressionQuality: 90 ImageType: 7 ;6 = TrueColor MergeBGColor: "black" ] start: does [ init-routines if none? *wand [ MagickWandGenesis *wand: NewMagickWand ] ] end: does [ ClearMagickWand *wand DestroyMagickWand *wand MagickWandTerminus *wand: none ] try: func[res [block! integer!] /local errmsg tmp][ either block? res [ system/words/try res ][ if zero? res [ errmsg: reform [ Exception/Severity "=" ptr-to-string tmp: MagickGetException *wand Exception ;"^/*** near:" join copy/part form pos 60 "..." ] MagickRelinquishMemory tmp end make error! errmsg ] ] ] ] ;do %test.r
function fx1 = p04_fx1 ( x ) %*****************************************************************************80 % %% P04_FX1 evaluates the derivative of the function for problem 4. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 07 May 2011 % % Author: % % John Burkardt % % Parameters: % % Input, real X, the abscissa. % % Output, real FX1, the first derivative of the function at X. % fx1 = exp ( x ) + 2.0 / ( 100.0 * x * x * x ); return end
[STATEMENT] lemma PartE [elim!]: "\<lbrakk> a \<in> Part A h; !!z. \<lbrakk> a \<in> A; a=h(z) \<rbrakk> \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>a \<in> Part A h; \<And>z. \<lbrakk>a \<in> A; a = h z\<rbrakk> \<Longrightarrow> P\<rbrakk> \<Longrightarrow> P [PROOF STEP] by (auto simp add: Part_def)
[STATEMENT] lemma ceiling_diff_numeral [simp]: "\<lceil>x - numeral v\<rceil> = \<lceil>x\<rceil> - numeral v" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lceil>x - numeral v\<rceil> = \<lceil>x\<rceil> - numeral v [PROOF STEP] using ceiling_diff_of_int [of x "numeral v"] [PROOF STATE] proof (prove) using this: \<lceil>x - of_int (numeral v)\<rceil> = \<lceil>x\<rceil> - numeral v goal (1 subgoal): 1. \<lceil>x - numeral v\<rceil> = \<lceil>x\<rceil> - numeral v [PROOF STEP] by simp
------------------------------------------------------------------------ -- The unit type ------------------------------------------------------------------------ module Data.Unit where open import Data.Sum open import Relation.Nullary open import Relation.Binary open import Relation.Binary.PropositionalEquality as PropEq using (_≡_; refl) ------------------------------------------------------------------------ -- Types -- Note that the name of this type is "\top", not T. record ⊤ : Set where tt : ⊤ tt = record {} record _≤_ (x y : ⊤) : Set where ------------------------------------------------------------------------ -- Operations _≟_ : Decidable {⊤} _≡_ _ ≟ _ = yes refl _≤?_ : Decidable _≤_ _ ≤? _ = yes _ total : Total _≤_ total _ _ = inj₁ _ ------------------------------------------------------------------------ -- Properties preorder : Preorder preorder = PropEq.preorder ⊤ setoid : Setoid setoid = PropEq.setoid ⊤ decTotalOrder : DecTotalOrder decTotalOrder = record { carrier = ⊤ ; _≈_ = _≡_ ; _≤_ = _≤_ ; isDecTotalOrder = record { isTotalOrder = record { isPartialOrder = record { isPreorder = record { isEquivalence = PropEq.isEquivalence ; reflexive = λ _ → _ ; trans = λ _ _ → _ ; ∼-resp-≈ = PropEq.resp₂ _≤_ } ; antisym = antisym } ; total = total } ; _≟_ = _≟_ ; _≤?_ = _≤?_ } } where antisym : Antisymmetric _≡_ _≤_ antisym _ _ = refl decSetoid : DecSetoid decSetoid = DecTotalOrder.Eq.decSetoid decTotalOrder poset : Poset poset = DecTotalOrder.poset decTotalOrder
{-# options_ghc -Wwarn #-} {-# language TypeOperators #-} {-# language FlexibleInstances #-} module Main where import Solitaire.Yukon import System.Directory import System.Environment import System.Microtimer import qualified Data.Vector as V import Statistics.Sample import Data.List (sort) import Options.Generic import LinearRegression data CliArgs w = CliArgs { numTrials :: w ::: Int <!> "10" <?> "Number of trials to run" , limitGames :: w ::: Int <!> "100" <?> "Limit number of games to test" , step :: w ::: Float <!> "0.1" <?> "Step size" } deriving stock (Generic) deriving instance Show (CliArgs Unwrapped) instance ParseRecord (CliArgs Wrapped) main :: IO () main = do args :: CliArgs Unwrapped <- unwrapRecord "Optimize heuristics" let limitGames = args ^. #limitGames numTrials = args ^. #numTrials fileNames <- take limitGames <$> listDirectory "games/Solvable" games <- for fileNames $ \name -> do fileContents <- readFile $ "games/Solvable/" <> name pure $ read fileContents let optimizeConfig = OptimizeConfig { numTrials, games } initialWeights = mempty & at "numFaceUp" ?~ 2 & at "numFaceDown" ?~ 5 & at "totalRunScore" ?~ (-0.5) test = testWeights optimizeConfig runTime <- test initialWeights prettyPrint runTime pure () data PartialDArgs = PartialDArgs { step :: Float , field :: Text , runTime :: RunTime , weights :: Weights , function :: Weights -> IO RunTime } deriving stock (Generic) partialDerivative :: PartialDArgs -> IO RunTime partialDerivative args = do let w_1 :: Weights w_1 = args ^. #weights & ix (args ^. #field) -~ (args ^. #step) w_2 :: Weights w_2 = args ^. #weights & ix (args ^. #field) +~ (args ^. #step) r0 = args ^. #runTime r1 <- args ^. #function $ w_1 r2 <- args ^. #function $ w_2 pure $ undefined data Uncertain a = a :+- a data Line = Line { m :: Uncertain Float , b :: Uncertain Float } deriving stock (Generic) linearRegression :: [(Weight, RunTime)] -> Line linearRegression = undefined data OptimizeConfig = OptimizeConfig { numTrials :: !Int , games :: ![Game] } deriving stock (Generic) data RunTime = RunTime { mean :: !Double , standardDeviation :: !Double } deriving stock (Generic) instance Pretty RunTime where prettyExpr run = prettyExpr $ (Empty :: Map Text Text) & at "mean" ?~ (run ^. #mean . to formatSeconds . packed) & at "std dev" ?~ (run ^. #standardDeviation . to formatSeconds . packed) testWeights :: OptimizeConfig -> Weights -> IO RunTime testWeights config weights = do let games = config ^. #games numTrials = config ^. #numTrials times <- for games $ \game -> do let run = runGame @Yukon game & (runReaderT ?? weights) & time_ sequenceA $ replicate numTrials run let sortedData = join times & sort & V.fromList (mean, variance) = meanVariance sortedData standardDeviation = sqrt variance pure $ RunTime { mean, standardDeviation } updateWeightsAtRandom :: forall k m. (Ord k, MonadRandom m) => Weights -> m Weights updateWeightsAtRandom map = do let n = length map keys = (map ^.. ifolded . asIndex) delta <- randomDelta n pure $ flip execState map $ ifor_ keys $ \i key -> do ix key += (delta ^?! ix i)
import Control.Indexed data State = One | Two | Three data Transition : Type -> State -> State -> Type where Pure : (x : a) -> Transition a s s First : Transition () One Two Second : Transition () Two Three Third : Transition () Three One Bind : Transition a x y -> (a -> Transition b y z) -> Transition b x z IndexedFunctor State State Transition where map f (Pure x) = Pure (f x) map f First = Bind First (Pure . f) map f Second = Bind Second (Pure . f) map f Third = Bind Third (Pure . f) map f (Bind x g) = Bind x (\x' => map f (g x')) IndexedApplicative State Transition where pure = Pure ap (Pure f) x = map f x ap (Bind y f) x = Bind y $ \y' => Bind (f y') $ \f' => Bind x (\x' => Pure (f' x')) IndexedMonad State Transition where bind = Bind main : Transition () One One main = do First Second Indexed.ignore $ Pure "hello" Third
ZHANJIANG, CHINA - JANUARY 03: The marines of China navy participate in the annual military training on January 3, 2018 in Zhanjiang, Guangdong Province of China. Taiwan deemed this “an intentional, reckless & provocative action,” which triggered “a 10-minute standoff” in the air. As Asia security expert Bonnie S. Glaser notes that, if intentional, this would be the first PLAAF crossing of the median line in about 20 years. In this case, it’s likely that Taiwan, not the South China Sea, prompted Beijing’s actions. To hear more from Ketian, don't miss her recently posted video Q&A. In addition, be sure to RSVP for her April 16 seminar "Killing the Chicken to Scare the Monkey: Explaining Coercion by China in the South China Sea."
-- --------------------------------------------------------------------- -- Ejercicio 1. Realizar las siguientes acciones: -- 1. Importar la teoría de monoides. -- 2. Declaral α como un tipo. -- 3. Declarar R como un monoide ordenado cancelativo. -- 4. Declarar a, b, c y d como variables sobre R. -- ---------------------------------------------------------------------- import algebra.order.monoid -- 1 variables {α : Type*} -- 2 variables {R : Type*} [ordered_cancel_add_comm_monoid R] -- 3 variables a b c d : R -- 4 -- --------------------------------------------------------------------- -- Ejercicio 2. Calcular el tipo de -- @add_le_add R _ a b c d -- ---------------------------------------------------------------------- -- #check @add_le_add -- Comentario: Al colocar el cursor sobre check se obtiene -- a ≤ b → c ≤ d → a + c ≤ b + d -- --------------------------------------------------------------------- -- Ejercicio 3. Definir la función -- fn_ub (α → R) → R → Prop -- tal que (fn_ub f a) afirma que a es una cota superior de f. -- ---------------------------------------------------------------------- def fn_ub (f : α → R) (a : R) : Prop := ∀ x, f x ≤ a -- --------------------------------------------------------------------- -- Ejercicio 4. Demostrar que que la suma de una cota superior de f y -- otra de g es una cota superior de f + g. -- ---------------------------------------------------------------------- theorem fn_ub_add {f g : α → R} {a b : R} (hfa : fn_ub f a) (hgb : fn_ub g b) : fn_ub (λ x, f x + g x) (a + b) := λ x, add_le_add (hfa x) (hgb x)
{-# OPTIONS --safe #-} module Cubical.Categories.Presheaf.Base where open import Cubical.Foundations.Prelude open import Cubical.Categories.Category open import Cubical.Categories.Instances.Sets open import Cubical.Categories.Instances.Functors PreShv : ∀ {ℓ ℓ'} → Category ℓ ℓ' → (ℓS : Level) → Category (ℓ-max (ℓ-max ℓ ℓ') (ℓ-suc ℓS)) (ℓ-max (ℓ-max ℓ ℓ') ℓS) PreShv C ℓS = FUNCTOR (C ^op) (SET ℓS)
random_point(M::Manifold) = random_point(M, Val(:Gaussian)) @doc raw""" random_point(M, :Uniform) return a random point on the [Circle](https://juliamanifolds.github.io/Manifolds.jl/stable/interface.html#ManifoldsBase.Manifold) $\mathbb S^1$ by picking a random element from $[-\pi,\pi)$ uniformly. """ random_point(M::Circle, ::Val{:Uniform}) = sym_rem(rand()*2*π) random_point(M::Circle) = random_point(M,Val(:Uniform)) # introduce different default @doc raw""" random_point(M::Euclidean[,T=Float64]) generate a random point on the `Euclidean` manifold `M`, where the optional parameter determines the type of the entries of the resulting point on the Euclidean space d. """ random_point(M::Euclidean) = randn(manifold_dimension(M)) @doc raw""" random_point(M::Grassmannian [,type=:Gaussian, σ=1.0]) return a random point `x` on `Grassmannian` manifold `M` by generating a random (Gaussian) matrix with standard deviation `σ` in matching size, which is orthonormal. """ function random_point(M::Grassmann{n,k,𝔽}, ::Val{:Gaussian}, σ::Float64=1.0) where {n,k,𝔽} V = σ * randn(𝔽===ℝ ? Float64 : ComplexF64, (n, k)) A = qr(V).Q[:,1:k] return A end function random_point(M::AbstractPowerManifold{𝔽,Mt,NestedPowerRepresentation}, options...) where {𝔽,Mt} return [ random_point(M.manifold, options...) for i in get_iterator(M) ] end function random_point(M::AbstractPowerManifold{𝔽,Mt,ArrayPowerRepresentation}, options...) where {𝔽,Mt} return cat( [ random_point(M.manifold, options...) for i in get_iterator(M) ]..., dims=length(representation_size(M.manifold))+1 ) end @doc raw""" random_point(M::ProductManifold [,type=:Gaussian, σ=1.0]) return a random point `x` on `Grassmannian` manifold `M` by generating a random (Gaussian) matrix with standard deviation `σ` in matching size, which is orthonormal. """ function random_point(M::ProductManifold, o...) return ProductRepr([ random_point(N,o...) for N in M.manifolds ]...) end @doc raw""" randomMPoint(M::Rotations [,type=:Gaussian, σ=1.0]) return a random point `p` on the manifold `Rotations` by generating a (Gaussian) random orthogonal matrix with determinant $+1$. Let $QR = A$ be the QR decomposition of a random matrix $A$, then the formula reads $p = QD$ where $D$ is a diagonal matrix with the signs of the diagonal entries of $R$, i.e. ````math D_{ij}=\begin{cases} \operatorname{sgn}(R_{ij}) & \text{if} \; i=j \\ 0 & \, \text{otherwise.} \end{cases}$ ```` It can happen that the matrix gets -1 as a determinant. In this case, the first and second columns are swapped. """ function random_point(M::Rotations, ::Val{:Gaussian}, σ::Real=1.0) d = manifold_dimension(M) if d == 1 return ones(1,1) else A=randn(Float64, d, d) s=diag(sign.(qr(A).R)) D=Diagonal(s) C = qr(A).Q*D if det(C)<0 C[:,[1,2]] = C[:,[2,1]] end return C end end @doc raw""" random_point(M::SymmetricPositiveDefinite, :Gaussian[, σ=1.0]) gerenate a random symmetric positive definite matrix on the `SymmetricPositiveDefinite` manifold `M`. """ function random_point(M::SymmetricPositiveDefinite{N},::Val{:Gaussian},σ::Float64=1.0) where N D = Diagonal( 1 .+ randn(N) ) # random diagonal matrix s = qr(σ * randn(N,N)) # random q return s.Q * D * transpose(s.Q) end @doc raw""" random_point(M::Stiefel, :Gaussian, σ=1.0]) return a random (Gaussian) point `x` on the `Stiefel` manifold `M` by generating a (Gaussian) matrix with standard deviation `σ` and return the orthogonalized version, i.e. return ​​the Q component of the QR decomposition of the random matrix of size $n×k$. """ function random_point(M::Stiefel{n,k,𝔽}, ::Val{:Gaussian}, σ::Float64=1.0) where {n,k,𝔽} A = σ*randn(𝔽===ℝ ? Float64 : ComplexF64, n, k) return Matrix(qr(A).Q) end @doc raw""" random_point(M::Sphere, :Gaussian, σ=1.0]) return a random point on the Sphere by projecting a normal distirbuted vector from within the embedding to the sphere. """ function random_point(M::Sphere, ::Val{:Gaussian}, σ::Float64=1.0) return project(M, σ * randn(manifold_dimension(M)+1)) end @doc raw""" random_tangent(M,p) generate a random tangent vector in the tangent space of `p` on `M`. By default this is a `:Gaussian` distribution. """ random_tangent(M::Manifold, p) = random_tangent(M,p,Val(:Gaussian)) @doc raw""" random_tangent(M::Circle, x[, :Gaussian, σ=1.0]) return a random tangent vector from the tangent space of the point `x` on the [Circle](https://juliamanifolds.github.io/Manifolds.jl/stable/interface.html#ManifoldsBase.Manifold) $\mathbb S^1$ by using a normal distribution with mean 0 and standard deviation 1. """ random_tangent(M::Circle, p, ::Val{:Gaussian}, σ::Real=1.0) = σ*randn() doc""" random_tangent(M,x,:Gaussian[,σ=1.0]) generate a Gaussian random vector on the `Euclidean` manifold `M` with standard deviation `σ`. """ random_tangent(M::Euclidean, p, ::Val{:Gaussian}, σ::Float64=1.0) = σ * randn(manifold_dimension(M)) @doc raw""" random_tangent(M::GRassmann,x[,type=:Gaussian, σ=1.0]) return a (Gaussian) random vector from the tangent space $T_x\mathrm{Gr}(n,k)$ with mean zero and standard deviation `σ` by projecting a random Matrix onto the `x`. """ function random_tangent(M::Grassmann, p, ::Val{:Gaussian}, σ::Float64=1.0) Z = σ * randn(eltype(p), size(p)) X = project(M, p, Z) X = X/norm(X) return X end @doc raw""" random_tangent(M::Hyperpolic, p) generate a random point on the Hyperbolic manifold by projecting a point from the embedding with respect to the Minkowsky metric. """ function random_tangent(M::Hyperbolic, p, ::Val{:Gaussian}) Y = randn(eltype(p), size(p)) X = project(M, p, Y) return X end function random_tangent(M::PowerManifold, p, options...) rep_size = representation_size(M.manifold) X = zero_tangent_vector(M, p) for i in get_iterator(M) set_component!( M, X, random_tangent( M.manifold, get_component(M, p, i), options... ), i ) end return X end @doc raw""" random_tangent(M::ProductManifold, x) generate a random tangent vector in the tangent space of the point `p` on the `ProductManifold` `M`. """ function random_tangent(M::ProductManifold, p, options...) X = map( (m,p) -> random_tangent(m, p, options...), M.manifolds, submanifold_components(M, p) ) return ProductRepr(X...) end @doc raw""" random_tangent(M::Rotations, p[, type=:Gaussian, σ=1.0]) return a random tangent vector in the tangent space $T_x\mathrm{SO}(n)$ of the point `x` on the `Rotations` manifold `M` by generating a random skew-symmetric matrix. The function takes the real upper triangular matrix of a (Gaussian) random matrix $A$ with dimension $n\times n$ and subtracts its transposed matrix. Finally, the matrix is ​​normalized. """ function random_tangent(M::Rotations, p, ::Val{:Gaussian}, σ::Real=1.0) d = manifold_dimension(M) if d == 1 return zeros(1,1) else A = randn(Float64, d, d) A = triu(A,1) - transpose(triu(A,1)) A = (1/norm(A))*A return A end end @doc raw""" random_tangent(M::Sphere, x[, :Gaussian, σ=1.0]) return a random tangent vector in the tangent space of `x` on the `Sphere` `M`. """ function random_tangent(M::Sphere, p, ::Val{:Gaussian}, σ::Float64=1.0) n = σ * randn( size(p) ) # Gaussian in embedding return n - dot(n, p)*p #project to TpM (keeps Gaussianness) end @doc raw""" random_tangent(M, p[, :Gaussian, σ = 1.0]) generate a random tangent vector in the tangent space of the point `p` on the `SymmetricPositiveDefinite` manifold `M` by using a Gaussian distribution with standard deviation `σ` on an ONB of the tangent space. """ function random_tangent(M::SymmetricPositiveDefinite, p, ::Val{:Gaussian}, σ::Float64 = 0.01) # generate ONB in TxM I = one(p) B = get_basis(M, p, DiagonalizingOrthonormalBasis(I)) Ξ = get_vectors(M,p,B) Ξx = vector_transport_to.(Ref(M), Ref(I), Ξ, Ref(p), Ref(ParallelTransport())) return sum( randn(length(Ξx)) .* Ξx ) end @doc raw""" random_tangent(M,x, Val(:Rician) [,σ = 0.01]) generate a random tangent vector in the tangent space of `x` on the `SymmetricPositiveDefinite` manifold `M` by using a Rician distribution with standard deviation `σ`. """ function random_tangent(M::SymmetricPositiveDefinite, p, ::Val{:Rician}, σ::Real = 0.01) # Rician C = cholesky( Hermitian(p) ) R = C.L + sqrt(σ) * triu( randn(size(p,1), size(p,2)), 0) return R*R' end
function imagescg(im) % imagescg(im) % Uses colormap('gray') for the imagecs imagesc(im) colormap('gray')
header {* Isomorphisms of Free Groups *} theory "Isomorphisms" imports "UnitGroup" "~~/src/HOL/Algebra/IntRing" "FreeGroups" C2 "~~/src/HOL/Cardinals/Cardinal_Order_Relation" begin subsection {* The Free Group over the empty set *} text {* The Free Group over an empty set of generators is isomorphic to the trivial group. *} lemma free_group_over_empty_set: "\<exists>h. h \<in> \<F>\<^bsub>{}\<^esub> \<cong> unit_group" proof(rule group.unit_group_unique) show "group \<F>\<^bsub>{}\<^esub>" by (rule free_group_is_group) next have "carrier \<F>\<^bsub>{}::'a set\<^esub> = {[]}" by (auto simp add:free_group_def) thus "card (carrier \<F>\<^bsub>{}::'a set\<^esub>) = 1" by simp qed subsection {* The Free Group over one generator *} text {* The Free Group over one generator is isomorphic to the free abelian group over one element, also known as the integers. *} abbreviation "int_group" where "int_group \<equiv> \<lparr> carrier = carrier \<Z>, mult = op +, one = 0::int \<rparr>" lemma replicate_set_eq[simp]: "\<forall>x \<in> set xs. x = y \<Longrightarrow> xs = replicate (length xs) y" by(induct xs)auto lemma int_group_gen_by_one: "\<langle>{1}\<rangle>\<^bsub>int_group\<^esub> = carrier int_group" proof show "\<langle>{1}\<rangle>\<^bsub>int_group\<^esub> \<subseteq> carrier int_group" by auto show "carrier int_group \<subseteq> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" proof interpret int: group int_group by (simp add: int.a_group) fix x have plus1: "1 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by (auto intro:gen_span.gen_gens) hence "inv\<^bsub>int_group\<^esub> 1 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by (auto intro:gen_span.gen_inv) moreover have "-1 = inv\<^bsub>int_group\<^esub> 1" by (rule sym, rule int.inv_equality) simp_all ultimately have minus1: "-1 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by (simp) show "x \<in> \<langle>{1::int}\<rangle>\<^bsub>int_group\<^esub>" (* It does not work directly, unfortunately: apply(induct x rule:int_induct[of _ "0::int"]) apply (auto simp add: int_arith_rules intro:gen_span.intros[of int_group]) *) proof(induct x rule:int_induct[of _ "0::int"]) case base have "\<one>\<^bsub>int_group\<^esub> \<in> \<langle>{1\<Colon>int}\<rangle>\<^bsub>int_group\<^esub>" by (rule gen_span.gen_one) thus"0 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by simp next case (step1 i) from `i \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>` and plus1 have "i \<otimes>\<^bsub>int_group\<^esub> 1 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by (rule gen_span.gen_mult) thus "i + 1 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by simp next case (step2 i) from `i \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>` and minus1 have "i \<otimes>\<^bsub>int_group\<^esub> -1 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by (rule gen_span.gen_mult) thus "i - 1 \<in> \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by simp qed qed qed lemma free_group_over_one_gen: "\<exists>h. h \<in> \<F>\<^bsub>{()}\<^esub> \<cong> int_group" proof- interpret int: group int_group by (simp add: int.a_group) def f \<equiv> "\<lambda>(x::unit).(1::int)" have "f \<in> {()} \<rightarrow> carrier int_group" by auto hence "int.lift f \<in> hom \<F>\<^bsub>{()}\<^esub> int_group" by (rule int.lift_is_hom) then interpret hom: group_hom "\<F>\<^bsub>{()}\<^esub>" int_group "int.lift f" unfolding group_hom_def group_hom_axioms_def by(auto intro: int.a_group free_group_is_group) { (* This shows injectiveness of the given map *) fix x assume "x \<in> carrier \<F>\<^bsub>{()}\<^esub>" hence "canceled x" by (auto simp add:free_group_def) assume "int.lift f x = (0::int)" have "x = []" proof(rule ccontr) assume "x \<noteq> []" then obtain a and xs where "x = a # xs" by (cases x, auto) hence "length (takeWhile (\<lambda>y. y = a) x) > 0" by auto then obtain i where i: "length (takeWhile (\<lambda>y. y = a) x) = Suc i" by (cases "length (takeWhile (\<lambda>y. y = a) x)", auto) have "Suc i \<ge> length x" proof(rule ccontr) assume "\<not> length x \<le> Suc i" hence "length (takeWhile (\<lambda>y. y = a) x) < length x" using i by simp hence "\<not> (\<lambda>y. y = a) (x ! length (takeWhile (\<lambda>y. y = a) x))" by (rule nth_length_takeWhile) hence "\<not> (\<lambda>y. y = a) (x ! Suc i)" using i by simp hence "fst (x ! Suc i) \<noteq> fst a" by (cases "x ! Suc i", cases "a", auto) moreover { have "takeWhile (\<lambda>y. y = a) x ! i = x ! i" using i by (auto intro: takeWhile_nth) moreover have "(takeWhile (\<lambda>y. y = a) x) ! i \<in> set (takeWhile (\<lambda>y. y = a) x)" using i by auto ultimately have "(\<lambda>y. y = a) (x ! i)" by (auto dest:set_takeWhileD) } hence "fst (x ! i) = fst a" by auto moreover have "snd (x ! i) = snd (x ! Suc i)" by simp ultimately have "canceling (x ! i) (x ! Suc i)" unfolding canceling_def by auto hence "cancels_to_1_at i x (cancel_at i x)" using `\<not> length x \<le> Suc i` unfolding cancels_to_1_at_def by (auto simp add:length_takeWhile_le) hence "cancels_to_1 x (cancel_at i x)" unfolding cancels_to_1_def by auto hence "\<not> canceled x" unfolding canceled_def by auto thus False using `canceled x` by contradiction qed hence "length (takeWhile (\<lambda>y. y = a) x) = length x" using i[THEN sym] by (auto dest:le_antisym simp add:length_takeWhile_le) hence "takeWhile (\<lambda>y. y = a) x = x" by (subst takeWhile_eq_take, simp) moreover have "\<forall>y \<in> set (takeWhile (\<lambda>y. y = a) x). y = a" by (auto dest: set_takeWhileD) ultimately have "\<forall>y \<in> set x. y = a" by auto hence "x = replicate (length x) a" by simp hence "int.lift f x = int.lift f (replicate (length x) a)" by simp also have "... = pow int_group (int.lift_gi f a) (length x)" by (induct x,auto simp add:int.lift_def [simplified]) also have "... = (int.lift_gi f a) * int (length x)" by (induct ("length x"), auto simp add:int_distrib) finally have "\<dots> = 0" using `int.lift f x = 0` by simp hence "nat (abs (group.lift_gi int_group f a * int (length x))) = 0" by simp hence "nat (abs (group.lift_gi int_group f a)) * length x = 0" by simp hence "nat (abs (group.lift_gi int_group f a)) = 0" using `x \<noteq> []` by auto moreover have "inv\<^bsub>int_group\<^esub> 1 = -1" using int.inv_equality by auto hence "abs (group.lift_gi int_group f a) = 1" using `group int_group` by(auto simp add: group.lift_gi_def f_def) ultimately show False by simp qed } hence "\<forall>x\<in>carrier \<F>\<^bsub>{()}\<^esub>. int.lift f x = \<one>\<^bsub>int_group\<^esub> \<longrightarrow> x = \<one>\<^bsub>\<F>\<^bsub>{()}\<^esub>\<^esub>" by (auto simp add:free_group_def) moreover { have "carrier \<F>\<^bsub>{()}\<^esub> = \<langle>insert`{()}\<rangle>\<^bsub>\<F>\<^bsub>{()}\<^esub>\<^esub>" by (rule gens_span_free_group[THEN sym]) moreover have "carrier int_group = \<langle>{1}\<rangle>\<^bsub>int_group\<^esub>" by (rule int_group_gen_by_one[THEN sym]) moreover have "int.lift f ` insert ` {()} = {1}" by (auto simp add: int.lift_def [simplified] insert_def f_def int.lift_gi_def [simplified]) moreover have "int.lift f ` \<langle>insert`{()}\<rangle>\<^bsub>\<F>\<^bsub>{()}\<^esub>\<^esub> = \<langle>int.lift f ` (insert `{()})\<rangle>\<^bsub>int_group\<^esub>" by (rule hom.hom_span, auto intro:insert_closed) ultimately have "int.lift f ` carrier \<F>\<^bsub>{()}\<^esub> = carrier int_group" by simp } ultimately have "int.lift f \<in> \<F>\<^bsub>{()}\<^esub> \<cong> int_group" using `int.lift f \<in> hom \<F>\<^bsub>{()}\<^esub> int_group` using hom.hom_mult int.is_group by (auto intro:group_isoI simp add: free_group_is_group) thus ?thesis by auto qed subsection {* Free Groups over isomorphic sets of generators *} text {* Free Groups are isomorphic if their set of generators are isomorphic. *} definition lift_generator_function :: "('a \<Rightarrow> 'b) \<Rightarrow> (bool \<times> 'a) list \<Rightarrow> (bool \<times> 'b) list" where "lift_generator_function f = map (map_prod id f)" theorem isomorphic_free_groups: assumes "bij_betw f gens1 gens2" shows "lift_generator_function f \<in> \<F>\<^bsub>gens1\<^esub> \<cong> \<F>\<^bsub>gens2\<^esub>" unfolding lift_generator_function_def proof(rule group_isoI) show "\<forall>x\<in>carrier \<F>\<^bsub>gens1\<^esub>. map (map_prod id f) x = \<one>\<^bsub>\<F>\<^bsub>gens2\<^esub>\<^esub> \<longrightarrow> x = \<one>\<^bsub>\<F>\<^bsub>gens1\<^esub>\<^esub>" by(auto simp add:free_group_def) next from `bij_betw f gens1 gens2` have "inj_on f gens1" by (auto simp:bij_betw_def) show "map (map_prod id f) ` carrier \<F>\<^bsub>gens1\<^esub> = carrier \<F>\<^bsub>gens2\<^esub>" proof(rule Set.set_eqI,rule iffI) from `bij_betw f gens1 gens2` have "f ` gens1 = gens2" by (auto simp:bij_betw_def) fix x :: "(bool \<times> 'b) list" assume "x \<in> image (map (map_prod id f)) (carrier \<F>\<^bsub>gens1\<^esub>)" then obtain y :: "(bool \<times> 'a) list" where "x = map (map_prod id f) y" and "y \<in> carrier \<F>\<^bsub>gens1\<^esub>" by auto from `y \<in> carrier \<F>\<^bsub>gens1\<^esub>` have "canceled y" and "y \<in> lists(UNIV\<times>gens1)" by (auto simp add:free_group_def) from `y \<in> lists (UNIV\<times>gens1)` and `x = map (map_prod id f) y` and `image f gens1 = gens2` have "x \<in> lists (UNIV\<times>gens2)" by (auto iff:lists_eq_set) moreover from `x = map (map_prod id f) y` and `y \<in> lists (UNIV\<times>gens1)` and `canceled y` and `inj_on f gens1` have "canceled x" by (auto intro!:rename_gens_canceled subset_inj_on[OF `inj_on f gens1`] iff:lists_eq_set) ultimately show "x \<in> carrier \<F>\<^bsub>gens2\<^esub>" by (simp add:free_group_def) next fix x assume "x \<in> carrier \<F>\<^bsub>gens2\<^esub>" hence "canceled x" and "x \<in> lists (UNIV\<times>gens2)" unfolding free_group_def by auto def y \<equiv> "map (map_prod id (the_inv_into gens1 f)) x" have "map (map_prod id f) y = map (map_prod id f) (map (map_prod id (the_inv_into gens1 f)) x)" by (simp add:y_def) also have "\<dots> = map (map_prod id f \<circ> map_prod id (the_inv_into gens1 f)) x" by simp also have "\<dots> = map (map_prod id (f \<circ> the_inv_into gens1 f)) x" by auto also have "\<dots> = map id x" proof(rule map_ext, rule impI) fix xa :: "bool \<times> 'b" assume "xa \<in> set x" from `x \<in> lists (UNIV\<times>gens2)` have "set (map snd x) \<subseteq> gens2" by auto hence "snd ` set x \<subseteq> gens2" by (simp add: set_map) with `xa \<in> set x` have "snd xa \<in> gens2" by auto with `bij_betw f gens1 gens2` have "snd xa \<in> f`gens1" by (auto simp add: bij_betw_def) have "map_prod id (f \<circ> the_inv_into gens1 f) xa = map_prod id (f \<circ> the_inv_into gens1 f) (fst xa, snd xa)" by simp also have "\<dots> = (fst xa, f (the_inv_into gens1 f (snd xa)))" by (auto simp del:pair_collapse) also with `snd xa \<in> image f gens1` and `inj_on f gens1` have "\<dots> = (fst xa, snd xa)" by (auto elim:f_the_inv_into_f simp del:pair_collapse) also have "\<dots> = id xa" by simp finally show "map_prod id (f \<circ> the_inv_into gens1 f) xa = id xa". qed also have "\<dots> = x" unfolding id_def by auto finally have "map (map_prod id f) y = x". moreover { from `bij_betw f gens1 gens2` have "bij_betw (the_inv_into gens1 f) gens2 gens1" by (rule bij_betw_the_inv_into) hence "inj_on (the_inv_into gens1 f) gens2" by (rule bij_betw_imp_inj_on) with `canceled x` and `x \<in> lists (UNIV\<times>gens2)` have "canceled y" by (auto intro!:rename_gens_canceled[OF subset_inj_on] simp add:y_def) moreover { from `bij_betw (the_inv_into gens1 f) gens2 gens1` and `x\<in>lists(UNIV\<times>gens2)` have "y \<in> lists(UNIV\<times>gens1)" unfolding y_def and bij_betw_def by (auto iff:lists_eq_set dest!:subsetD) } ultimately have "y \<in> carrier \<F>\<^bsub>gens1\<^esub>" by (simp add:free_group_def) } ultimately show "x \<in> map (map_prod id f) ` carrier \<F>\<^bsub>gens1\<^esub>" by auto qed next from `bij_betw f gens1 gens2` have "inj_on f gens1" by (auto simp:bij_betw_def) { fix x assume "x \<in> carrier \<F>\<^bsub>gens1\<^esub>" fix y assume "y \<in> carrier \<F>\<^bsub>gens1\<^esub>" from `x \<in> carrier \<F>\<^bsub>gens1\<^esub>` and `y \<in> carrier \<F>\<^bsub>gens1\<^esub>` have "x \<in> lists(UNIV\<times>gens1)" and "y \<in> lists(UNIV\<times>gens1)" by (auto simp add:occuring_gens_in_element) (* hence "occuring_generators (x@y) \<subseteq> gens1" by(auto simp add:occuring_generators_def) with `inj_on f gens1` have "inj_on f (occuring_generators (x@y))" by (rule subset_inj_on) *) have "map (map_prod id f) (x \<otimes>\<^bsub>\<F>\<^bsub>gens1\<^esub>\<^esub> y) = map (map_prod id f) (normalize (x@y))" by (simp add:free_group_def) also (* from `inj_on f (occuring_generators (x@y))` *) from `x \<in> lists(UNIV\<times>gens1)` and `y \<in> lists(UNIV\<times>gens1)` and `inj_on f gens1` have "\<dots> = normalize (map (map_prod id f) (x@y))" by -(rule rename_gens_normalize[THEN sym], auto intro!: subset_inj_on[OF `inj_on f gens1`] iff:lists_eq_set) also have "\<dots> = normalize (map (map_prod id f) x @ map (map_prod id f) y)" by (auto) also have "\<dots> = map (map_prod id f) x \<otimes>\<^bsub>\<F>\<^bsub>gens2\<^esub>\<^esub> map (map_prod id f) y" by (simp add:free_group_def) finally have "map (map_prod id f) (x \<otimes>\<^bsub>\<F>\<^bsub>gens1\<^esub>\<^esub> y) = map (map_prod id f) x \<otimes>\<^bsub>\<F>\<^bsub>gens2\<^esub>\<^esub> map (map_prod id f) y". } thus "\<forall>x\<in>carrier \<F>\<^bsub>gens1\<^esub>. \<forall>y\<in>carrier \<F>\<^bsub>gens1\<^esub>. map (map_prod id f) (x \<otimes>\<^bsub>\<F>\<^bsub>gens1\<^esub>\<^esub> y) = map (map_prod id f) x \<otimes>\<^bsub>\<F>\<^bsub>gens2\<^esub>\<^esub> map (map_prod id f) y" by auto qed (auto intro: free_group_is_group) subsection {* Bases of isomorphic free groups *} text {* Isomorphic free groups have bases of same cardinality. The proof is very different for infinite bases and for finite bases. The proof for the finite case uses the set of of homomorphisms from the free group to the group with two elements, as suggested by Christian Sievers. The definition of @{term hom} is not suitable for proofs about the cardinality of that set, as its definition does not require extensionality. This is amended by the following definition: *} definition homr where "homr G H = {h. h \<in> hom G H \<and> h \<in> extensional (carrier G)}" lemma (in group_hom) restrict_hom[intro!]: shows "restrict h (carrier G) \<in> homr G H" unfolding homr_def and hom_def by (auto) lemma hom_F_C2_Powerset: "\<exists> f. bij_betw f (Pow X) (homr (\<F>\<^bsub>X\<^esub>) C2)" proof interpret F: group "\<F>\<^bsub>X\<^esub>" by (rule free_group_is_group) interpret C2: group C2 by (rule C2_is_group) let ?f = "\<lambda>S . restrict (C2.lift (\<lambda>x. x \<in> S)) (carrier \<F>\<^bsub>X\<^esub>)" let ?f' = "\<lambda>h . X \<inter> Collect(h \<circ> insert)" show "bij_betw ?f (Pow X) (homr (\<F>\<^bsub>X\<^esub>) C2)" proof(induct rule: bij_betwI[of ?f _ _ ?f']) case 1 show ?case proof fix S assume "S \<in> Pow X" interpret h: group_hom "\<F>\<^bsub>X\<^esub>" C2 "C2.lift (\<lambda>x. x \<in> S)" by unfold_locales (auto intro: C2.lift_is_hom) show "?f S \<in> homr \<F>\<^bsub>X\<^esub> C2" by (rule h.restrict_hom) qed next case 2 show ?case by auto next case (3 S) show ?case proof (induct rule: Set.set_eqI) case (1 x) show ?case proof(cases "x \<in> X") case True thus ?thesis using insert_closed[of x X] by (auto simp add:insert_def C2.lift_def C2.lift_gi_def) next case False thus ?thesis using 3 by auto qed qed next case (4 h) hence hom: "h \<in> hom \<F>\<^bsub>X\<^esub> C2" and extn: "h \<in> extensional (carrier \<F>\<^bsub>X\<^esub>)" unfolding homr_def by auto have "\<forall>x \<in> carrier \<F>\<^bsub>X\<^esub> . h x = group.lift C2 (\<lambda>z. z \<in> X & (h \<circ> FreeGroups.insert) z) x" by (rule C2.lift_is_unique[OF C2_is_group _ hom, of "(\<lambda>z. z \<in> X & (h \<circ> FreeGroups.insert) z)"], auto) thus ?case by -(rule extensionalityI[OF restrict_extensional extn], auto) qed qed lemma group_iso_betw_hom: assumes "group G1" and "group G2" and iso: "i \<in> G1 \<cong> G2" shows "\<exists> f . bij_betw f (homr G2 H) (homr G1 H)" proof- interpret G2: group G2 by (rule `group G2`) let ?i' = "restrict (inv_into (carrier G1) i) (carrier G2)" have "inv_into (carrier G1) i \<in> G2 \<cong> G1" by (rule group.iso_sym[OF `group G1` iso]) hence iso': "?i' \<in> G2 \<cong> G1" by (auto simp add:Group.iso_def hom_def G2.m_closed) show ?thesis proof(rule, induct rule: bij_betwI[of "(\<lambda>h. compose (carrier G1) h i)" _ _ "(\<lambda>h. compose (carrier G2) h ?i')"]) case 1 show ?case proof fix h assume "h \<in> homr G2 H" hence "compose (carrier G1) h i \<in> hom G1 H" using iso by (auto intro: group.hom_compose[OF `group G1`, of _ G2] simp add:Group.iso_def homr_def) thus "compose (carrier G1) h i \<in> homr G1 H" unfolding homr_def by simp qed next case 2 show ?case proof fix h assume "h \<in> homr G1 H" hence "compose (carrier G2) h ?i' \<in> hom G2 H" using iso' by (auto intro: group.hom_compose[OF `group G2`, of _ G1] simp add:Group.iso_def homr_def) thus "compose (carrier G2) h ?i' \<in> homr G2 H" unfolding homr_def by simp qed next case (3 x) hence "compose (carrier G2) (compose (carrier G1) x i) ?i' = compose (carrier G2) x (compose (carrier G2) i ?i')" using iso iso' by (auto intro: compose_assoc[THEN sym] simp add:Group.iso_def hom_def homr_def) also have "\<dots> = compose (carrier G2) x (\<lambda>y\<in>carrier G2. y)" using iso by (subst compose_id_inv_into, auto simp add:Group.iso_def hom_def bij_betw_def) also have "\<dots> = x" using 3 by (auto intro:compose_Id simp add:homr_def) finally show ?case . next case (4 y) hence "compose (carrier G1) (compose (carrier G2) y ?i') i = compose (carrier G1) y (compose (carrier G1) ?i' i)" using iso iso' by (auto intro: compose_assoc[THEN sym] simp add:Group.iso_def hom_def homr_def) also have "\<dots> = compose (carrier G1) y (\<lambda>x\<in>carrier G1. x)" using iso by (subst compose_inv_into_id, auto simp add:Group.iso_def hom_def bij_betw_def) also have "\<dots> = y" using 4 by (auto intro:compose_Id simp add:homr_def) finally show ?case . qed qed lemma isomorphic_free_groups_bases_finite: assumes iso: "i \<in> \<F>\<^bsub>X\<^esub> \<cong> \<F>\<^bsub>Y\<^esub>" and finite: "finite X" shows "\<exists>f. bij_betw f X Y" proof- obtain f where "bij_betw f (homr \<F>\<^bsub>Y\<^esub> C2) (homr \<F>\<^bsub>X\<^esub> C2)" using group_iso_betw_hom[OF free_group_is_group free_group_is_group iso] by auto moreover obtain g' where "bij_betw g' (Pow X) (homr (\<F>\<^bsub>X\<^esub>) C2)" using hom_F_C2_Powerset by auto then obtain g where "bij_betw g (homr (\<F>\<^bsub>X\<^esub>) C2) (Pow X)" by (auto intro: bij_betw_inv_into) moreover obtain h where "bij_betw h (Pow Y) (homr (\<F>\<^bsub>Y\<^esub>) C2)" using hom_F_C2_Powerset by auto ultimately have "bij_betw (g \<circ> f \<circ> h) (Pow Y) (Pow X)" by (auto intro: bij_betw_trans) hence eq_card: "card (Pow Y) = card (Pow X)" by (rule bij_betw_same_card) with finite have "finite (Pow Y)" by -(rule card_ge_0_finite, auto simp add:card_Pow) hence finite': "finite Y" by simp with eq_card finite have "card X = card Y" by (auto simp add:card_Pow) with finite finite' show ?thesis by (rule finite_same_card_bij) qed text {* The proof for the infinite case is trivial once the fact that the free group over an infinite set has the same cardinality is established. *} lemma free_group_card_infinite: assumes "\<not> finite X" shows "|X| =o |carrier \<F>\<^bsub>X\<^esub>|" proof- have "inj_on insert X" and "insert ` X \<subseteq> carrier \<F>\<^bsub>X\<^esub>" by (auto intro:insert_closed inj_onI simp add:insert_def) hence "|X| \<le>o |carrier \<F>\<^bsub>X\<^esub>|" by (subst card_of_ordLeq[THEN sym], auto) moreover have "|carrier \<F>\<^bsub>X\<^esub>| \<le>o |lists ((UNIV::bool set)\<times>X)|" by (auto intro!:card_of_mono1 simp add:free_group_def) moreover have "|lists ((UNIV::bool set)\<times>X)| =o |(UNIV::bool set)\<times>X|" using `\<not> finite X` by (auto intro:card_of_lists_infinite dest!:finite_cartesian_productD2) moreover have "|(UNIV::bool set)\<times>X| =o |X|" using `\<not> finite X` by (auto intro: card_of_Times_infinite[OF _ _ ordLess_imp_ordLeq[OF finite_ordLess_infinite2], THEN conjunct2]) ultimately show "|X| =o |carrier \<F>\<^bsub>X\<^esub>|" by (subst ordIso_iff_ordLeq, auto intro: ord_trans) qed theorem isomorphic_free_groups_bases: assumes iso: "i \<in> \<F>\<^bsub>X\<^esub> \<cong> \<F>\<^bsub>Y\<^esub>" shows "\<exists>f. bij_betw f X Y" proof(cases "finite X") case True thus ?thesis using iso by -(rule isomorphic_free_groups_bases_finite) next case False show ?thesis proof(cases "finite Y") case True from iso obtain i' where "i' \<in> \<F>\<^bsub>Y\<^esub> \<cong> \<F>\<^bsub>X\<^esub>" by (auto intro: group.iso_sym[OF free_group_is_group]) with `finite Y` have "\<exists>f. bij_betw f Y X" by -(rule isomorphic_free_groups_bases_finite) thus "\<exists>f. bij_betw f X Y" by (auto intro: bij_betw_the_inv_into) next case False from `\<not> finite X` have "|X| =o |carrier \<F>\<^bsub>X\<^esub>|" by (rule free_group_card_infinite) moreover from `\<not> finite Y` have "|Y| =o |carrier \<F>\<^bsub>Y\<^esub>|" by (rule free_group_card_infinite) moreover from iso have "|carrier \<F>\<^bsub>X\<^esub>| =o |carrier \<F>\<^bsub>Y\<^esub>|" by (auto simp add:Group.iso_def iff:card_of_ordIso[THEN sym]) ultimately have "|X| =o |Y|" by (auto intro: ordIso_equivalence) thus ?thesis by (subst card_of_ordIso) qed qed end
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import Std.Classes.Order import Std.Control.ForInStep.Basic /-! # Red-black trees This module implements a type `RBMap α β cmp` which is a functional data structure for storing a key-value store in a binary search tree. It is built on the simpler `RBSet α cmp` type, which stores a set of values of type `α` using the function `cmp : α → α → Ordering` for determining the ordering relation. The tree will never store two elements that compare `.eq` under the `cmp` function, but the function does not have to satisfy `cmp x y = .eq → x = y`, and in the map case `α` is a key-value pair and the `cmp` function only compares the keys. -/ namespace Std /-- In a red-black tree, every node has a color which is either "red" or "black" (this particular choice of colors is conventional). A nil node is considered black. -/ inductive RBColor where /-- A red node is required to have black children. -/ | red /-- Every path from the root to a leaf must pass through the same number of black nodes. -/ | black deriving Repr /-- A red-black tree. (This is an internal implementation detail of the `RBSet` type, which includes the invariants of the tree.) This is a binary search tree augmented with a "color" field which is either red or black for each node and used to implement the re-balancing operations. See: [Red–black tree](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree) -/ inductive RBNode (α : Type u) where /-- An empty tree. -/ | nil /-- A node consists of a value `v`, a subtree `l` of smaller items, and a subtree `r` of larger items. The color `c` is either `red` or `black` and participates in the red-black balance invariant (see `Balanced`). -/ | node (c : RBColor) (l : RBNode α) (v : α) (r : RBNode α) deriving Repr namespace RBNode open RBColor instance : EmptyCollection (RBNode α) := ⟨nil⟩ /-- The minimum element of a tree is the left-most value. -/ protected def min : RBNode α → Option α | nil => none | node _ nil v _ => some v | node _ l _ _ => l.min /-- The maximum element of a tree is the right-most value. -/ protected def max : RBNode α → Option α | nil => none | node _ _ v nil => some v | node _ _ _ r => r.max /-- Fold a function in tree order along the nodes. `v₀` is used at `nil` nodes and `f` is used to combine results at branching nodes. -/ @[specialize] def fold (v₀ : σ) (f : σ → α → σ → σ) : RBNode α → σ | nil => v₀ | node _ l v r => f (l.fold v₀ f) v (r.fold v₀ f) /-- Fold a function on the values from left to right (in increasing order). -/ @[specialize] def foldl (f : σ → α → σ) : (init : σ) → RBNode α → σ | b, nil => b | b, node _ l v r => foldl f (f (foldl f b l) v) r /-- Fold a function on the values from right to left (in decreasing order). -/ @[specialize] def foldr (f : α → σ → σ) : RBNode α → (init : σ) → σ | nil, b => b | node _ l v r, b => l.foldr f <| f v <| r.foldr f b /-- `O(n)`. Convert the tree to a list in ascending order. -/ def toList (t : RBNode α) : List α := t.foldr (·::·) [] /-- Run monadic function `f` on each element of the tree (in increasing order). -/ @[specialize] def forM [Monad m] (f : α → m PUnit) : RBNode α → m PUnit | nil => pure ⟨⟩ | node _ l v r => do forM f l; f v; forM f r /-- Fold a monadic function on the values from left to right (in increasing order). -/ @[specialize] def foldlM [Monad m] (f : σ → α → m σ) : (init : σ) → RBNode α → m σ | b, nil => pure b | b, node _ l v r => do foldlM f (← f (← foldlM f b l) v) r /-- Implementation of `for x in t` loops over a `RBNode` (in increasing order). -/ @[inline] protected def forIn [Monad m] (as : RBNode α) (init : σ) (f : α → σ → m (ForInStep σ)) : m σ := do ForInStep.run <$> visit as init where /-- Inner loop of `forIn`. -/ @[specialize] visit : RBNode α → σ → m (ForInStep σ) | nil, b => return ForInStep.yield b | node _ l v r, b => ForInStep.bindM (visit l b) fun b => ForInStep.bindM (f v b) (visit r ·) instance : ForIn m (RBNode α) α where forIn := RBNode.forIn /-- An auxiliary data structure (an iterator) over an `RBNode` which lazily pulls elements from the left. -/ protected inductive Stream (α : Type _) | /-- The stream is empty. -/ nil | /-- We are ready to deliver element `v` with right child `r`, and where `tail` represents all the subtrees we have yet to destructure. -/ cons (v : α) (r : RBNode α) (tail : RBNode.Stream α) /-- `O(log n)`. Turn a node into a stream, by descending along the left spine. -/ def toStream : RBNode α → (_ : RBNode.Stream α := .nil) → RBNode.Stream α | nil, acc => acc | node _ l v r, acc => toStream l (.cons v r acc) namespace Stream /-- `O(1)` amortized, `O(log n)` worst case: Get the next element from the stream. -/ def next? : RBNode.Stream α → Option (α × RBNode.Stream α) | nil => none | cons v r tail => some (v, toStream r tail) /-- Fold a function on the values from left to right (in increasing order). -/ @[specialize] def foldl (f : σ → α → σ) : (init : σ) → RBNode.Stream α → σ | b, nil => b | b, cons v r tail => foldl f (r.foldl f (f b v)) tail /-- Fold a function on the values from right to left (in decreasing order). -/ @[specialize] def foldr (f : α → σ → σ) : RBNode.Stream α → (init : σ) → σ | nil, b => b | cons v r tail, b => f v <| r.foldr f <| tail.foldr f b /-- `O(n)`. Convert the stream to a list in ascending order. -/ def toList (t : RBNode.Stream α) : List α := t.foldr (·::·) [] end Stream instance : ToStream (RBNode α) (RBNode.Stream α) := ⟨(·.toStream)⟩ instance : Stream (RBNode.Stream α) α := ⟨Stream.next?⟩ /-- Returns `true` iff every element of the tree satisfies `p`. -/ @[specialize] def all (p : α → Bool) : RBNode α → Bool | nil => true | node _ l v r => p v && all p l && all p r /-- Returns `true` iff any element of the tree satisfies `p`. -/ @[specialize] def any (p : α → Bool) : RBNode α → Bool | nil => false | node _ l v r => p v || any p l || any p r /-- Asserts that `p` holds on every element of the tree. -/ def All (p : α → Prop) : RBNode α → Prop | nil => True | node _ l v r => p v ∧ All p l ∧ All p r theorem All.imp (H : ∀ {x : α}, p x → q x) : ∀ {t : RBNode α}, t.All p → t.All q | nil => id | node .. => fun ⟨h, hl, hr⟩ => ⟨H h, hl.imp H, hr.imp H⟩ /-- Asserts that `p` holds on some element of the tree. -/ def Any (p : α → Prop) : RBNode α → Prop | nil => False | node _ l v r => p v ∨ Any p l ∨ Any p r /-- True if `x` is an element of `t` "exactly", i.e. up to equality, not the `cmp` relation. -/ def EMem (x : α) (t : RBNode α) : Prop := t.Any (x = ·) instance : Membership α (RBNode α) := ⟨EMem⟩ /-- True if the specified `cut` matches at least one element of of `t`. -/ def MemP (cut : α → Ordering) (t : RBNode α) : Prop := t.Any (cut · = .eq) /-- True if `x` is equivalent to an element of `t`. -/ @[reducible] def Mem (cmp : α → α → Ordering) (x : α) (t : RBNode α) : Prop := MemP (cmp x) t /-- Asserts that `t₁` and `t₂` have the same number of elements in the same order, and `R` holds pairwise between them. The tree structure is ignored. -/ @[specialize] def all₂ (R : α → β → Bool) (t₁ : RBNode α) (t₂ : RBNode β) : Bool := let result := StateT.run (s := t₂.toStream) <| t₁.forM fun a s => do let (b, s) ← s.next? bif R a b then pure (⟨⟩, s) else none result matches some (_, .nil) instance [BEq α] : BEq (RBNode α) where beq a b := a.all₂ (· == ·) b /-- We say that `x < y` under the comparator `cmp` if `cmp x y = .lt`. * In order to avoid assuming the comparator is always lawful, we use a local `∀ [TransCmp cmp]` binder in the relation so that the ordering properties of the tree only need to hold if the comparator is lawful. * The `Nonempty` wrapper is a no-op because this is already a proposition, but it prevents the `[TransCmp cmp]` binder from being introduced when we don't want it. -/ def cmpLT (cmp : α → α → Ordering) (x y : α) : Prop := Nonempty (∀ [TransCmp cmp], cmp x y = .lt) /-- We say that `x ≈ y` under the comparator `cmp` if `cmp x y = .eq`. See also `cmpLT`. -/ def cmpEq (cmp : α → α → Ordering) (x y : α) : Prop := Nonempty (∀ [TransCmp cmp], cmp x y = .eq) /-- The first half of Okasaki's `balance`, concerning red-red sequences in the left child. -/ @[inline] def balance1 : RBNode α → α → RBNode α → RBNode α | node red (node red a x b) y c, z, d | node red a x (node red b y c), z, d => node red (node black a x b) y (node black c z d) | a, x, b => node black a x b /-- The second half of Okasaki's `balance`, concerning red-red sequences in the right child. -/ @[inline] def balance2 : RBNode α → α → RBNode α → RBNode α | a, x, node red (node red b y c) z d | a, x, node red b y (node red c z d) => node red (node black a x b) y (node black c z d) | a, x, b => node black a x b /-- Returns `red` if the node is red, otherwise `black`. (Nil nodes are treated as `black`.) -/ @[inline] def isRed : RBNode α → RBColor | node c .. => c | _ => black /-- Returns `black` if the node is black, otherwise `red`. (Nil nodes are treated as `red`, which is not the usual convention but useful for deletion.) -/ @[inline] def isBlack : RBNode α → RBColor | node c .. => c | _ => red /-- Change the color of the root to `black`. -/ def setBlack : RBNode α → RBNode α | nil => nil | node _ l v r => node black l v r section Insert /-- The core of the `insert` function. This adds an element `x` to a balanced red-black tree. Importantly, the result of calling `ins` is not a proper red-black tree, because it has a broken balance invariant. (See `Balanced.ins` for the balance invariant of `ins`.) The `insert` function does the final fixup needed to restore the invariant. -/ @[specialize] def ins (cmp : α → α → Ordering) (x : α) : RBNode α → RBNode α | nil => node red nil x nil | node red a y b => match cmp x y with | Ordering.lt => node red (ins cmp x a) y b | Ordering.gt => node red a y (ins cmp x b) | Ordering.eq => node red a x b | node black a y b => match cmp x y with | Ordering.lt => balance1 (ins cmp x a) y b | Ordering.gt => balance2 a y (ins cmp x b) | Ordering.eq => node black a x b /-- `insert cmp t v` inserts element `v` into the tree, using the provided comparator `cmp` to put it in the right place and automatically rebalancing the tree as necessary. -/ @[specialize] def insert (cmp : α → α → Ordering) (t : RBNode α) (v : α) : RBNode α := match isRed t with | red => (ins cmp v t).setBlack | black => ins cmp v t end Insert /-- Recolor the root of the tree to `red` if possible. -/ def setRed : RBNode α → RBNode α | node _ a v b => node red a v b | nil => nil /-- Rebalancing a tree which has shrunk on the left. -/ def balLeft (l : RBNode α) (v : α) (r : RBNode α) : RBNode α := match l with | node red a x b => node red (node black a x b) v r | l => match r with | node black a y b => balance2 l v (node red a y b) | node red (node black a y b) z c => node red (node black l v a) y (balance2 b z (setRed c)) | r => node red l v r -- unreachable /-- Rebalancing a tree which has shrunk on the right. -/ def balRight (l : RBNode α) (v : α) (r : RBNode α) : RBNode α := match r with | node red b y c => node red l v (node black b y c) | r => match l with | node black a x b => balance1 (node red a x b) v r | node red a x (node black b y c) => node red (balance1 (setRed a) x b) y (node black c v r) | l => node red l v r -- unreachable /-- The number of nodes in the tree. -/ @[simp] def size : RBNode α → Nat | nil => 0 | node _ x _ y => x.size + y.size + 1 /-- Concatenate two trees with the same black-height. -/ def append : RBNode α → RBNode α → RBNode α | nil, x | x, nil => x | node red a x b, node red c y d => match append b c with | node red b' z c' => node red (node red a x b') z (node red c' y d) | bc => node red a x (node red bc y d) | node black a x b, node black c y d => match append b c with | node red b' z c' => node red (node black a x b') z (node black c' y d) | bc => balLeft a x (node black bc y d) | a@(node black ..), node red b x c => node red (append a b) x c | node red a x b, c@(node black ..) => node red a x (append b c) termination_by _ x y => x.size + y.size /-! ## erase -/ /-- The core of the `erase` function. The tree returned from this function has a broken invariant, which is restored in `erase`. -/ @[specialize] def del (cut : α → Ordering) : RBNode α → RBNode α | nil => nil | node _ a y b => match cut y with | .lt => match a.isBlack with | black => balLeft (del cut a) y b | red => node red (del cut a) y b | .gt => match b.isBlack with | black => balRight a y (del cut b) | red => node red a y (del cut b) | .eq => append a b /-- The `erase cut t` function removes an element from the tree `t`. The `cut` function is used to locate an element in the tree: it returns `.gt` if we go too high and `.lt` if we go too low; if it returns `.eq` we will remove the element. (The function `cmp k` for some key `k` is a valid cut function, but we can also use cuts that are not of this form as long as they are suitably monotonic.) -/ @[specialize] def erase (cut : α → Ordering) (t : RBNode α) : RBNode α := (del cut t).setBlack /-- Finds an element in the tree satisfying the `cut` function. -/ @[specialize] def find? (cut : α → Ordering) : RBNode α → Option α | nil => none | node _ a y b => match cut y with | .lt => find? cut a | .gt => find? cut b | .eq => some y /-- `lowerBound? cut` retrieves the largest entry smaller than or equal to `cut`, if it exists. -/ @[specialize] def lowerBound? (cut : α → Ordering) : RBNode α → Option α → Option α | nil, lb => lb | node _ a y b, lb => match cut y with | .lt => lowerBound? cut a lb | .gt => lowerBound? cut b (some y) | .eq => some y /-- Returns the root of the tree, if any. -/ def root? : RBNode α → Option α | nil => none | node _ _ v _ => some v /-- `O(n)`. Map a function on every value in the tree. This requires `IsMonotone` on the function in order to preserve the order invariant. -/ @[specialize] def map (f : α → β) : RBNode α → RBNode β | nil => nil | node c l v r => node c (l.map f) (f v) (r.map f) /-- Converts the tree into an array in increasing sorted order. -/ def toArray (n : RBNode α) : Array α := n.foldl (init := #[]) (·.push ·) /-- A `RBNode.Path α` is a "cursor" into an `RBNode` which represents the path from the root to a subtree. Note that the path goes from the target subtree up to the root, which is reversed from the normal way data is stored in the tree. See [Zipper](https://en.wikipedia.org/wiki/Zipper_(data_structure)) for more information. -/ inductive Path (α : Type u) where /-- The root of the tree, which is the end of the path of parents. -/ | root /-- A path that goes down the left subtree. -/ | left (c : RBColor) (parent : Path α) (v : α) (r : RBNode α) /-- A path that goes down the right subtree. -/ | right (c : RBColor) (l : RBNode α) (v : α) (parent : Path α) /-- Fills the `Path` with a subtree. -/ def Path.fill : Path α → RBNode α → RBNode α | .root, t => t | .left c parent y b, a | .right c a y parent, b => parent.fill (node c a y b) /-- Like `find?`, but instead of just returning the element, it returns the entire subtree at the element and a path back to the root for reconstructing the tree. -/ @[specialize] def zoom (cut : α → Ordering) : RBNode α → (e : Path α := .root) → RBNode α × Path α | nil, path => (nil, path) | n@(node c a y b), path => match cut y with | .lt => zoom cut a (.left c path y b) | .gt => zoom cut b (.right c a y path) | .eq => (n, path) /-- This function does the second part of `RBNode.ins`, which unwinds the stack and rebuilds the tree. -/ def Path.ins : Path α → RBNode α → RBNode α | .root, t => t.setBlack | .left red parent y b, a | .right red a y parent, b => parent.ins (node red a y b) | .left black parent y b, a => parent.ins (balance1 a y b) | .right black a y parent, b => parent.ins (balance2 a y b) /-- `path.insertNew v` inserts element `v` into the tree, assuming that `path` is zoomed in on a `nil` node such that inserting a new element at this position is valid. -/ @[inline] def Path.insertNew (path : Path α) (v : α) : RBNode α := path.ins (node red nil v nil) /-- `path.insert t v` inserts element `v` into the tree, assuming that `(t, path)` was the result of a previous `zoom` operation (so either the root of `t` is equivalent to `v` or it is empty). -/ def Path.insert (path : Path α) (t : RBNode α) (v : α) : RBNode α := match t with | nil => path.insertNew v | node c a _ b => path.fill (node c a v b) /-- `path.del t c` does the second part of `RBNode.del`, which unwinds the stack and rebuilds the tree. The `c` argument is the color of the node before the deletion (we used `t₀.isBlack` for this in `RBNode.del` but the original tree is no longer available in this formulation). -/ def Path.del : Path α → RBNode α → RBColor → RBNode α | .root, t, _ => t.setBlack | .left c parent y b, a, red | .right c a y parent, b, red => parent.del (node red a y b) c | .left c parent y b, a, black => parent.del (balLeft a y b) c | .right c a y parent, b, black => parent.del (balRight a y b) c /-- `path.erase t v` removes the root element of `t` from the tree, assuming that `(t, path)` was the result of a previous `zoom` operation. -/ def Path.erase (path : Path α) (t : RBNode α) : RBNode α := match t with | nil => path.fill nil | node c a _ b => path.del (a.append b) c /-- `modify cut f t` uses `cut` to find an element, then modifies the element using `f` and reinserts it into the tree. Because the tree structure is not modified, `f` must not modify the ordering properties of the element. The element in `t` is used linearly if `t` is unshared. -/ @[specialize] def modify (cut : α → Ordering) (f : α → α) (t : RBNode α) : RBNode α := match zoom cut t with | (nil, _) => t -- TODO: profile whether it would be better to use `path.fill nil` here | (node c a x b, path) => path.fill (node c a (f x) b) /-- `alter cut f t` simultaneously handles inserting, erasing and replacing an element using a function `f : Option α → Option α`. It is passed the result of `t.find? cut` and can either return `none` to remove the element or `some a` to replace/insert the element with `a` (which must have the same ordering properties as the original element). The element is used linearly if `t` is unshared. -/ @[specialize] def alter (cut : α → Ordering) (f : Option α → Option α) (t : RBNode α) : RBNode α := match zoom cut t with | (nil, path) => match f none with | none => t -- TODO: profile whether it would be better to use `path.fill nil` here | some y => path.insertNew y | (node c a x b, path) => match f (some x) with | none => path.del (a.append b) c | some y => path.fill (node c a y b) /-- The ordering invariant of a red-black tree, which is a binary search tree. This says that every element of a left subtree is less than the root, and every element in the right subtree is greater than the root, where the less than relation `x < y` is understood to mean `cmp x y = .lt`. Because we do not assume that `cmp` is lawful when stating this property, we write it in such a way that if `cmp` is not lawful then the condition holds trivially. That way we can prove the ordering invariants without assuming `cmp` is lawful. -/ def Ordered (cmp : α → α → Ordering) : RBNode α → Prop | nil => True | node _ a x b => a.All (cmpLT cmp · x) ∧ b.All (cmpLT cmp x ·) ∧ a.Ordered cmp ∧ b.Ordered cmp /-- The red-black balance invariant. `Balanced t c n` says that the color of the root node is `c`, and the black-height (the number of black nodes on any path from the root) of the tree is `n`. Additionally, every red node must have black children. -/ inductive Balanced : RBNode α → RBColor → Nat → Prop where /-- A nil node is balanced with black-height 0, and it is considered black. -/ | protected nil : Balanced nil black 0 /-- A red node is balanced with black-height `n` if its children are both black with with black-height `n`. -/ | protected red : Balanced x black n → Balanced y black n → Balanced (node red x v y) red n /-- A black node is balanced with black-height `n + 1` if its children both have black-height `n`. -/ | protected black : Balanced x c₁ n → Balanced y c₂ n → Balanced (node black x v y) black (n + 1) /-- The well-formedness invariant for a red-black tree. The first constructor is the real invariant, and the others allow us to "cheat" in this file and define `insert` and `erase`, which have more complex proofs that are delayed to `Std.Data.RBMap.Lemmas`. -/ inductive WF (cmp : α → α → Ordering) : RBNode α → Prop /-- The actual well-formedness invariant: a red-black tree has the ordering and balance invariants. -/ | mk : t.Ordered cmp → t.Balanced c n → WF cmp t /-- Inserting into a well-formed tree yields another well-formed tree. (See `Ordered.insert` and `Balanced.insert` for the actual proofs.) -/ | insert : WF cmp t → WF cmp (t.insert cmp a) /-- Erasing from a well-formed tree yields another well-formed tree. (See `Ordered.erase` and `Balanced.erase` for the actual proofs.) -/ | erase : WF cmp t → WF cmp (t.erase cut) end RBNode open RBNode /-- An `RBSet` is a self-balancing binary search tree. The `cmp` function is the comparator that will be used for performing searches; it should satisfy the requirements of `TransCmp` for it to have sensible behavior. -/ def RBSet (α : Type u) (cmp : α → α → Ordering) : Type u := {t : RBNode α // t.WF cmp} /-- `O(1)`. Construct a new empty tree. -/ @[inline] def mkRBSet (α : Type u) (cmp : α → α → Ordering) : RBSet α cmp := ⟨.nil, .mk ⟨⟩ .nil⟩ namespace RBSet /-- `O(1)`. Construct a new empty tree. -/ @[inline] def empty : RBSet α cmp := mkRBSet .. instance (α : Type u) (cmp : α → α → Ordering) : EmptyCollection (RBSet α cmp) := ⟨empty⟩ instance (α : Type u) (cmp : α → α → Ordering) : Inhabited (RBSet α cmp) := ⟨∅⟩ /-- `O(1)`. Construct a new tree with one element `v`. -/ @[inline] def single (v : α) : RBSet α cmp := ⟨.node .red .nil v .nil, .mk ⟨⟨⟩, ⟨⟩, ⟨⟩, ⟨⟩⟩ (.red .nil .nil)⟩ /-- `O(n)`. Fold a function on the values from left to right (in increasing order). -/ @[inline] def foldl (f : σ → α → σ) (init : σ) (t : RBSet α cmp) : σ := t.1.foldl f init /-- `O(n)`. Fold a function on the values from right to left (in decreasing order). -/ @[inline] def foldr (f : α → σ → σ) (init : σ) (t : RBSet α cmp) : σ := t.1.foldr f init /-- `O(n)`. Fold a monadic function on the values from left to right (in increasing order). -/ @[inline] def foldlM [Monad m] (f : σ → α → m σ) (init : σ) (t : RBSet α cmp) : m σ := t.1.foldlM f init /-- `O(n)`. Run monadic function `f` on each element of the tree (in increasing order). -/ @[inline] def forM [Monad m] (f : α → m PUnit) (t : RBSet α cmp) : m PUnit := t.1.forM f instance : ForIn m (RBSet α cmp) α where forIn t := t.1.forIn instance : ToStream (RBSet α cmp) (RBNode.Stream α) := ⟨fun x => x.1.toStream .nil⟩ /-- `O(1)`. Is the tree empty? -/ @[inline] def isEmpty : RBSet α cmp → Bool | ⟨nil, _⟩ => true | _ => false /-- `O(n)`. Convert the tree to a list in ascending order. -/ @[inline] def toList (t : RBSet α cmp) : List α := t.1.toList /-- `O(log n)`. Returns the entry `a` such that `a ≤ k` for all keys in the RBSet. -/ @[inline] protected def min (t : RBSet α cmp) : Option α := t.1.min /-- `O(log n)`. Returns the entry `a` such that `a ≥ k` for all keys in the RBSet. -/ @[inline] protected def max (t : RBSet α cmp) : Option α := t.1.max instance [Repr α] : Repr (RBSet α cmp) where reprPrec m prec := Repr.addAppParen ("RBSet.ofList " ++ repr m.toList) prec /-- `O(log n)`. Insert element `v` into the tree. -/ @[inline] def insert (t : RBSet α cmp) (v : α) : RBSet α cmp := ⟨t.1.insert cmp v, t.2.insert⟩ /-- `O(log n)`. Remove an element from the tree using a cut function. The `cut` function is used to locate an element in the tree: it returns `.gt` if we go too high and `.lt` if we go too low; if it returns `.eq` we will remove the element. (The function `cmp k` for some key `k` is a valid cut function, but we can also use cuts that are not of this form as long as they are suitably monotonic.) -/ @[inline] def erase (t : RBSet α cmp) (cut : α → Ordering) : RBSet α cmp := ⟨t.1.erase cut, t.2.erase⟩ /-- `O(log n)`. Find an element in the tree using a cut function. -/ @[inline] def findP? (t : RBSet α cmp) (cut : α → Ordering) : Option α := t.1.find? cut /-- `O(log n)`. Returns an element in the tree equivalent to `x` if one exists. -/ @[inline] def find? (t : RBSet α cmp) (x : α) : Option α := t.1.find? (cmp x) /-- `O(log n)`. Find an element in the tree, or return a default value `v₀`. -/ @[inline] def findPD (t : RBSet α cmp) (cut : α → Ordering) (v₀ : α) : α := (t.findP? cut).getD v₀ /-- `O(log n)`. `lowerBoundP cut` retrieves the largest entry comparing `lt` or `eq` under `cut`, if it exists. -/ @[inline] def lowerBoundP? (t : RBSet α cmp) (cut : α → Ordering) : Option α := t.1.lowerBound? cut none /-- `O(log n)`. `lowerBound? k` retrieves the largest entry smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound? (t : RBSet α cmp) (k : α) : Option α := t.1.lowerBound? (cmp k) none /-- `O(log n)`. Returns true if the given cut returns `eq` for something in the RBSet. -/ @[inline] def containsP (t : RBSet α cmp) (cut : α → Ordering) : Bool := (t.findP? cut).isSome /-- `O(log n)`. Returns true if the given key `a` is in the RBSet. -/ @[inline] def contains (t : RBSet α cmp) (a : α) : Bool := (t.find? a).isSome /-- `O(n log n)`. Build a tree from an unsorted list by inserting them one at a time. -/ @[inline] def ofList (l : List α) (cmp : α → α → Ordering) : RBSet α cmp := l.foldl (fun r p => r.insert p) (mkRBSet α cmp) /-- `O(n log n)`. Build a tree from an unsorted array by inserting them one at a time. -/ @[inline] def ofArray (l : Array α) (cmp : α → α → Ordering) : RBSet α cmp := l.foldl (fun r p => r.insert p) (mkRBSet α cmp) /-- `O(n)`. Returns true if the given predicate is true for all items in the RBSet. -/ @[inline] def all (t : RBSet α cmp) (p : α → Bool) : Bool := t.1.all p /-- `O(n)`. Returns true if the given predicate is true for any item in the RBSet. -/ @[inline] def any (t : RBSet α cmp) (p : α → Bool) : Bool := t.1.any p /-- Asserts that `t₁` and `t₂` have the same number of elements in the same order, and `R` holds pairwise between them. The tree structure is ignored. -/ @[inline] def all₂ (R : α → β → Bool) (t₁ : RBSet α cmpα) (t₂ : RBSet β cmpβ) : Bool := t₁.1.all₂ R t₂.1 /-- True if `x` is an element of `t` "exactly", i.e. up to equality, not the `cmp` relation. -/ def EMem (x : α) (t : RBSet α cmp) : Prop := t.1.EMem x /-- True if the specified `cut` matches at least one element of of `t`. -/ def MemP (cut : α → Ordering) (t : RBSet α cmp) : Prop := t.1.MemP cut /-- True if `x` is equivalent to an element of `t`. -/ def Mem (x : α) (t : RBSet α cmp) : Prop := MemP (cmp x) t instance : Membership α (RBSet α cmp) := ⟨Mem⟩ /-- Returns true if `t₁` and `t₂` are equal as sets (assuming `cmp` and `==` are compatible), ignoring the internal tree structure. -/ instance [BEq α] : BEq (RBSet α cmp) where beq a b := a.all₂ (· == ·) b /-- `O(n)`. The number of items in the RBSet. -/ def size (m : RBSet α cmp) : Nat := m.1.size /-- `O(log n)`. Returns the minimum element of the tree, or panics if the tree is empty. -/ @[inline] def min! [Inhabited α] (t : RBSet α cmp) : α := t.min.getD (panic! "tree is empty") /-- `O(log n)`. Returns the maximum element of the tree, or panics if the tree is empty. -/ @[inline] def max! [Inhabited α] (t : RBSet α cmp) : α := t.max.getD (panic! "tree is empty") /-- `O(log n)`. Attempts to find the value with key `k : α` in `t` and panics if there is no such key. -/ @[inline] def findP! [Inhabited α] (t : RBSet α cmp) (cut : α → Ordering) : α := (t.findP? cut).getD (panic! "key is not in the tree") /-- `O(log n)`. Attempts to find the value with key `k : α` in `t` and panics if there is no such key. -/ @[inline] def find! [Inhabited α] (t : RBSet α cmp) (k : α) : α := (t.find? k).getD (panic! "key is not in the tree") /-- The predicate asserting that the result of `modifyP` is safe to construct. -/ class ModifyWF (t : RBSet α cmp) (cut : α → Ordering) (f : α → α) : Prop where /-- The resulting tree is well formed. -/ wf : (t.1.modify cut f).WF cmp /-- `O(log n)`. In-place replace an element found by `cut`. This takes the element out of the tree while `f` runs, so it uses the element linearly if `t` is unshared. The `ModifyWF` assumption is required because `f` may change the ordering properties of the element, which would break the invariants. -/ def modifyP (t : RBSet α cmp) (cut : α → Ordering) (f : α → α) [wf : ModifyWF t cut f] : RBSet α cmp := ⟨t.1.modify cut f, wf.wf⟩ /-- The predicate asserting that the result of `alterP` is safe to construct. -/ class AlterWF (t : RBSet α cmp) (cut : α → Ordering) (f : Option α → Option α) : Prop where /-- The resulting tree is well formed. -/ wf : (t.1.alter cut f).WF cmp /-- `O(log n)`. `alterP cut f t` simultaneously handles inserting, erasing and replacing an element using a function `f : Option α → Option α`. It is passed the result of `t.findP? cut` and can either return `none` to remove the element or `some a` to replace/insert the element with `a` (which must have the same ordering properties as the original element). The element is used linearly if `t` is unshared. The `AlterWF` assumption is required because `f` may change the ordering properties of the element, which would break the invariants. -/ def alterP (t : RBSet α cmp) (cut : α → Ordering) (f : Option α → Option α) [wf : AlterWF t cut f] : RBSet α cmp := ⟨t.1.alter cut f, wf.wf⟩ /-- `O(n₂ * log (n₁ + n₂))`. Merges the maps `t₁` and `t₂`. If equal keys exist in both, the key from `t₂` is preferred. -/ def union (t₁ t₂ : RBSet α cmp) : RBSet α cmp := t₂.foldl .insert t₁ /-- `O(n₂ * log (n₁ + n₂))`. Merges the maps `t₁` and `t₂`. If equal keys exist in both, then use `mergeFn a₁ a₂` to produce the new merged value. -/ def mergeWith (mergeFn : α → α → α) (t₁ t₂ : RBSet α cmp) : RBSet α cmp := t₂.foldl (init := t₁) fun t₁ a₂ => t₁.insert <| match t₁.find? a₂ with | some a₁ => mergeFn a₁ a₂ | none => a₂ /-- `O(n₁ * log (n₁ + n₂))`. Intersects the maps `t₁` and `t₂` using `mergeFn a b` to produce the new value. -/ def intersectWith (cmp : α → β → Ordering) (mergeFn : α → β → γ) (t₁ : RBSet α cmpα) (t₂ : RBSet β cmpβ) : RBSet γ cmpγ := t₁.foldl (init := ∅) fun acc a => match t₂.findP? (cmp a) with | some b => acc.insert <| mergeFn a b | none => acc /-- `O(n * log n)`. Constructs the set of all elements satisfying `p`. -/ def filter (t : RBSet α cmp) (p : α → Bool) : RBSet α cmp := t.foldl (init := ∅) fun acc a => bif p a then acc.insert a else acc /-- `O(n₁ * (log n₁ + log n₂))`. Constructs the set of all elements of `t₁` that are not in `t₂`. -/ def sdiff (t₁ t₂ : RBSet α cmp) : RBSet α cmp := t₁.filter (!t₂.contains ·) end RBSet /- TODO(Leo): define dRBMap -/ /-- An `RBMap` is a self-balancing binary search tree, used to store a key-value map. The `cmp` function is the comparator that will be used for performing searches; it should satisfy the requirements of `TransCmp` for it to have sensible behavior. -/ def RBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Type (max u v) := RBSet (α × β) (byKey Prod.fst cmp) /-- `O(1)`. Construct a new empty map. -/ @[inline] def mkRBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : RBMap α β cmp := mkRBSet .. /-- `O(1)`. Construct a new empty map. -/ @[inline] def RBMap.empty {α : Type u} {β : Type v} {cmp : α → α → Ordering} : RBMap α β cmp := mkRBMap .. instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : EmptyCollection (RBMap α β cmp) := ⟨RBMap.empty⟩ instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Inhabited (RBMap α β cmp) := ⟨∅⟩ /-- `O(1)`. Construct a new tree with one key-value pair `k, v`. -/ @[inline] def RBMap.single (k : α) (v : β) : RBMap α β cmp := RBSet.single (k, v) namespace RBMap variable {α : Type u} {β : Type v} {σ : Type w} {cmp : α → α → Ordering} /-- `O(n)`. Fold a function on the values from left to right (in increasing order). -/ @[inline] def foldl (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.foldl (fun s (a, b) => f s a b) b /-- `O(n)`. Fold a function on the values from right to left (in decreasing order). -/ @[inline] def foldr (f : α → β → σ → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.foldr (fun (a, b) s => f a b s) b /-- `O(n)`. Fold a monadic function on the values from left to right (in increasing order). -/ @[inline] def foldlM [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β cmp → m σ | b, ⟨t, _⟩ => t.foldlM (fun s (a, b) => f s a b) b /-- `O(n)`. Run monadic function `f` on each element of the tree (in increasing order). -/ @[inline] def forM [Monad m] (f : α → β → m PUnit) (t : RBMap α β cmp) : m PUnit := t.foldlM (fun _ k v => f k v) ⟨⟩ instance : ForIn m (RBMap α β cmp) (α × β) := inferInstanceAs (ForIn _ (RBSet ..) _) instance : ToStream (RBMap α β cmp) (RBNode.Stream (α × β)) := inferInstanceAs (ToStream (RBSet ..) _) /-- `O(n)`. Constructs the array of keys of the map. -/ @[inline] def keysArray (t : RBMap α β cmp) : Array α := t.1.foldl (init := #[]) (·.push ·.1) /-- `O(n)`. Constructs the list of keys of the map. -/ @[inline] def keysList (t : RBMap α β cmp) : List α := t.1.foldr (init := []) (·.1 :: ·) /-- An "iterator" over the keys of the map. This is a trivial wrapper over the underlying map, but it comes with a small API to use it in a `for` loop or convert it to an array or list. -/ def Keys (α β cmp) := RBMap α β cmp /-- The keys of the map. This is an `O(1)` wrapper operation, which can be used in `for` loops or converted to an array or list. -/ @[inline] def keys (t : RBMap α β cmp) : Keys α β cmp := t @[inline, inherit_doc keysArray] def Keys.toArray := @keysArray @[inline, inherit_doc keysList] def Keys.toList := @keysList instance : CoeHead (Keys α β cmp) (Array α) := ⟨keysArray⟩ instance : CoeHead (Keys α β cmp) (List α) := ⟨keysList⟩ instance : ForIn m (Keys α β cmp) α where forIn t init f := t.val.forIn init (f ·.1) instance : ForM m (Keys α β cmp) α where forM t f := t.val.forM (f ·.1) /-- The result of `toStream` on a `Keys`. -/ def Keys.Stream (α β) := RBNode.Stream (α × β) /-- A stream over the iterator. -/ def Keys.toStream (t : Keys α β cmp) : Keys.Stream α β := t.1.toStream /-- `O(1)` amortized, `O(log n)` worst case: Get the next element from the stream. -/ def Keys.Stream.next? (t : Stream α β) : Option (α × Stream α β) := match inline (RBNode.Stream.next? t) with | none => none | some ((a, _), t) => some (a, t) instance : ToStream (Keys α β cmp) (Keys.Stream α β) := ⟨Keys.toStream⟩ instance : Stream (Keys.Stream α β) α := ⟨Keys.Stream.next?⟩ /-- `O(n)`. Constructs the array of values of the map. -/ @[inline] def valuesArray (t : RBMap α β cmp) : Array β := t.1.foldl (init := #[]) (·.push ·.2) /-- `O(n)`. Constructs the list of values of the map. -/ @[inline] def valuesList (t : RBMap α β cmp) : List β := t.1.foldr (init := []) (·.2 :: ·) /-- An "iterator" over the values of the map. This is a trivial wrapper over the underlying map, but it comes with a small API to use it in a `for` loop or convert it to an array or list. -/ def Values (α β cmp) := RBMap α β cmp /-- The "keys" of the map. This is an `O(1)` wrapper operation, which can be used in `for` loops or converted to an array or list. -/ @[inline] def values (t : RBMap α β cmp) : Values α β cmp := t @[inline, inherit_doc valuesArray] def Values.toArray := @valuesArray @[inline, inherit_doc valuesList] def Values.toList := @valuesList instance : CoeHead (Values α β cmp) (Array β) := ⟨valuesArray⟩ instance : CoeHead (Values α β cmp) (List β) := ⟨valuesList⟩ instance : ForIn m (Values α β cmp) β where forIn t init f := t.val.forIn init (f ·.2) instance : ForM m (Values α β cmp) β where forM t f := t.val.forM (f ·.2) /-- The result of `toStream` on a `Values`. -/ def Values.Stream (α β) := RBNode.Stream (α × β) /-- A stream over the iterator. -/ def Values.toStream (t : Values α β cmp) : Values.Stream α β := t.1.toStream /-- `O(1)` amortized, `O(log n)` worst case: Get the next element from the stream. -/ def Values.Stream.next? (t : Stream α β) : Option (β × Stream α β) := match inline (RBNode.Stream.next? t) with | none => none | some ((_, b), t) => some (b, t) instance : ToStream (Values α β cmp) (Values.Stream α β) := ⟨Values.toStream⟩ instance : Stream (Values.Stream α β) β := ⟨Values.Stream.next?⟩ /-- `O(1)`. Is the tree empty? -/ @[inline] def isEmpty : RBMap α β cmp → Bool := RBSet.isEmpty /-- `O(n)`. Convert the tree to a list in ascending order. -/ @[inline] def toList : RBMap α β cmp → List (α × β) := RBSet.toList /-- `O(log n)`. Returns the key-value pair `(a, b)` such that `a ≤ k` for all keys in the RBMap. -/ @[inline] protected def min : RBMap α β cmp → Option (α × β) := RBSet.min /-- `O(log n)`. Returns the key-value pair `(a, b)` such that `a ≥ k` for all keys in the RBMap. -/ @[inline] protected def max : RBMap α β cmp → Option (α × β) := RBSet.max instance [Repr α] [Repr β] : Repr (RBMap α β cmp) where reprPrec m prec := Repr.addAppParen ("RBMap.ofList " ++ repr m.toList) prec /-- `O(log n)`. Insert key-value pair `(k, v)` into the tree. -/ @[inline] def insert (t : RBMap α β cmp) (k : α) (v : β) : RBMap α β cmp := RBSet.insert t (k, v) /-- `O(log n)`. Remove an element `k` from the map. -/ @[inline] def erase (t : RBMap α β cmp) (k : α) : RBMap α β cmp := RBSet.erase t (cmp k ·.1) /-- `O(n log n)`. Build a tree from an unsorted list by inserting them one at a time. -/ @[inline] def ofList (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBSet.ofList l _ /-- `O(n log n)`. Build a tree from an unsorted array by inserting them one at a time. -/ @[inline] def ofArray (l : Array (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBSet.ofArray l _ /-- `O(log n)`. Find an entry in the tree with key equal to `k`. -/ @[inline] def findEntry? (t : RBMap α β cmp) (k : α) : Option (α × β) := t.findP? (cmp k ·.1) /-- `O(log n)`. Find the value corresponding to key `k`. -/ @[inline] def find? (t : RBMap α β cmp) (k : α) : Option β := t.findEntry? k |>.map (·.2) /-- `O(log n)`. Find the value corresponding to key `k`, or return `v₀` if it is not in the map. -/ @[inline] def findD (t : RBMap α β cmp) (k : α) (v₀ : β) : β := (t.find? k).getD v₀ /-- `O(log n)`. `lowerBound? k` retrieves the key-value pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound? (t : RBMap α β cmp) (k : α) : Option (α × β) := RBSet.lowerBoundP? t (cmp k ·.1) /-- `O(log n)`. Returns true if the given key `a` is in the RBMap. -/ @[inline] def contains (t : RBMap α β cmp) (a : α) : Bool := (t.findEntry? a).isSome /-- `O(n)`. Returns true if the given predicate is true for all items in the RBMap. -/ @[inline] def all (t : RBMap α β cmp) (p : α → β → Bool) : Bool := RBSet.all t fun (a, b) => p a b /-- `O(n)`. Returns true if the given predicate is true for any item in the RBMap. -/ @[inline] def any (t : RBMap α β cmp) (p : α → β → Bool) : Bool := RBSet.any t fun (a, b) => p a b /-- Asserts that `t₁` and `t₂` have the same number of elements in the same order, and `R` holds pairwise between them. The tree structure is ignored. -/ @[inline] def all₂ (R : α × β → γ × δ → Bool) (t₁ : RBMap α β cmpα) (t₂ : RBMap γ δ cmpγ) : Bool := RBSet.all₂ R t₁ t₂ /-- Asserts that `t₁` and `t₂` have the same set of keys (up to equality). -/ @[inline] def eqKeys (t₁ : RBMap α β cmp) (t₂ : RBMap α γ cmp) : Bool := t₁.all₂ (cmp ·.1 ·.1 = .eq) t₂ /-- Returns true if `t₁` and `t₂` have the same keys and values (assuming `cmp` and `==` are compatible), ignoring the internal tree structure. -/ instance [BEq α] [BEq β] : BEq (RBMap α β cmp) := inferInstanceAs (BEq (RBSet ..)) /-- `O(n)`. The number of items in the RBMap. -/ def size : RBMap α β cmp → Nat := RBSet.size /-- `O(log n)`. Returns the minimum element of the map, or panics if the map is empty. -/ @[inline] def min! [Inhabited α] [Inhabited β] : RBMap α β cmp → α × β := RBSet.min! /-- `O(log n)`. Returns the maximum element of the map, or panics if the map is empty. -/ @[inline] def max! [Inhabited α] [Inhabited β] : RBMap α β cmp → α × β := RBSet.max! /-- Attempts to find the value with key `k : α` in `t` and panics if there is no such key. -/ @[inline] def find! [Inhabited β] (t : RBMap α β cmp) (k : α) : β := (t.find? k).getD (panic! "key is not in the map") /-- `O(n₂ * log (n₁ + n₂))`. Merges the maps `t₁` and `t₂`, if a key `a : α` exists in both, then use `mergeFn a b₁ b₂` to produce the new merged value. -/ def mergeWith (mergeFn : α → β → β → β) (t₁ t₂ : RBMap α β cmp) : RBMap α β cmp := RBSet.mergeWith (fun (_, b₁) (a, b₂) => (a, mergeFn a b₁ b₂)) t₁ t₂ /-- `O(n₁ * log (n₁ + n₂))`. Intersects the maps `t₁` and `t₂` using `mergeFn a b` to produce the new value. -/ def intersectWith (mergeFn : α → β → γ → δ) (t₁ : RBMap α β cmp) (t₂ : RBMap α γ cmp) : RBMap α δ cmp := RBSet.intersectWith (cmp ·.1 ·.1) (fun (a, b₁) (_, b₂) => (a, mergeFn a b₁ b₂)) t₁ t₂ /-- `O(n * log n)`. Constructs the set of all elements satisfying `p`. -/ def filter (t : RBMap α β cmp) (p : α → β → Bool) : RBMap α β cmp := RBSet.filter t fun (a, b) => p a b /-- `O(n₁ * (log n₁ + log n₂))`. Constructs the set of all elements of `t₁` that are not in `t₂`. -/ def sdiff (t₁ t₂ : RBMap α β cmp) : RBMap α β cmp := t₁.filter fun a _ => !t₂.contains a end RBMap end Std open Std @[inherit_doc RBMap.ofList] abbrev List.toRBMap (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBMap.ofList l cmp
Require Import Coq.Setoids.Setoid Coq.Classes.Morphisms. Require Export PerformanceExperiments.rewrite_repeated_app_common. Require Import Ltac2.Ltac2. Require Import Ltac2.Constr. Require Import Ltac2.Control. Require Ltac2.Notations. Require Ltac2.Array. Require Ltac2.Int. Require PerformanceExperiments.Ltac2Compat.Array. Require Import PerformanceExperiments.Ltac2Compat.Constr. Module Import WithLtac2. Import Ltac2.Notations. (*Goal True. let x := Unsafe.make (Unsafe.mkLambda (Binder.make None 'True) (Unsafe.make (Unsafe.Rel 1))) in Message.print (Message.of_constr x).*) Ltac2 rec preshare_pf (f : constr) (g : constr) (f_res_ty : constr) (eq : constr) (eq_refl : constr) (cst : cast) (prop : constr) (hfg_ext : constr) (fx : constr) := let mkRel i := Unsafe.make (Unsafe.Rel i) in match Unsafe.kind fx with | Unsafe.App _f args => let x := Array.get args 0 in let (under_lets_cont, gy) := preshare_pf f g f_res_ty eq eq_refl cst prop hfg_ext x in (* let x' := ... in let y' := ... in let pf' := ... in let fx' := f ^3 in let gy' := g ^3 in let pf' := hfg_ext ^5 ^4 ^3 in ... *) let fx'_bind := Binder.make None f_res_ty in let fx'_body := Unsafe.make (Unsafe.App f (Array.of_list [mkRel 3])) in let gy'_bind := Binder.make None f_res_ty in let gy'_body := Unsafe.make (Unsafe.App g (Array.of_list [mkRel 3])) in let pf'_bind := Binder.make None (Unsafe.make (Unsafe.Cast (Unsafe.make (Unsafe.App eq (Array.of_list [f_res_ty; mkRel 2; mkRel 1]))) cst prop)) in let pf'_body := Unsafe.make (Unsafe.App hfg_ext (Array.of_list [mkRel 5; mkRel 4; mkRel 3])) in let gy := Unsafe.make (Unsafe.App g (Array.of_list [gy])) in ((fun k => under_lets_cont (fun v => Unsafe.make (Unsafe.mkLetIn fx'_bind fx'_body (Unsafe.make (Unsafe.mkLetIn gy'_bind gy'_body (Unsafe.make (Unsafe.mkLetIn pf'_bind pf'_body (k v)))))))) , gy) | _ => let x := fx in (* let x' := fx in let y' := fx in let pf' := eq_refl fx in ... *) let fx'_bind := Binder.make None f_res_ty in let fx'_body := x in let gy'_bind := Binder.make None f_res_ty in let gy'_body := x in let pf'_bind := Binder.make None (Unsafe.make (Unsafe.Cast (Unsafe.make (Unsafe.App eq (Array.of_list [f_res_ty; mkRel 2; mkRel 1]))) cst prop)) in let pf'_body := Unsafe.make (Unsafe.App eq_refl (Array.of_list [f_res_ty; x])) in ((fun k v => Unsafe.make (Unsafe.mkLetIn fx'_bind fx'_body (Unsafe.make (Unsafe.mkLetIn gy'_bind gy'_body (Unsafe.make (Unsafe.mkLetIn pf'_bind pf'_body (k v))))))) , x) end. Ltac2 get_normal_cast () := match Unsafe.kind '(I : True) with | Unsafe.Cast _ cst _ => cst | _ => Control.throw Not_found end. Axiom admit : forall {T}, T. Ltac2 time_build_check_fast_proof (fx : constr) := let mkRel i := Unsafe.make (Unsafe.Rel i) in let f := 'f in let g := 'g in let f_res_ty := 'nat in let eq := '(@eq) in let eq_refl := '(@eq_refl) in let hfg_ext := 'fg_ext in let c_I := 'I in let cst := get_normal_cast () in let c_admit := '(@admit) in let prop := 'Prop in let mkAdmit t := Unsafe.make (Unsafe.App c_admit (Array.of_list [t])) in let (mk, gy) := Control.time (Some "build-eval-thunk-regression-linear") (fun () => let (mk, gy) := Control.time (Some "build-thunk-regression-linear") (fun () => preshare_pf f g f_res_ty eq eq_refl cst prop hfg_ext fx) in (Control.time (Some "eval-thunk-regression-linear") (fun () => mk (fun c => c)) , gy)) in let let_I := Control.time (Some "build-I-regression-linear") (fun () => mk c_I) in let _ := Control.time (Some "check-I-regression-linear") (fun () => Unsafe.check let_I) in let _ := Control.time (Some "type-I-regression-linear") (fun () => Constr.type let_I) in let top_ty := Unsafe.make (Unsafe.App eq (Array.of_list [f_res_ty; fx; gy])) in let let_admit := Control.time (Some "build-admit-regression-linear") (fun () => mk (mkAdmit top_ty)) in let _ := Control.time (Some "check-admit-regression-quadratic") (fun () => Unsafe.check let_admit) in let _ := Control.time (Some "type-admit-regression-quadratic") (fun () => Constr.type let_admit) in (* fx = gy from context *) let under_ty := Unsafe.make (Unsafe.App eq (Array.of_list [f_res_ty; mkRel 3; mkRel 2])) in let let_admit_cast := Control.time (Some "build-admit-cast-regression-linear") (fun () => mk (Unsafe.make (Unsafe.Cast (mkAdmit under_ty) cst top_ty))) in let _ := Control.time (Some "check-admit-cast-regression-quadratic") (fun () => Unsafe.check let_admit_cast) in let _ := Control.time (Some "type-admit-cast-regression-quadratic") (fun () => Constr.type let_admit_cast) in let let_pf_cast := Control.time (Some "build-pf-cast-regression-linear") (fun () => mk (Unsafe.make (Unsafe.Cast (mkRel 1) cst top_ty))) in let _ := Control.time (Some "check-pf-cast-regression-quadratic") (fun () => Unsafe.check let_pf_cast) in let _ := Control.time (Some "type-pf-cast-regression-quadratic") (fun () => Constr.type let_pf_cast) in let_pf_cast. Ltac2 fast_rewrite () := let fx := (lazy_match! goal with | [ |- ?fx = _ ] => fx end) in let pf := time_build_check_fast_proof fx in Control.time (Some "refine-regression-quadratic-regression-linear") (fun () => Control.refine (fun () => pf)). End WithLtac2. Ltac fast_rewrite_ltac2 := ltac2:(fast_rewrite ()). Global Set Default Proof Mode "Classic".
(* Title: HOL/SET_Protocol/Event_SET.thy Author: Giampaolo Bella Author: Fabio Massacci Author: Lawrence C Paulson *) section{*Theory of Events for SET*} theory Event_SET imports Message_SET begin text{*The Root Certification Authority*} abbreviation "RCA == CA 0" text{*Message events*} datatype event = Says agent agent msg | Gets agent msg | Notes agent msg text{*compromised agents: keys known, Notes visible*} consts bad :: "agent set" text{*Spy has access to his own key for spoof messages, but RCA is secure*} specification (bad) Spy_in_bad [iff]: "Spy \<in> bad" RCA_not_bad [iff]: "RCA \<notin> bad" by (rule exI [of _ "{Spy}"], simp) subsection{*Agents' Knowledge*} consts (*Initial states of agents -- parameter of the construction*) initState :: "agent => msg set" (* Message reception does not extend spy's knowledge because of reception invariant enforced by Reception rule in protocol definition*) primrec knows :: "[agent, event list] => msg set" where knows_Nil: "knows A [] = initState A" | knows_Cons: "knows A (ev # evs) = (if A = Spy then (case ev of Says A' B X => insert X (knows Spy evs) | Gets A' X => knows Spy evs | Notes A' X => if A' \<in> bad then insert X (knows Spy evs) else knows Spy evs) else (case ev of Says A' B X => if A'=A then insert X (knows A evs) else knows A evs | Gets A' X => if A'=A then insert X (knows A evs) else knows A evs | Notes A' X => if A'=A then insert X (knows A evs) else knows A evs))" subsection{*Used Messages*} primrec used :: "event list => msg set" where (*Set of items that might be visible to somebody: complement of the set of fresh items. As above, message reception does extend used items *) used_Nil: "used [] = (UN B. parts (initState B))" | used_Cons: "used (ev # evs) = (case ev of Says A B X => parts {X} Un (used evs) | Gets A X => used evs | Notes A X => parts {X} Un (used evs))" (* Inserted by default but later removed. This declaration lets the file be re-loaded. Addsimps [knows_Cons, used_Nil, *) (** Simplifying parts (insert X (knows Spy evs)) = parts {X} Un parts (knows Spy evs) -- since general case loops*) lemmas parts_insert_knows_A = parts_insert [of _ "knows A evs"] for A evs text{*Letting the Spy see "bad" agents' notes avoids redundant case-splits on whether @{term "A=Spy"} and whether @{term "A\<in>bad"}*} lemma knows_Spy_Notes [simp]: "knows Spy (Notes A X # evs) = (if A:bad then insert X (knows Spy evs) else knows Spy evs)" apply auto done lemma knows_Spy_Gets [simp]: "knows Spy (Gets A X # evs) = knows Spy evs" by auto lemma initState_subset_knows: "initState A <= knows A evs" apply (induct_tac "evs") apply (auto split: event.split) done lemma knows_Spy_subset_knows_Spy_Says: "knows Spy evs <= knows Spy (Says A B X # evs)" by auto lemma knows_Spy_subset_knows_Spy_Notes: "knows Spy evs <= knows Spy (Notes A X # evs)" by auto lemma knows_Spy_subset_knows_Spy_Gets: "knows Spy evs <= knows Spy (Gets A X # evs)" by auto (*Spy sees what is sent on the traffic*) lemma Says_imp_knows_Spy [rule_format]: "Says A B X \<in> set evs --> X \<in> knows Spy evs" apply (induct_tac "evs") apply (auto split: event.split) done (*Use with addSEs to derive contradictions from old Says events containing items known to be fresh*) lemmas knows_Spy_partsEs = Says_imp_knows_Spy [THEN parts.Inj, elim_format] parts.Body [elim_format] subsection{*The Function @{term used}*} lemma parts_knows_Spy_subset_used: "parts (knows Spy evs) <= used evs" apply (induct_tac "evs") apply (auto simp add: parts_insert_knows_A split: event.split) done lemmas usedI = parts_knows_Spy_subset_used [THEN subsetD, intro] lemma initState_subset_used: "parts (initState B) <= used evs" apply (induct_tac "evs") apply (auto split: event.split) done lemmas initState_into_used = initState_subset_used [THEN subsetD] lemma used_Says [simp]: "used (Says A B X # evs) = parts{X} Un used evs" by auto lemma used_Notes [simp]: "used (Notes A X # evs) = parts{X} Un used evs" by auto lemma used_Gets [simp]: "used (Gets A X # evs) = used evs" by auto lemma Notes_imp_parts_subset_used [rule_format]: "Notes A X \<in> set evs --> parts {X} <= used evs" apply (induct_tac "evs") apply (rename_tac [2] a evs') apply (induct_tac [2] "a", auto) done text{*NOTE REMOVAL--laws above are cleaner, as they don't involve "case"*} declare knows_Cons [simp del] used_Nil [simp del] used_Cons [simp del] text{*For proving theorems of the form @{term "X \<notin> analz (knows Spy evs) --> P"} New events added by induction to "evs" are discarded. Provided this information isn't needed, the proof will be much shorter, since it will omit complicated reasoning about @{term analz}.*} lemmas analz_mono_contra = knows_Spy_subset_knows_Spy_Says [THEN analz_mono, THEN contra_subsetD] knows_Spy_subset_knows_Spy_Notes [THEN analz_mono, THEN contra_subsetD] knows_Spy_subset_knows_Spy_Gets [THEN analz_mono, THEN contra_subsetD] lemmas analz_impI = impI [where P = "Y \<notin> analz (knows Spy evs)"] for Y evs ML {* fun analz_mono_contra_tac ctxt = rtac @{thm analz_impI} THEN' REPEAT1 o (dresolve_tac @{thms analz_mono_contra}) THEN' mp_tac ctxt *} method_setup analz_mono_contra = {* Scan.succeed (fn ctxt => SIMPLE_METHOD (REPEAT_FIRST (analz_mono_contra_tac ctxt))) *} "for proving theorems of the form X \<notin> analz (knows Spy evs) --> P" end
theory flash23Bra imports flash23Rev begin lemma onInv23: assumes a1:"iInv1 \<le> N" and a2:"iInv2 \<le> N" and a3:"iInv3 \<le> N" and a4:"iInv1~=iInv2 " and a5:"iInv1~=iInv3 " and a6:"iInv2~=iInv3 " and b1:"r \<in> rules N" and b2:"invf=inv23 iInv1 iInv2 iInv3 " shows "invHoldForRule' s invf r (invariants N)" proof - have c1:"ex1P N (% iRule1 . r=NI_Local_GetX_PutX1 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_GetX iRule1 )\<or>ex1P N (% iRule1 . r=NI_Replace iRule1 )\<or>ex0P N ( r=NI_ShWb N )\<or>ex0P N ( r=PI_Local_GetX_GetX2 )\<or>ex0P N ( r=NI_Local_PutXAcksDone )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX7 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Nak2 iRule1 )\<or>ex0P N ( r=NI_ReplaceHomeShrVld )\<or>ex1P N (% iRule1 . r=NI_Remote_Put iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX5 N iRule1 )\<or>ex0P N ( r=NI_Wb )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Get iRule1 )\<or>ex0P N ( r=PI_Local_Replace )\<or>ex1P N (% iRule1 . r=NI_ReplaceShrVld iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Local_GetX_PutX8 N iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_InvAck_2 N iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_Get_Nak2 iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=PI_Remote_Replace iRule1 )\<or>ex0P N ( r=NI_Nak_Home )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Put2 iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_InvAck_1 iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX11 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX6 N iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_Get_Put2 iRule1 iRule2 )\<or>ex0P N ( r=PI_Local_Get_Put )\<or>ex0P N ( r=PI_Local_GetX_PutX1 N )\<or>ex1P N (% iRule1 . r=NI_InvAck_1_Home iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_Get_Nak1 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Nak1 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_Nak2 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX10_home N iRule1 )\<or>ex1P N (% iRule1 . r=PI_Remote_Get iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_Nak3 iRule1 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Local_GetX_PutX10 N iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX2 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_Get_Put1 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_PutX iRule1 )\<or>ex1P N (% iRule1 . r=Store iRule1 )\<or>ex0P N ( r=NI_FAck )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX3 N iRule1 )\<or>ex0P N ( r=PI_Local_GetX_PutX3 )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_GetX_PutX iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX8_home N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Put1 N iRule1 )\<or>ex0P N ( r=PI_Local_GetX_GetX1 )\<or>ex0P N ( r=StoreHome )\<or>ex2P N (% iRule1 iRule2 . r=NI_Remote_GetX_Nak iRule1 iRule2 )\<or>ex1P N (% iRule1 . r=NI_Inv iRule1 )\<or>ex1P N (% iRule1 . r=PI_Remote_PutX iRule1 )\<or>ex0P N ( r=PI_Local_GetX_PutX4 )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX4 N iRule1 )\<or>ex1P N (% iRule1 . r=NI_Nak iRule1 )\<or>ex0P N ( r=PI_Local_GetX_PutX2 N )\<or>ex0P N ( r=NI_Local_Put )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_Nak1 iRule1 )\<or>ex0P N ( r=NI_Nak_Clear )\<or>ex0P N ( r=PI_Local_PutX )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Nak3 iRule1 )\<or>ex1P N (% iRule1 . r=NI_Remote_GetX_Nak_Home iRule1 )\<or>ex0P N ( r=PI_Local_Get_Get )\<or>ex1P N (% iRule1 . r=NI_Local_GetX_PutX9 N iRule1 )\<or>ex1P N (% iRule1 . r=PI_Remote_GetX iRule1 )\<or>ex0P N ( r=NI_ReplaceHome )\<or>ex1P N (% iRule1 . r=NI_Remote_GetX_PutX_Home iRule1 )\<or>ex1P N (% iRule1 . r=NI_Local_Get_Put3 iRule1 )" apply(cut_tac b1) apply auto done moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX1 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX1 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX1 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_GetX iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_GetX iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_GetX iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_GetXVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Replace iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Replace iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Replace iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_ReplaceVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_ShWb N ) " from c1 have c2:" r= NI_ShWb N " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_ShWb N ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_ShWbVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_GetX_GetX2 ) " from c1 have c2:" r= PI_Local_GetX_GetX2 " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_GetX_GetX2 ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_GetX_GetX2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_Local_PutXAcksDone ) " from c1 have c2:" r= NI_Local_PutXAcksDone " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_PutXAcksDone ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_Local_PutXAcksDoneVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX7 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX7 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX7 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX7VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Nak2 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Nak2 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Get_Nak2 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_Get_Nak2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_ReplaceHomeShrVld ) " from c1 have c2:" r= NI_ReplaceHomeShrVld " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_ReplaceHomeShrVld ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_ReplaceHomeShrVldVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Remote_Put iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_Put iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_Put iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_PutVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX5 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX5 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX5 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX5VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_Wb ) " from c1 have c2:" r= NI_Wb " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Wb ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_WbVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Get iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Get iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Get_Get iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_Get_GetVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_Replace ) " from c1 have c2:" r= PI_Local_Replace " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_Replace ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_ReplaceVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_ReplaceShrVld iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_ReplaceShrVld iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_ReplaceShrVld iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_ReplaceShrVldVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Local_GetX_PutX8 N iRule1 iRule2 ) " from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Local_GetX_PutX8 N iRule1 iRule2 " by (auto simp add: ex2P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX8 N iRule1 iRule2 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX8VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_InvAck_2 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_InvAck_2 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_InvAck_2 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_InvAck_2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_Get_Nak2 iRule1 iRule2 ) " from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_Get_Nak2 iRule1 iRule2 " by (auto simp add: ex2P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_Get_Nak2 iRule1 iRule2 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_Get_Nak2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= PI_Remote_Replace iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_Replace iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Remote_Replace iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis PI_Remote_ReplaceVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_Nak_Home ) " from c1 have c2:" r= NI_Nak_Home " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Nak_Home ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_Nak_HomeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Put2 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Put2 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Get_Put2 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_Get_Put2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex2P N (% iRule1 iRule2 . r= NI_InvAck_1 iRule1 iRule2 ) " from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_InvAck_1 iRule1 iRule2 " by (auto simp add: ex2P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_InvAck_1 iRule1 iRule2 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_InvAck_1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX11 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX11 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX11 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX11VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX6 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX6 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX6 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX6VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_Get_Put2 iRule1 iRule2 ) " from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_Get_Put2 iRule1 iRule2 " by (auto simp add: ex2P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_Get_Put2 iRule1 iRule2 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_Get_Put2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_Get_Put ) " from c1 have c2:" r= PI_Local_Get_Put " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_Get_Put ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_Get_PutVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_GetX_PutX1 N ) " from c1 have c2:" r= PI_Local_GetX_PutX1 N " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_GetX_PutX1 N ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_GetX_PutX1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_InvAck_1_Home iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_InvAck_1_Home iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_InvAck_1_Home iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_InvAck_1_HomeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Remote_Get_Nak1 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_Get_Nak1 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_Get_Nak1 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_Get_Nak1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Nak1 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Nak1 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Get_Nak1 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_Get_Nak1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_Nak2 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_Nak2 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_Nak2 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_Nak2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX10_home N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX10_home N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX10_home N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX10_homeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= PI_Remote_Get iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_Get iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Remote_Get iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis PI_Remote_GetVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_Nak3 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_Nak3 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_Nak3 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_Nak3VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Local_GetX_PutX10 N iRule1 iRule2 ) " from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Local_GetX_PutX10 N iRule1 iRule2 " by (auto simp add: ex2P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX10 N iRule1 iRule2 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX10VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX2 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX2 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX2 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Remote_Get_Put1 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_Get_Put1 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_Get_Put1 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_Get_Put1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Remote_PutX iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_PutX iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_PutX iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_PutXVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= Store iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= Store iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (Store iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis StoreVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_FAck ) " from c1 have c2:" r= NI_FAck " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_FAck ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_FAckVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX3 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX3 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX3 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX3VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_GetX_PutX3 ) " from c1 have c2:" r= PI_Local_GetX_PutX3 " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_GetX_PutX3 ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_GetX_PutX3VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_GetX_PutX iRule1 iRule2 ) " from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_GetX_PutX iRule1 iRule2 " by (auto simp add: ex2P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_GetX_PutX iRule1 iRule2 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_GetX_PutXVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX8_home N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX8_home N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX8_home N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX8_homeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Put1 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Put1 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Get_Put1 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_Get_Put1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_GetX_GetX1 ) " from c1 have c2:" r= PI_Local_GetX_GetX1 " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_GetX_GetX1 ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_GetX_GetX1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= StoreHome ) " from c1 have c2:" r= StoreHome " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (StoreHome ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis StoreHomeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex2P N (% iRule1 iRule2 . r= NI_Remote_GetX_Nak iRule1 iRule2 ) " from c1 obtain iRule1 iRule2 where c2:" iRule1~=iRule2 \<and> iRule1 \<le> N \<and> iRule2 \<le> N \<and> r= NI_Remote_GetX_Nak iRule1 iRule2 " by (auto simp add: ex2P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_GetX_Nak iRule1 iRule2 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_GetX_NakVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Inv iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Inv iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Inv iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_InvVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= PI_Remote_PutX iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_PutX iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Remote_PutX iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis PI_Remote_PutXVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_GetX_PutX4 ) " from c1 have c2:" r= PI_Local_GetX_PutX4 " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_GetX_PutX4 ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_GetX_PutX4VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX4 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX4 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX4 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX4VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Nak iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Nak iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Nak iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_NakVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_GetX_PutX2 N ) " from c1 have c2:" r= PI_Local_GetX_PutX2 N " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_GetX_PutX2 N ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_GetX_PutX2VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_Local_Put ) " from c1 have c2:" r= NI_Local_Put " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Put ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_Local_PutVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_Nak1 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_Nak1 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_Nak1 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_Nak1VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_Nak_Clear ) " from c1 have c2:" r= NI_Nak_Clear " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Nak_Clear ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_Nak_ClearVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_PutX ) " from c1 have c2:" r= PI_Local_PutX " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_PutX ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_PutXVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Nak3 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Nak3 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Get_Nak3 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_Get_Nak3VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Remote_GetX_Nak_Home iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_GetX_Nak_Home iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_GetX_Nak_Home iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_GetX_Nak_HomeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= PI_Local_Get_Get ) " from c1 have c2:" r= PI_Local_Get_Get " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Local_Get_Get ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis PI_Local_Get_GetVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_GetX_PutX9 N iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_GetX_PutX9 N iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_GetX_PutX9 N iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_GetX_PutX9VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= PI_Remote_GetX iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= PI_Remote_GetX iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (PI_Remote_GetX iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis PI_Remote_GetXVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex0P N ( r= NI_ReplaceHome ) " from c1 have c2:" r= NI_ReplaceHome " by (auto simp add: ex0P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_ReplaceHome ) (invariants N) " apply(cut_tac a1 a2 a3 a4 a5 a6 b2 c2 ) by (metis NI_ReplaceHomeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Remote_GetX_PutX_Home iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Remote_GetX_PutX_Home iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Remote_GetX_PutX_Home iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Remote_GetX_PutX_HomeVsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) } moreover {assume c1: "ex1P N (% iRule1 . r= NI_Local_Get_Put3 iRule1 ) " from c1 obtain iRule1 where c2:" iRule1 \<le> N \<and> r= NI_Local_Get_Put3 iRule1 " by (auto simp add: ex1P_def) have "invHoldForRule' s (inv23 iInv1 iInv2 iInv3 ) (NI_Local_Get_Put3 iRule1 ) (invariants N) " apply(cut_tac c2 a1 a2 a3 a4 a5 a6 ) by (metis NI_Local_Get_Put3VsInv23 ) then have "invHoldForRule' s invf r (invariants N) " by(cut_tac c2 b2, metis) }ultimately show "invHoldForRule' s invf r (invariants N) " by blast qed end
From QuickChick Require Import QuickChick. Import MonadNotation. Require Import Arith. Definition test_prop (n : nat) := Some (n <=? 10). Definition gen : G nat := choose (0,5). Definition fuzz (n : nat) : G nat := x <- choose (1,3);; ret (n + x). Definition fuzzer := fun (u : unit) => fuzzLoop gen fuzz show test_prop. QuickChickDebug Debug On. FuzzChick test_prop (fuzzer tt).
# 11 ODE Applications (Projectile with linear air resistance) Let's apply our ODE solvers to some problems involving balls and projectiles. We will start with projectile motion with linear air resistances. The `integrators.py` file from the lesson on [ODE integrators](https://py4phy.github.io/PHY432/modules/ODEs/integrators/) is used here (and named [`ode.py`](https://github.com/Py4Phy/PHY432-resources/blob/main/11_ODE_applications/ode.py)). ```python import numpy as np import ode ``` ```python %matplotlib inline import matplotlib.pyplot as plt plt.matplotlib.style.use('ggplot') ``` ## Theory Linear drag force $$ \mathbf{F}_1 = -b_1 \mathbf{v} $$ Equations of motion with force due to gravity $\mathbf{g} = -g \hat{\mathbf{e}}_y$ \begin{align} \frac{d\mathbf{r}}{dt} &= \mathbf{v}\\ \frac{d\mathbf{v}}{dt} &= - g \hat{\mathbf{e}}_y -\frac{b_1}{m} \mathbf{v} \end{align} Bring into standard ODE form for $$ \frac{d\mathbf{y}}{dt} = \mathbf{f}(t, \mathbf{y}) $$ as $$ \mathbf{y} = \begin{pmatrix} x\\ y\\ v_x\\ v_y \end{pmatrix}, \quad \mathbf{f} = \begin{pmatrix} v_x\\ v_y\\ -\frac{b_1}{m} v_x\\ -g -\frac{b_1}{m} v_y \end{pmatrix} $$ (Based on Wang 2016, Ch 3.3.1) ## Python implementation with ODE solver - Formulate the function `f()` for the standard ODE form (note: velocity dependence) - Set up the integration loop: - only integrate until the particle hits ground, i.e. while $y ≥ 0$. - choose an appropriate ODE solver from `ode.py` such as RK4 (because there's no energy conservation so velocity Verlet is not as useful) ```python def simulate(v0, h=0.01, b1=0.2, g=9.81, m=0.5): def f(t, y): # y = [x, y, vx, vy] return np.array([y[2], y[3], -b1/m * y[2], -g - b1/m * y[3]]) vx, vy = v0 t = 0 positions = [] y = np.array([0, 0, vx, vy], dtype=np.float64) while y[1] >= 0: positions.append([t, y[0], y[1]]) # record t, x and y y[:] = ode.rk4(y, f, t, h) t += h return np.array(positions) def initial_v(v, theta): x = np.deg2rad(theta) return v * np.array([np.cos(x), np.sin(x)]) ``` ### Launch at fixed angle ```python r = simulate(initial_v(200, 30), h=0.01, b1=1) ``` ```python plt.plot(r[:, 1], r[:, 2]) plt.xlabel(r"distance $x$ (m)") plt.ylabel(r"height $y$ (m)"); ``` ### Distance depends on launch angle Plot the trajectory for launch angles from 5º to 45º. ```python for angle in (5, 7.5, 10, 20, 30, 45): r = simulate(initial_v(200, angle), h=0.01, b1=1) plt.plot(r[:, 1], r[:, 2], label=r"$\theta = {}^\circ$".format(angle)) plt.legend(loc="best") plt.xlabel(r"distance $x$ (m)") plt.ylabel(r"height $y$ (m)"); plt.savefig("launch_linear_air_resistance.svg") ``` ```python ```
The quake seriously damaged the control tower at Toussaint L 'Ouverture International Airport . Damage to the Port @-@ au @-@ Prince seaport rendered the harbor unusable for immediate rescue operations ; its container crane subsided severely at an angle because of weak foundations . Gonaïves seaport in northern Haiti remained operational .
import glob #from kornia import * from PIL import Image from skimage.transform import resize import sys, os sys.path.append(os.path.abspath(os.path.join('./models'))) sys.path.append(os.path.abspath(os.path.join('./Data_Loaders'))) sys.path.append(os.path.abspath(os.path.join('./Loss_Functions'))) from resnet import ResNetUNet, ResNetUNet50, NOCS_decoder, NOCS_decoder_2 import torch.nn as nn import argparse from torch.utils.data import Dataset, DataLoader import torch.optim as optim from torchvision import transforms, utils import torch import tqdm import gc import matplotlib.pyplot as plt import numpy as np import cv2 import open3d as o3d from trainers import DRACO_phase_2 as training_model from omegaconf import OmegaConf def camera_matrix(focal_x, focal_y, c_x, c_y): ''' Constructs camera matrix ''' K = np.array([[ focal_x, 0, c_x], [ 0, focal_y, c_y], [ 0, 0, 1]]) return K def preprocess_image(image, dim = 64): ''' Function to preprocess image ''' h, w, c = image.shape image_out = resize(image, (dim, dim))[:, :, :3] return image_out, {"scale_y": h / dim, "scale_x": w / dim} def get_grid(x, y): ''' Get index grid from image ''' y_i, x_i = np.indices((x, y)) coords = np.stack([x_i, y_i, np.ones_like(x_i)], axis = -1).reshape(x*y, 3) return coords.T def depth_2_point_cloud(invK, image, depth_image, depth_tiff=None): ''' Convert depth map to point cloud ''' points_hom = get_grid(image.shape[0], image.shape[1]) depth = depth_image.reshape(1, -1) point_3D = invK @ points_hom point_3D = point_3D / point_3D[2, :] point_3D = point_3D * depth return point_3D def save_point_cloud(K, image, mask, depth, ply_name, depth_tiff = None): ''' Save point cloud given depth map ''' image_colors = image.reshape(-1, 3) invK = np.linalg.inv(K) point_cloud = depth_2_point_cloud(invK, image, depth, depth_tiff) mask = mask.reshape(-1, 1) mask = mask > 0.5 image_colors = image_colors[mask[:, 0], :] point_cloud = point_cloud[:, mask[:, 0]] image_colors = image_colors[point_cloud[2,:] < 10, :] point_cloud = point_cloud[:, point_cloud[2,:] < 10] pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(point_cloud.T) pcd.colors = o3d.utility.Vector3dVector(image_colors) o3d.io.write_point_cloud(ply_name, pcd) return point_cloud, pcd if __name__ == "__main__": ################################# Argument Parser ##################################### parser = argparse.ArgumentParser() parser.add_argument("--path", help = "Path to images", required=True) parser.add_argument("--model", help = "Model weights", required=True) parser.add_argument("--output", help = "Output directory path", required=True) parser.add_argument("--normalize", required=False, type=int, default=1) parser.add_argument("--real", help = "Real images?", required=False, default = 0, type=int) # parser.add_argument("--multi_seq", help = "Multiple sequences", type=int, default=1) args = parser.parse_args() ####################################################################################### #cfgs = OmegaConf.load('cfgs/config_DRACO.yaml') print(args.model) directory_save = args.output directory_save = os.path.join(directory_save, "") K = camera_matrix(888.88, 1000.0, 320, 240) if not os.path.exists(directory_save): os.makedirs(directory_save) images_list = [] images_paths = os.path.join(args.path, "") + "**/frame_**_Color_00.png" images_list = glob.glob(images_paths) if args.real: images_list = glob.glob(os.path.join(args.path, "**/**.jpg")) if len(images_list) == 0: images_paths = os.path.join(args.path, "") + "frame_**_Color_00.png" #print(images_paths) images_list.extend(glob.glob(images_paths)) #print(images_list) if args.real == 1: print("real") images_list.extend(glob.glob(os.path.join(args.path, "**.jpg"))) images_list.sort() #print(images_list) net = training_model.load_from_checkpoint(args.model) net.eval() if torch.cuda.is_available(): net.cuda() for image_name in images_list: directory, tail = os.path.split(image_name) name_without_ext, ext = os.path.splitext(tail) print(name_without_ext) sub_directory_save = os.path.join(directory_save + image_name.split('/')[-2], "") if not os.path.exists(sub_directory_save): os.makedirs(sub_directory_save) image_view = plt.imread(image_name)[:, :, :3] if image_view.max() > 1: image_view = image_view / 255.0 #image_view = cv2.cvtColor(image_view, cv2.COLOR_BGR2RGB) / 255.0 image_view = cv2.resize(image_view, (640, 480)) print(image_view.shape, "not real") if args.real == 1: print("real") image_view = cv2.resize(image_view, (440, 280)) #print(image_view.shape) image_view = cv2.copyMakeBorder(image_view, 100, 100, 100, 100, cv2.BORDER_CONSTANT) if torch.cuda.is_available(): image_tensor = torch.from_numpy(image_view.transpose(2, 0, 1)).unsqueeze(0).cuda() else: image_tensor = torch.from_numpy(image_view.transpose(2, 0, 1)).unsqueeze(0) if args.normalize: print("NORMALIZE") normalize_transform = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], inplace=True) image_tensor = normalize_transform(image_tensor[0]).unsqueeze(0) output = net.test_pass(image_tensor.float()) depth = (output[0][0,0]).cpu().detach().numpy() mask = output[1][0,0].cpu().detach().numpy() mask = (mask > 0.5) * 1.0 nocs = (net.nocs_decoder(output[2])) nocs = nocs.detach().cpu().numpy() nocs[0, :, mask < 0.5] = 1.0 nocs = nocs[0].transpose((1, 2, 0)) nocs = (nocs * 255).astype("uint8") depth = (depth * mask) #################################### SAVING FILES ########################################### print("Saving") im_depth = depth.astype('float32') im_depth_tiff = Image.fromarray(im_depth, 'F') ply_name = sub_directory_save + name_without_ext + "_pointcloud.ply" save_point_cloud(K, image_view, mask, depth, ply_name, im_depth_tiff) image = (image_view*255).astype("uint8") mask = (mask*255).astype("uint8") mask_name = sub_directory_save + name_without_ext + "_mask.jpg" nocs_name = sub_directory_save + name_without_ext + "_nocs.jpg" depth_tiff_name = sub_directory_save + name_without_ext + "_depth.tiff" image_name_save = sub_directory_save + name_without_ext + "_input.jpg" plt.imsave(image_name_save, image) plt.imsave(nocs_name, nocs) plt.imsave(mask_name, mask) im_depth_tiff.save(depth_tiff_name) #############################################################################################
import os import unittest import pandas as pd from financier import Portfolio import numpy as np class MarketPortfolioTestCase(unittest.TestCase): print("----") print(os.getcwd()) def setUp(self): df = pd.read_csv('../tests/data/10stocks.csv') exp_ret = [] exp_vol = [] for (stock,returns) in df.iteritems(): exp_ret.append(np.mean(returns.values)) exp_vol.append(np.std(returns.values)) exp_cov = df.cov(min_periods=None, ddof=0).values tickers = df.columns self.portfolio = Portfolio(tickers, exp_ret, exp_vol, exp_cov) def test_noshorts(self): result = self.portfolio.optimize(rf=.25, allow_short=None).fun self.assertEqual(round(result,2), round(-0.4968591918232762,2)) def test_shorts(self): result = self.portfolio.optimize(rf=.25, allow_short=None).fun self.assertEqual(round(result,2), round(-0.5472016099820182,2)) if __name__ == '__main__': unittest.main()
(* Title: Nominal2_Eqvt Author: Brian Huffman, Author: Christian Urban Test cases for perm_simp *) theory Eqvt imports Nominal2_Base begin declare [[trace_eqvt = false]] (* declare [[trace_eqvt = true]] *) lemma fixes B::"'a::pt" shows "p \<bullet> (B = C)" apply(perm_simp) oops lemma fixes B::"bool" shows "p \<bullet> (B = C)" apply(perm_simp) oops lemma fixes B::"bool" shows "p \<bullet> (A \<longrightarrow> B = C)" apply (perm_simp) oops lemma shows "p \<bullet> (\<lambda>(x::'a::pt). A \<longrightarrow> (B::'a \<Rightarrow> bool) x = C) = foo" apply(perm_simp) oops lemma shows "p \<bullet> (\<lambda>B::bool. A \<longrightarrow> (B = C)) = foo" apply (perm_simp) oops lemma shows "p \<bullet> (\<lambda>x y. \<exists>z. x = z \<and> x = y \<longrightarrow> z \<noteq> x) = foo" apply (perm_simp) oops lemma shows "p \<bullet> (\<lambda>f x. f (g (f x))) = foo" apply (perm_simp) oops lemma fixes p q::"perm" and x::"'a::pt" shows "p \<bullet> (q \<bullet> x) = foo" apply(perm_simp) oops lemma fixes p q r::"perm" and x::"'a::pt" shows "p \<bullet> (q \<bullet> r \<bullet> x) = foo" apply(perm_simp) oops lemma fixes p r::"perm" shows "p \<bullet> (\<lambda>q::perm. q \<bullet> (r \<bullet> x)) = foo" apply (perm_simp) oops lemma fixes C D::"bool" shows "B (p \<bullet> (C = D))" apply(perm_simp) oops declare [[trace_eqvt = false]] text \<open>there is no raw eqvt-rule for The\<close> lemma "p \<bullet> (THE x. P x) = foo" apply(perm_strict_simp exclude: The) apply(perm_simp exclude: The) oops lemma fixes P :: "(('b \<Rightarrow> bool) \<Rightarrow> ('b::pt)) \<Rightarrow> ('a::pt)" shows "p \<bullet> (P The) = foo" apply(perm_simp exclude: The) oops lemma fixes P :: "('a::pt) \<Rightarrow> ('b::pt) \<Rightarrow> bool" shows "p \<bullet> (\<lambda>(a, b). P a b) = (\<lambda>(a, b). (p \<bullet> P) a b)" apply(perm_simp) oops thm eqvts thm eqvts_raw ML \<open>Nominal_ThmDecls.is_eqvt @{context} @{term "supp"}\<close> end
import joblib import nltk from pandas.core.frame import DataFrame import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from src import DEFAULT_N_WORDS_SUMMARIES, LAST_SUMMARIES_ROUTE,\ MIN_N_TOP_TWEETS, KEYWORDS_ROUTE, TOP_TWEETS_FILTER from src.relevance import get_top_tweets from src.relevance import max_relevance, relevance_score from nltk.probability import FreqDist from gensim.summarization import summarize from gensim.summarization import keywords def only_nouns(keys): ptagkeys = nltk.pos_tag(keys, tagset='universal') return [pos_word[0] for pos_word in ptagkeys if pos_word[1] == 'NOUN'] def keyword_extraction(state_union, n_keywords, ndocuments_stateunion): if n_keywords < 0: # Read the keywords from the file where it were saved before try: return joblib.load(KEYWORDS_ROUTE) except(FileNotFoundError): print("ERROR: No valid keywords file found.") while(True): inp = input("Do you want to select keywords again? [Y/N]: ") if inp == 'Y' or inp == 'y': n_keywords = int(input("How many keywords?: ")) ndocuments_stateunion = int(input("""How many documents in state_union to see?: """)) break elif inp == 'N' or inp == 'n': return None unions = [state_union.raw(t) for t in np.random.permutation( state_union.fileids())[ :ndocuments_stateunion]] # Keyword extraction using gensim 'keywords' ks = [only_nouns(keywords(t, words=n_keywords, split=True, lemmatize=True)) for t in unions if type(t) is str] # keywords in a flat list (all in same level) flatset_of_keywords = list() for lis in ks: for word in lis: flatset_of_keywords.append(word) # We select the most common in all documents fd = FreqDist(flatset_of_keywords) keywords_to_match = [k[0] for k in fd.most_common(n_keywords)] joblib.dump(keywords_to_match, KEYWORDS_ROUTE) return keywords_to_match def summarize_clusters(dataframe_clust: DataFrame, clusters: list, tfidf: TfidfVectorizer, mapping=None, labeled=False, n_words_summaries=DEFAULT_N_WORDS_SUMMARIES) -> None: """Summarizes the clusters made Args: dataframe_clust (DataFrame): Dataframe with predicted classes clusters (list): list of predicted cluster for each document in the dataframe_clust mapping (dict, optional): Mapping of supervised labels (numbers) to its meaning (str). Those labels are in the 'trueval' column of the dataframe_clust. This argument is only used for previously labeled datasets, as the hillary one. Therefore, you don't need to provide the 'trueval' column in normal cases. The point of this mapping is to see the distribution of those labels in each cluster. Defaults to None. labeled (bool, optional): This argument is to make the behaviour explained before to work. Defaults to False. """ with open(LAST_SUMMARIES_ROUTE, "w+") as f: pass dict_summaries = dict() for i in range(0, len(list(set(clusters)))): indexes = [j for j, e in enumerate( dataframe_clust["predicted_cluster"]) if e == i] if (len(indexes) <= 1): print("No tweets of cluster ", i, "skipping...") continue tweets_from_cluster = np.array( dataframe_clust["tweets"])[indexes] ms = max_relevance(tweets_from_cluster) tweet_w_score = [(t, relevance_score(t, ms)) for t in tweets_from_cluster] n_top = max( min(len(tweet_w_score), MIN_N_TOP_TWEETS), int(TOP_TWEETS_FILTER*len(tweet_w_score))) top_tweets = get_top_tweets(tweet_w_score, n=n_top) text = ".\n".join([t['text'] for t in top_tweets]) print(text) summerize = summarize(text, word_count=n_words_summaries) print("-----------------------------------------") print("Summarizing tweets of class", i, end="") dict_summaries[str(i)] = [None, None] if labeled: truevals = [t['trueval'] for t in tweets_from_cluster] mcommon = FreqDist(truevals) dict_summaries[str(i)][1] = dict() print(", where: ") for m in mcommon.keys(): string = "\t * {:.2f}".format(mcommon.freq( m)*100) + "% of the samples were originally labeled as \""\ + str(mapping[m]) + "\", " # Save the frequency of the label "mapping[m]" in position # 1 of the tuple assigned to the summaries of the cluster i. # first value of the tuple are the actual summaries: dict_summaries[str(i)][1][mapping[m]] = mcommon.freq(m)*100 print(string) else: print() print(summerize) dict_summaries[str(i)][0] = summerize print("-----------------------------------------") print() with open(LAST_SUMMARIES_ROUTE, "a+") as f: print(dict_summaries, file=f)
program t integer::i(:) pointer::i nullify(i) print *,associated(i) end program t
VendState : Type VendState = (Nat, Nat) data Input = COIN | VEND | CHANGE | REFILL Nat strToInput : String -> Maybe Input strToInput "insert" = Just COIN strToInput "vend" = Just VEND strToInput "change" = Just CHANGE strToInput x = if all isDigit (unpack x) then Just (REFILL (cast x)) else Nothing data CoinResult = Inserted | Rejected data MachineCmd : (ty : Type) -> VendState -> (ty -> VendState) -> Type where -- data MachineCmd : Type -> VendState -> VendState -> Type where InsertCoin : MachineCmd CoinResult (pounds, chocs) (\res => case res of Inserted => (S pounds, chocs) Rejected => (pounds, chocs)) Vend : MachineCmd () (S pounds, S chocs) (const (pounds, chocs)) GetCoins : MachineCmd () (pounds, chocs) (const (Z, chocs)) Display : String -> MachineCmd () state (const state) Refill : (bars : Nat) -> MachineCmd () (Z, chocs) (const (Z, bars + chocs)) GetInput : MachineCmd (Maybe Input) state (const state) Pure : (x:ty) -> MachineCmd ty (state_fn x) state_fn (>>=) : MachineCmd a state1 state2_fn -> ((x : a) -> MachineCmd b (state2_fn x) state3_fn) -> MachineCmd b state1 state3_fn data MachineIO : VendState -> Type where Do : MachineCmd a state1 state2 -> ((x : a) -> Inf (MachineIO (state2 x))) -> MachineIO state1 runMachine : MachineCmd ty inState outState -> IO ty runMachine InsertCoin = do putStrLn "Coin inserted" pure Inserted runMachine Vend = putStrLn "Please take your chocolate" runMachine {inState = (pounds, _)} GetCoins = putStrLn (show pounds ++ " coins returned") runMachine (Display str) = putStrLn str runMachine (Refill bars) = putStrLn ("Chocolate remaining: " ++ show bars) runMachine {inState = (pounds, chocs)} GetInput = do putStrLn ("Coins: " ++ show pounds ++ "; " ++ "Stock: " ++ show chocs) putStr "> " x <- getLine pure (strToInput x) runMachine (Pure x) = pure x runMachine (cmd >>= prog) = do x <- runMachine cmd runMachine (prog x) data Fuel = Dry | More (Lazy Fuel) partial forever : Fuel forever = More forever run : Fuel -> MachineIO state -> IO () run (More fuel) (Do c f) = do res <- runMachine c run fuel (f res) run Dry p = pure () namespace MachineDo (>>=) : MachineCmd a state1 state2 -> (a -> Inf (MachineIO state2)) -> MachineIO state1 (>>=) = Do mutual vend : MachineIO (pounds, chocs) vend {pounds = S p} {chocs = S c} = do Vend Display "Enjoy!" machineLoop vend {pounds = Z} = do Display "Insert a coin" machineLoop vend {chocs = Z} = do Display "Out of stock" machineLoop refill : (num : Nat) -> MachineIO (pounds, chocs) refill {pounds = Z} num = do Refill num machineLoop refill _ = do Display "Can't refill: Coins in machine" machineLoop machineLoop : MachineIO (pounds, chocs) machineLoop = do Just x <- GetInput | Nothing => do Display "Invalid input" machineLoop case x of COIN => do InsertCoin machineLoop VEND => vend CHANGE => do GetCoins Display "Change returned" machineLoop REFILL num => refill num main : IO () main = run forever (machineLoop {pounds = 0} {chocs = 1})
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.algebra_tower import Mathlib.linear_algebra.matrix import Mathlib.PostPort universes u v w namespace Mathlib /-! # Tower of field extensions In this file we prove the tower law for arbitrary extensions and finite extensions. Suppose `L` is a field extension of `K` and `K` is a field extension of `F`. Then `[L:F] = [L:K] [K:F]` where `[E₁:E₂]` means the `E₂`-dimension of `E₁`. In fact we generalize it to vector spaces, where `L` is not necessarily a field, but just a vector space over `K`. ## Implementation notes We prove two versions, since there are two notions of dimensions: `vector_space.dim` which gives the dimension of an arbitrary vector space as a cardinal, and `finite_dimensional.findim` which gives the dimension of a finitely-dimensional vector space as a natural number. ## Tags tower law -/ /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim' (F : Type u) (K : Type v) (A : Type w) [field F] [field K] [add_comm_group A] [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] : cardinal.lift (vector_space.dim F K) * cardinal.lift (vector_space.dim K A) = cardinal.lift (vector_space.dim F A) := sorry /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim (F : Type u) (K : Type v) (A : Type v) [field F] [field K] [add_comm_group A] [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] : vector_space.dim F K * vector_space.dim K A = vector_space.dim F A := sorry namespace finite_dimensional theorem trans (F : Type u) (K : Type v) (A : Type w) [field F] [field K] [add_comm_group A] [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] [finite_dimensional F K] [finite_dimensional K A] : finite_dimensional F A := sorry theorem right (F : Type u) (K : Type v) (A : Type w) [field F] [field K] [add_comm_group A] [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] [hf : finite_dimensional F A] : finite_dimensional K A := sorry /-- Tower law: if `A` is a `K`-algebra and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem findim_mul_findim (F : Type u) (K : Type v) (A : Type w) [field F] [field K] [add_comm_group A] [algebra F K] [vector_space K A] [vector_space F A] [is_scalar_tower F K A] [finite_dimensional F K] : findim F K * findim K A = findim F A := sorry protected instance linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [vector_space F V] [add_comm_group W] [vector_space F W] [finite_dimensional F V] [finite_dimensional F W] : finite_dimensional F (linear_map F V W) := sorry theorem findim_linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [vector_space F V] [add_comm_group W] [vector_space F W] [finite_dimensional F V] [finite_dimensional F W] : findim F (linear_map F V W) = findim F V * findim F W := sorry -- TODO: generalize by removing [finite_dimensional F K] -- V = ⊕F, -- (V →ₗ[F] K) = ((⊕F) →ₗ[F] K) = (⊕ (F →ₗ[F] K)) = ⊕K protected instance linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [vector_space F V] [finite_dimensional F V] : finite_dimensional K (linear_map F V K) := right F K (linear_map F V K) theorem findim_linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [vector_space F V] [finite_dimensional F V] : findim K (linear_map F V K) = findim F V := iff.mp (nat.mul_right_inj ((fun (this : 0 < findim F K) => this) findim_pos)) (Eq.trans (Eq.trans (findim_mul_findim F K (linear_map F V K)) (findim_linear_map F V K)) (mul_comm (findim F V) (findim F K))) end Mathlib
{- HOW TO: 1) install cabal and idris 2) run: $ idris hello.idr -o hello $ ./hello -} module Main main : IO () main = putStrLn "Hello world"
function [epoch, jd] = mydatemjdi (mjd) jd = mjd + 2400000.5; epoch = mydatejdi (jd); end %!test %! num = mydatenum([1858 11 17 0 0 0]); %! num2 = mydatemjdi(0); %! myassert (num2, num)
# start in REPL or with: julia htttp_webserver_simple.jl: using HTTP HTTP.listen() do http # 1 while !eof(http) # 2 println("body data: ", String(readavailable(http))) # 3 end HTTP.setstatus(http, 200) HTTP.setheader(http, "Content-Type" => "text/html") # 4 HTTP.startwrite(http) # 5 write(http, "ToDo 1: Getting groceries<br>") # 6 write(http, "ToDo 2: Visiting my therapist<br>") write(http, "ToDo 3: Getting a haircut") end # const host = # ip-address in string format, like "127.0.0.1" # const port = 8081 # HTTP.listen(host, port) do http #   # code                       # end
[STATEMENT] lemma B_eval1: "\<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (lift (lift g 0) 0 \<degree> (Var 1 \<degree> Var 0)))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (lift (lift g 0) 0 \<degree> (Var 1 \<degree> Var 0))) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (lift (lift g 0) 0 \<degree> (Var 1 \<degree> Var 0))) [PROOF STEP] have "\<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (Var 2 \<degree> (Var 1 \<degree> Var 0))) [g/0]" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (Var 2 \<degree> (Var 1 \<degree> Var 0)))[g/0] [PROOF STEP] unfolding B_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. Abs (Abs (Abs (Var 2 \<degree> (Var 1 \<degree> Var 0)))) \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (Var 2 \<degree> (Var 1 \<degree> Var 0)))[g/0] [PROOF STEP] .. [PROOF STATE] proof (state) this: \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (Var 2 \<degree> (Var 1 \<degree> Var 0)))[g/0] goal (1 subgoal): 1. \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (lift (lift g 0) 0 \<degree> (Var 1 \<degree> Var 0))) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (Var 2 \<degree> (Var 1 \<degree> Var 0)))[g/0] [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (Var 2 \<degree> (Var 1 \<degree> Var 0)))[g/0] goal (1 subgoal): 1. \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (lift (lift g 0) 0 \<degree> (Var 1 \<degree> Var 0))) [PROOF STEP] by (simp add: numerals) [PROOF STATE] proof (state) this: \<B> \<degree> g \<rightarrow>\<^sub>\<beta> Abs (Abs (lift (lift g 0) 0 \<degree> (Var 1 \<degree> Var 0))) goal: No subgoals! [PROOF STEP] qed
test_that("str_length is number of characters", { expect_equal(str_length("a"), 1) expect_equal(str_length("ab"), 2) expect_equal(str_length("abc"), 3) }) test_that("str_length of missing string is missing", { expect_equal(str_length(NA), NA_integer_) expect_equal(str_length(c(NA, 1)), c(NA, 1)) expect_equal(str_length("NA"), 2) }) test_that("str_length of factor is length of level", { expect_equal(str_length(factor("a")), 1) expect_equal(str_length(factor("ab")), 2) expect_equal(str_length(factor("abc")), 3) }) test_that("str_width returns display width", { x <- c("\u0308", "x", "\U0001f60a") expect_equal(str_width(x), c(0, 1, 2)) })
open import Data.Nat open import Data.Vec using ( Vec ; [] ; _∷_ ) module OpenTheory2 where ---------------------------------------------------------------------- data _∈_ {A : Set} : A → {n : ℕ} → Vec A n → Set where here : {n : ℕ} {x : A} {xs : Vec A n} → x ∈ (x ∷ xs) there : {n : ℕ} {x y : A} {xs : Vec A n} (p : x ∈ xs) → x ∈ (y ∷ xs) ----------------------------------------------------------------------
lemma openin_contains_ball: "openin (top_of_set T) S \<longleftrightarrow> S \<subseteq> T \<and> (\<forall>x \<in> S. \<exists>e. 0 < e \<and> ball x e \<inter> T \<subseteq> S)" (is "?lhs = ?rhs")
""" Bridges `CP.Implication` to reification. """ struct Implication2ReificationBridge{T} <: MOIBC.AbstractBridge var_antecedent::MOI.VariableIndex var_consequent::MOI.VariableIndex var_antecedent_bin::MOI.ConstraintIndex{MOI.VariableIndex, MOI.ZeroOne} var_consequent_bin::MOI.ConstraintIndex{MOI.VariableIndex, MOI.ZeroOne} con_reif_antecedent::MOI.ConstraintIndex con_reif_consequent::MOI.ConstraintIndex # Ideally, Vector{MOI.ConstraintIndex{MOI.VectorAffineFunction{T}, CP.Reification{<: MOI.AbstractSet}}}, # but Julia has no notion of type erasure. con_implication::MOI.ConstraintIndex{MOI.ScalarAffineFunction{T}, MOI.GreaterThan{T}} end function MOIBC.bridge_constraint( ::Type{Implication2ReificationBridge{T}}, model, f::MOI.VectorOfVariables, s::CP.Implication{S1, S2}, ) where {T, S1, S2} return MOIBC.bridge_constraint( Implication2ReificationBridge{T}, model, MOI.VectorAffineFunction{T}(f), s, ) end function MOIBC.bridge_constraint( ::Type{Implication2ReificationBridge{T}}, model, f::MOI.VectorAffineFunction{T}, s::CP.Implication{S1, S2}, ) where {T, S1, S2} var_antecedent, var_antecedent_bin = MOI.add_constrained_variable(model, MOI.ZeroOne()) var_consequent, var_consequent_bin = MOI.add_constrained_variable(model, MOI.ZeroOne()) f_scalars = MOIU.scalarize(f) con_reif_antecedent = MOI.add_constraint( model, MOIU.vectorize( [ one(T) * var_antecedent, f_scalars[1 : MOI.dimension(s.antecedent)]..., ] ), CP.Reification(s.antecedent) ) con_reif_consequent = MOI.add_constraint( model, MOIU.vectorize( [ one(T) * var_consequent, f_scalars[(MOI.dimension(s.antecedent) + 1) : (MOI.dimension(s.antecedent) + MOI.dimension(s.consequent))]..., ] ), CP.Reification(s.consequent) ) # x ⟹ y is equivalent to ¬x ∨ y: # (1 - var_antecedent) + var_consequent ≥ 1 # var_consequent - var_antecedent ≥ 0 con_implication = MOI.add_constraint( model, one(T) * var_consequent - one(T) * var_antecedent, MOI.GreaterThan(zero(T)) ) return Implication2ReificationBridge(var_antecedent, var_consequent, var_antecedent_bin, var_consequent_bin, con_reif_antecedent, con_reif_consequent, con_implication) end function MOI.supports_constraint( ::Type{Implication2ReificationBridge{T}}, ::Union{Type{MOI.VectorOfVariables}, Type{MOI.VectorAffineFunction{T}}}, ::Type{CP.Implication{S1, S2}}, ) where {T, S1, S2} return true # Ideally, ensure that the underlying solver supports all the needed # reified constraints. end function MOIB.added_constrained_variable_types(::Type{Implication2ReificationBridge{T}}) where {T} return [(MOI.ZeroOne,)] end function MOIB.added_constraint_types(::Type{Implication2ReificationBridge{T}}) where {T} return [ (MOI.VectorAffineFunction{T}, CP.Reification), # TODO: how to be more precise? (MOI.ScalarAffineFunction{T}, MOI.GreaterThan{T}), ] end function MOI.get(::Implication2ReificationBridge{T}, ::MOI.NumberOfVariables) where {T} return 2 end function MOI.get( ::Implication2ReificationBridge{T}, ::MOI.NumberOfConstraints{ MOI.VariableIndex, MOI.ZeroOne, }, ) where {T} return 2 end function MOI.get( ::Implication2ReificationBridge{T}, ::MOI.NumberOfConstraints{ MOI.VectorAffineFunction{T}, CP.Reification, }, ) where {T} return 2 end function MOI.get( ::Implication2ReificationBridge{T}, ::MOI.NumberOfConstraints{ MOI.ScalarAffineFunction{T}, MOI.GreaterThan{T}, }, ) where {T} return 1 end function MOI.get( b::Implication2ReificationBridge{T}, ::MOI.ListOfVariableIndices, ) where {T} return [b.var_antecedent, b.var_consequent] end function MOI.get( b::Implication2ReificationBridge{T}, ::MOI.ListOfConstraintIndices{ MOI.VariableIndex, MOI.ZeroOne, }, ) where {T} return [b.var_antecedent_bin, b.var_consequent_bin] end function MOI.get( b::Implication2ReificationBridge{T}, ::MOI.ListOfConstraintIndices{ MOI.VectorAffineFunction{T}, CP.Reification, }, ) where {T} return [b.con_reif_antecedent, b.con_reif_consequent] end function MOI.get( b::Implication2ReificationBridge{T}, ::MOI.ListOfConstraintIndices{ MOI.ScalarAffineFunction{T}, MOI.GreaterThan{T}, }, ) where {T} return [b.con_implication] end
module Ch02.Perceptron where import Prelude hiding (and, or) import Numeric.LinearAlgebra and_ :: (Ord a, Fractional a, Num b) => a -> a -> b and_ x1 x2 = if (x1*w1 + x2*w2) <= theta then 0 else 1 where w1 = 0.5 w2 = 0.5 theta = 0.7 -- λ> and_ 0 0 -- 0 -- λ> and_ 1 0 -- 0 -- λ> and_ 0 1 -- 0 -- λ> and_ 1 1 -- 1 perceptron :: R -> R -> R -> R -> R -> R perceptron w1 w2 b = \x1 x2 -> if (sum $ toList $ (vector [x1,x2]) * vector [w1,w2]) + b <= 0 then 0 else 1 and = perceptron 0.5 0.5 (-0.7) nand = perceptron (-0.5) (-0.5) 0.7 or = perceptron 0.5 0.5 (-0.2) xor x1 x2 = and (nand x1 x2) (or x1 x2)
# This file was generated, do not modify it. # hide using Soss N = 10000 m = @model x, λ begin σ ~ Exponential(λ) β ~ Normal(0,1) y ~ For(1:N) do j Normal(x[j] * β, σ) end return y end
From Coq Require Import Arith String. From ExtLib Require Import Data.String Structures.Monad Core.RelDec Data.Map.FMapAList. From Paco Require Import paco. From ITree Require Import Axioms ITree ITreeFacts Eq.Rutt Events.MapDefault Events.State Events.StateFacts. From ITree.Extra Require Import ITrace.ITraceDefinition ITrace.ITraceFacts ITrace.ITracePreds Dijkstra.DelaySpecMonad Dijkstra.DijkstraMonad Dijkstra.TracesIT Dijkstra.StateSpecT. Import Monads. Import MonadNotation. #[local] Open Scope monad_scope. Definition env := alist string nat. Variant StateE : Type -> Type := | GetE : string -> StateE nat | PutE : string -> nat -> StateE unit . Variant IO : Type -> Type := | Read : IO nat | Write : nat -> IO unit . Notation stateiotree A := (itree (StateE +' IO) A). Definition StateIOSpec : Type -> Type := StateSpecT env (TraceSpec IO). Definition SIOSpecOrder := StateSpecTOrder env (TraceSpec IO). Definition SIOSpecOrderLaws := StateSpecTOrderedLaws env (TraceSpec IO). Definition SIOSpecEq := StateSpecTEq env (TraceSpec IO). Definition SIOObs := EffectObsStateT env (TraceSpec IO) (itree IO). Definition SIOMorph :=MonadMorphimStateT env (TraceSpec IO) (itree IO). Definition verify_cond {A : Type} := DijkstraProp (stateT env (itree IO)) StateIOSpec SIOObs A. (*Predicate on initial state and initial log*) Definition StateIOSpecPre : Type := env -> ev_list IO -> Prop. (*Predicate on final log and possible return value*) Definition StateIOSpecPost (A : Type) : Type := itrace IO (env * A) -> Prop. Program Definition encode {A} (pre : StateIOSpecPre) (post : StateIOSpecPost A) : StateIOSpec A := fun s log p => pre s log /\ (forall tr, post tr -> p tr). Section PrintMults. Variable X Y : string. Context (HXY : X <> Y). (*this part has some pretty basic errors*) Variant write_next_mult (n : nat) : forall B, IO B -> B -> Prop := | wnm : write_next_mult n unit (Write n) tt. Definition wnm_ev (next : nat) A (io : IO A) (_ : A) : forall B, IO B -> B -> Prop := match io with | Write n => write_next_mult (next + n) | Read => bot3 end. Variant writes_n (n : nat) : forall A, IO A -> A -> Prop := | wn : writes_n n unit (Write n) tt. Definition mults_n {R : Type} (n : nat) (tr : itrace IO R) := state_machine (wnm_ev n) bot4 (writes_n 0) bot1 tr. CoFixpoint mults_of_n_from_m {R : Type} (n m : nat) : itrace IO R:= Vis (evans unit (Write m) tt) (fun _ => mults_of_n_from_m n (n + m) ). Definition mults_of_n {R : Type} (n : nat) : itrace IO R := mults_of_n_from_m n 0. Definition print_mults_pre : StateIOSpecPre := fun s log => log = nil /\ lookup_default Y 0 s = 0. (*Is there going to be a problem introducing k?*) Definition print_mults_post : StateIOSpecPost unit := fun tr => exists n k, (tr ≈ Vis (evans _ Read n) k /\ (mults_of_n n) ≈ (k tt))%itree. Definition print_mults : stateiotree unit := x <- trigger Read;; trigger (PutE X x);; ITree.iter ( fun _ : unit => y <- trigger (GetE Y);; trigger (Write y);; x <- trigger (GetE X);; trigger (PutE Y (y + x));; Ret (inl tt) ) tt. Definition add (V : string) (v : nat) (s : env) : env := alist_add _ V v s. Definition handleIOStateE (A : Type) (ev : (StateE +' IO) A) : stateT env (itree IO) A := fun s => match ev with | inl1 ev' => match ev' with | GetE V => Ret (s, lookup_default V 0 s) | PutE V v => Ret (Maps.add V v s, tt) end | inr1 ev' => Vis ev' (fun x => Ret (s,x) ) end. Ltac unf_res := unfold resum, ReSum_id, id_, Id_IFun in *. Lemma lookup_eq : forall (s : env) (x : string) (v d : nat), lookup_default x d (Maps.add x v s) = v. Proof. intros. assert (Maps.mapsto x v (Maps.add x v s) ). { apply Maps.mapsto_add_eq; try reflexivity. } eapply Maps.mapsto_lookup in H. unfold lookup_default. rewrite H. auto. Qed. Lemma lookup_nin : forall (x : string) (s : env), (forall v : nat, ~ Maps.mapsto x v s) -> Maps.lookup x s = None. Proof. intros. red in s. red in s. generalize dependent x. induction s; intros; auto. - cbn. destruct a as [y v]. destruct (Strings.String.string_dec x y). + subst. exfalso. eapply H. red. cbn. red. cbn. rewrite RelDec.rel_dec_eq_true; auto. apply RelDec_Correct_string. + rewrite RelDec.rel_dec_neq_false; auto; try apply RelDec_Correct_string. unfold Maps.lookup in IHs. cbn in *. apply IHs; auto. intros. intro Hcontra. eapply H. red. cbn. rewrite RelDec.rel_dec_neq_false; eauto; try apply RelDec_Correct_string. Qed. Lemma lookup_neq : forall (s : env) (x y: string) (v d: nat), x <> y -> lookup_default x d (Maps.add y v s) = lookup_default x d s. Proof. intros. destruct (classic (exists v', Maps.mapsto x v' s)). - destruct H0 as [v' Hv']. assert (Maps.mapsto x v' (Maps.add y v s)). { eapply Maps.mapsto_add_neq in Hv'; eauto. } apply Maps.mapsto_lookup in H0. apply Maps.mapsto_lookup in Hv'. unfold lookup_default. rewrite Hv'. rewrite H0. auto. - assert (forall v',~ Maps.mapsto x v' s). { intros v' Hc. apply H0. exists v'. auto. } clear H0. apply lookup_nin in H1 as Hs. unfold lookup_default. rewrite Hs. assert (forall v', ~Maps.mapsto x v' (Maps.add y v s)). { intros v' Hcontra. apply Maps.mapsto_add_neq in Hcontra; auto. eapply H1; eauto. } apply lookup_nin in H0 as Hs'. rewrite Hs'. auto. Qed. Ltac prove_arg H := let H' := fresh H in match type of H with ?P -> _ => assert (H' : P); try (specialize (H H'); clear H') end. Lemma print_mults_sats_spec : verify_cond (encode print_mults_pre print_mults_post) (interp_state handleIOStateE print_mults). Proof. repeat red. simpl. intros s log [p Hp] [Hpre H'] b Href. simpl in *. apply H'. clear H'. unfold print_mults_pre in Hpre. destruct Hpre as [Hlog Henv]. subst. unfold print_mults_post. setoid_rewrite append_nil. unfold print_mults in Href. setoid_rewrite interp_state_bind in Href. setoid_rewrite interp_state_trigger in Href. setoid_rewrite bind_vis in Href. apply trace_refine_vis in Href as Hbhd. basic_solve. rewrite Hbhd in Href. setoid_rewrite Hbhd. destruct e0. 2 : destruct ev; assert void; try apply Hempty; try constructor; contradiction. assert (A = nat). { destruct ev; auto. cbn in *. pinversion Href. ddestruction; subst. cbn in *. inversion H1; auto. } subst. rename ans into n. exists n. match type of Href with _ ⊑ Vis _ ?k => remember k as kp end. exists k0. split. { simpl in Href. clear Henv. unf_res. pinversion Href. ddestruction; subst. inversion H1. ddestruction; subst. reflexivity. } clear Hp p Hbhd b. assert (k0 tt ⊑ kp n). { clear Heqkp. pinversion Href. ddestruction; subst. unfold resum, ReSum_id, id_, Id_IFun in *. inversion H1. ddestruction; subst. assert (RAnsRef IO unit nat (evans nat Read n) tt Read n); auto with itree. apply H6 in H. pclearbot. auto. } clear Href ev. subst. rewrite bind_ret_l in H. simpl in *. rewrite interp_state_bind in H. rewrite interp_state_trigger in H. simpl in *. rewrite bind_ret_l in H. simpl in *. specialize (@interp_state_iter' (StateE +' IO) ) as Hiter. unfold state_eq in Hiter. rewrite Hiter in H. clear Hiter. remember (Maps.add X n s) as si. assert (si = alist_add RelDec_string X n s); try (subst; auto; fail). rewrite <- H0 in H. clear H0. unfold mults_of_n. remember 0 as next_to_write. (*set up invariant for the coind hyp*) assert (lookup_default Y 0 si = next_to_write). { subst. rewrite lookup_neq; auto. } assert(lookup_default X 0 si = n). { subst. apply lookup_eq. } clear Heqsi Heqnext_to_write Henv s. generalize dependent si. remember (k0 tt) as tr. clear Heqtr k0. generalize dependent tr. generalize dependent next_to_write. pcofix CIH. (*This coinductive hypothesis looks good*) intros. rename H1 into HX. pfold. red. (*should be able to learn that observe tr is what we need*) (*This block shows how to proceed through the loop body*) rename H0 into H. unfold Basics.iter, MonadIter_stateT0, Basics.iter, MonadIter_itree in H. rewrite unfold_iter in H. match type of H with _ ⊑ ITree.bind _ ?k0 => remember k0 as k end. setoid_rewrite bind_bind in H. rewrite bind_trigger in H. setoid_rewrite interp_state_vis in H. cbn in H. rewrite bind_ret_l in H. rewrite tau_eutt in H. setoid_rewrite bind_trigger in H. rewrite interp_state_vis in H. cbn in H. rewrite bind_vis in H. rewrite bind_vis in H. setoid_rewrite bind_ret_l in H. unf_res. punfold H. red in H. cbn in *. dependent induction H. 2:{ rewrite <- x. constructor; auto. eapply IHruttF; eauto; reflexivity. } inversion H; ddestruction; subst; ddestruction; try contradiction. subst. specialize (H0 tt tt). destruct a. prove_arg H0; auto with itree. pclearbot. match type of H0 with paco2 _ bot2 ?tr ?t => assert (Hk1 : tr ⊑ t); auto end. rewrite <- x. constructor; auto. intros []. clear x tr. right. remember (lookup_default X 0 si) as n. remember (lookup_default Y 0 si) as m. eapply CIH with (Maps.add Y (n + m) si); try apply lookup_eq. 2: { rewrite lookup_neq; subst; auto. } rewrite tau_eutt in Hk1. setoid_rewrite bind_trigger in Hk1. setoid_rewrite interp_state_vis in Hk1. cbn in *. rewrite bind_ret_l in Hk1. rewrite tau_eutt in Hk1. setoid_rewrite bind_vis in Hk1. setoid_rewrite interp_state_vis in Hk1. cbn in *. rewrite bind_ret_l in Hk1. rewrite bind_ret_l in Hk1. rewrite tau_eutt in Hk1. cbn in *. rewrite interp_state_ret in Hk1. rewrite bind_ret_l in Hk1. cbn in *. rewrite tau_eutt in Hk1. unfold Basics.iter, MonadIter_stateT0, Basics.iter, MonadIter_itree. match goal with H : _ ⊑ ITree.iter _ (?s1, _) |- _ ⊑ ITree.iter _ (?s2, _) => enough (Hseq : s2 = s1) end; try rewrite Hseq; auto. subst. rewrite Nat.add_comm. auto. Qed. End PrintMults.
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.primitive_element import linear_algebra.determinant import linear_algebra.matrix.charpoly.coeff import linear_algebra.matrix.to_linear_equiv import ring_theory.power_basis /-! # Norm for (finite) ring extensions Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`, the determinant of the linear map given by multiplying by `s` gives information about the roots of the minimal polynomial of `s` over `R`. ## Implementation notes Typically, the norm is defined specifically for finite field extensions. The current definition is as general as possible and the assumption that we have fields or that the extension is finite is added to the lemmas as needed. We only define the norm for left multiplication (`algebra.left_mul_matrix`, i.e. `algebra.lmul_left`). For now, the definitions assume `S` is commutative, so the choice doesn't matter anyway. See also `algebra.trace`, which is defined similarly as the trace of `algebra.left_mul_matrix`. ## References * https://en.wikipedia.org/wiki/Field_norm -/ universes u v w variables {R S T : Type*} [comm_ring R] [is_domain R] [comm_ring S] variables [algebra R S] variables {K L F : Type*} [field K] [field L] [field F] variables [algebra K L] [algebra L F] [algebra K F] variables {ι : Type w} [fintype ι] open finite_dimensional open linear_map open matrix open_locale big_operators open_locale matrix namespace algebra variables (R) /-- The norm of an element `s` of an `R`-algebra is the determinant of `(*) s`. -/ noncomputable def norm : S →* R := linear_map.det.comp (lmul R S).to_ring_hom.to_monoid_hom lemma norm_apply (x : S) : norm R x = linear_map.det (lmul R S x) := rfl lemma norm_eq_one_of_not_exists_basis (h : ¬ ∃ (s : finset S), nonempty (basis s R S)) (x : S) : norm R x = 1 := by { rw [norm_apply, linear_map.det], split_ifs with h, refl } variables {R} -- Can't be a `simp` lemma because it depends on a choice of basis lemma norm_eq_matrix_det [decidable_eq ι] (b : basis ι R S) (s : S) : norm R s = matrix.det (algebra.left_mul_matrix b s) := by rw [norm_apply, ← linear_map.det_to_matrix b, to_matrix_lmul_eq] /-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. -/ lemma norm_algebra_map_of_basis (b : basis ι R S) (x : R) : norm R (algebra_map R S x) = x ^ fintype.card ι := begin haveI := classical.dec_eq ι, rw [norm_apply, ← det_to_matrix b, lmul_algebra_map], convert @det_diagonal _ _ _ _ _ (λ (i : ι), x), { ext i j, rw [to_matrix_lsmul, matrix.diagonal] }, { rw [finset.prod_const, finset.card_univ] } end /-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. (If `L` is not finite-dimensional over `K`, then `norm = 1 = x ^ 0 = x ^ (finrank L K)`.) -/ @[simp] lemma norm_algebra_map (x : K) : norm K (algebra_map K L x) = x ^ finrank K L := begin by_cases H : ∃ (s : finset L), nonempty (basis s K L), { rw [norm_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] }, { rw [norm_eq_one_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis, pow_zero], rintros ⟨s, ⟨b⟩⟩, exact H ⟨s, ⟨b⟩⟩ }, end section eq_prod_roots lemma norm_gen_eq_prod_roots [algebra K S] (pb : power_basis K S) (hf : (minpoly K pb.gen).splits (algebra_map K F)) : algebra_map K F (norm K pb.gen) = ((minpoly K pb.gen).map (algebra_map K F)).roots.prod := begin -- Write the LHS as the 0'th coefficient of `minpoly K pb.gen` rw [norm_eq_matrix_det pb.basis, det_eq_sign_charpoly_coeff, charpoly_left_mul_matrix, ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_neg, ring_hom.map_one, ← polynomial.coeff_map, fintype.card_fin], -- Rewrite `minpoly K pb.gen` as a product over the roots. conv_lhs { rw polynomial.eq_prod_roots_of_splits hf }, rw [polynomial.coeff_C_mul, polynomial.coeff_zero_multiset_prod, multiset.map_map, (minpoly.monic pb.is_integral_gen).leading_coeff, ring_hom.map_one, one_mul], -- Incorporate the `-1` from the `charpoly` back into the product. rw [← multiset.prod_repeat (-1 : F), ← pb.nat_degree_minpoly, polynomial.nat_degree_eq_card_roots hf, ← multiset.map_const, ← multiset.prod_map_mul], -- And conclude that both sides are the same. congr, convert multiset.map_id _, ext f, simp end end eq_prod_roots section eq_zero_iff lemma norm_eq_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} : algebra.norm R x = 0 ↔ x = 0 := begin have hι : nonempty ι := b.index_nonempty, letI := classical.dec_eq ι, rw algebra.norm_eq_matrix_det b, split, { rw ← matrix.exists_mul_vec_eq_zero_iff, rintros ⟨v, v_ne, hv⟩, rw [← b.equiv_fun.apply_symm_apply v, b.equiv_fun_symm_apply, b.equiv_fun_apply, algebra.left_mul_matrix_mul_vec_repr] at hv, refine (mul_eq_zero.mp (b.ext_elem $ λ i, _)).resolve_right (show ∑ i, v i • b i ≠ 0, from _), { simpa only [linear_equiv.map_zero, pi.zero_apply] using congr_fun hv i }, { contrapose! v_ne with sum_eq, apply b.equiv_fun.symm.injective, rw [b.equiv_fun_symm_apply, sum_eq, linear_equiv.map_zero] } }, { rintro rfl, rw [alg_hom.map_zero, matrix.det_zero hι] }, end lemma norm_ne_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} : algebra.norm R x ≠ 0 ↔ x ≠ 0 := not_iff_not.mpr (algebra.norm_eq_zero_iff_of_basis b) /-- See also `algebra.norm_eq_zero_iff'` if you already have rewritten with `algebra.norm_apply`. -/ @[simp] lemma norm_eq_zero_iff [finite_dimensional K L] {x : L} : algebra.norm K x = 0 ↔ x = 0 := algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L) /-- This is `algebra.norm_eq_zero_iff` composed with `algebra.norm_apply`. -/ @[simp] lemma norm_eq_zero_iff' [finite_dimensional K L] {x : L} : linear_map.det (algebra.lmul K L x) = 0 ↔ x = 0 := algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L) end eq_zero_iff open intermediate_field variable (K) lemma norm_eq_norm_adjoin [finite_dimensional K L] [is_separable K L] (x : L) : norm K x = norm K (adjoin_simple.gen K x) ^ finrank K⟮x⟯ L := begin letI := is_separable_tower_top_of_is_separable K K⟮x⟯ L, let pbL := field.power_basis_of_finite_of_separable K⟮x⟯ L, let pbx := intermediate_field.adjoin.power_basis (is_separable.is_integral K x), rw [← adjoin_simple.algebra_map_gen K x, norm_eq_matrix_det (pbx.basis.smul pbL.basis) _, smul_left_mul_matrix_algebra_map, det_block_diagonal, norm_eq_matrix_det pbx.basis], simp only [finset.card_fin, finset.prod_const, adjoin.power_basis_basis], congr, rw [← power_basis.finrank, adjoin_simple.algebra_map_gen K x], end section eq_prod_embeddings variable {K} open intermediate_field intermediate_field.adjoin_simple polynomial variables (E : Type*) [field E] [algebra K E] [is_scalar_tower K L F] lemma norm_eq_prod_embeddings_gen (pb : power_basis K L) (hE : (minpoly K pb.gen).splits (algebra_map K E)) (hfx : (minpoly K pb.gen).separable) : algebra_map K E (norm K pb.gen) = (@@finset.univ (power_basis.alg_hom.fintype pb)).prod (λ σ, σ pb.gen) := begin letI := classical.dec_eq E, rw [norm_gen_eq_prod_roots pb hE, fintype.prod_equiv pb.lift_equiv', finset.prod_mem_multiset, finset.prod_eq_multiset_prod, multiset.to_finset_val, multiset.erase_dup_eq_self.mpr, multiset.map_id], { exact nodup_roots ((separable_map _).mpr hfx) }, { intro x, refl }, { intro σ, rw [power_basis.lift_equiv'_apply_coe, id.def] } end variable (F) lemma prod_embeddings_eq_finrank_pow [is_alg_closed E] [is_separable K F] [finite_dimensional K F] (pb : power_basis K L) : ∏ σ : F →ₐ[K] E, σ (algebra_map L F pb.gen) = ((@@finset.univ (power_basis.alg_hom.fintype pb)).prod (λ σ : L →ₐ[K] E, σ pb.gen)) ^ finrank L F := begin haveI : finite_dimensional L F := finite_dimensional.right K L F, haveI : is_separable L F := is_separable_tower_top_of_is_separable K L F, letI : fintype (L →ₐ[K] E) := power_basis.alg_hom.fintype pb, letI : ∀ (f : L →ₐ[K] E), fintype (@@alg_hom L F E _ _ _ _ f.to_ring_hom.to_algebra) := _, rw [fintype.prod_equiv alg_hom_equiv_sigma (λ (σ : F →ₐ[K] E), _) (λ σ, σ.1 pb.gen), ← finset.univ_sigma_univ, finset.prod_sigma, ← finset.prod_pow], refine finset.prod_congr rfl (λ σ _, _), { letI : algebra L E := σ.to_ring_hom.to_algebra, simp only [finset.prod_const, finset.card_univ], congr, rw alg_hom.card L F E }, { intros σ, simp only [alg_hom_equiv_sigma, equiv.coe_fn_mk, alg_hom.restrict_domain, alg_hom.comp_apply, is_scalar_tower.coe_to_alg_hom'] } end variable (K) /-- For `L/K` a finite separable extension of fields and `E` an algebraically closed extension of `K`, the norm (down to `K`) of an element `x` of `L` is equal to the product of the images of `x` over all the `K`-embeddings `σ` of `L` into `E`. -/ lemma norm_eq_prod_embeddings [finite_dimensional K L] [is_separable K L] [is_alg_closed E] {x : L} : algebra_map K E (norm K x) = ∏ σ : L →ₐ[K] E, σ x := begin have hx := is_separable.is_integral K x, rw [norm_eq_norm_adjoin K x, ring_hom.map_pow, ← adjoin.power_basis_gen hx, norm_eq_prod_embeddings_gen E (adjoin.power_basis hx) (is_alg_closed.splits_codomain _)], { exact (prod_embeddings_eq_finrank_pow L E (adjoin.power_basis hx)).symm }, { haveI := is_separable_tower_bot_of_is_separable K K⟮x⟯ L, exact is_separable.separable K _ } end end eq_prod_embeddings end algebra
[STATEMENT] lemma col_ket_vec_index [simp]: assumes "i < dim_row v" shows "|col v 0\<rangle> $$ (i,0) = v $$ (i,0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. |col v 0\<rangle> $$ (i, 0) = v $$ (i, 0) [PROOF STEP] using assms ket_vec_def [PROOF STATE] proof (prove) using this: i < dim_row v |?v\<rangle> \<equiv> mat (dim_vec ?v) 1 (\<lambda>(i, j). ?v $ i) goal (1 subgoal): 1. |col v 0\<rangle> $$ (i, 0) = v $$ (i, 0) [PROOF STEP] by (simp add: col_def)
lemma has_field_derivative_inverse_strong_x: fixes f :: "'a::{euclidean_space,real_normed_field} \<Rightarrow> 'a" shows "\<lbrakk>DERIV f (g y) :> f'; f' \<noteq> 0; open S; continuous_on S f; g y \<in> S; f(g y) = y; \<And>z. z \<in> S \<Longrightarrow> g (f z) = z\<rbrakk> \<Longrightarrow> DERIV g y :> inverse (f')"
module Test.StrictCheck.Consume ( Input , Inputs , Consume(..) , constructor , normalize , consumeTrivial , consumePrimitive ) where import Test.QuickCheck import Generics.SOP import Generics.SOP.NS import Test.StrictCheck.Internal.Inputs import Data.Monoid as Monoid import Data.Semigroup as Semigroup import Control.Applicative import Control.Monad.State import Control.Monad.Cont import Control.Monad.Except import Control.Monad.Identity import Control.Monad.RWS import Control.Monad.Reader import Control.Monad.Writer import Control.Monad.ST import GHC.Conc import Data.Functor.Product as Functor import Data.Functor.Sum as Functor import Data.Functor.Compose as Functor import Data.Complex import Data.Foldable as Fold import Data.List.NonEmpty (NonEmpty(..)) import Data.Tree as Tree import Data.Set as Set import Data.Map as Map import Data.Sequence as Seq import Data.IntMap as IntMap import Data.IntSet as IntSet ------------------------------------------------------- -- The user interface for creating Consume instances -- ------------------------------------------------------- -- | Generate a tree of all possible ways to destruct the input value. class Consume a where consume :: a -> Input default consume :: GConsume a => a -> Input consume = gConsume -- | Reassemble pieces of input into a larger Input. constructor :: Int -> [Input] -> Input constructor n !is = Input (Variant (variant n)) is -- | Use the CoArbitrary instance for a type to consume it. This should only be -- used for "flat" types, i.e. those which contain no interesting substructure. consumePrimitive :: CoArbitrary a => a -> Input consumePrimitive !a = Input (Variant (coarbitrary a)) [] -- | If a type has no observable properties or substructure which can be used -- to drive the randomization of output, consumption should merely evaluate a -- value to weak-head normal form. consumeTrivial :: a -> Input consumeTrivial !_ = Input mempty [] -- | Fully normalize something which can be consumed normalize :: Consume a => a -> () normalize (consume -> input) = go input where go (Input _ is) = Fold.foldr seq () (fmap go is) -------------------------------------------- -- Deriving Consume instances generically -- -------------------------------------------- type GConsume a = (Generic a, All2 Consume (Code a)) gConsume :: GConsume a => a -> Input gConsume !(from -> sop) = constructor (index_SOP sop) . hcollapse . hcliftA (Proxy :: Proxy Consume) (K . consume . unI) $ sop --------------- -- Instances -- --------------- instance Consume (IO a) where consume = consumeTrivial instance Consume (STM a) where consume = consumeTrivial instance Consume (ST s a) where consume = consumeTrivial instance Consume (a -> b) where consume = consumeTrivial instance Consume (Proxy p) where consume = consumeTrivial instance Consume Char where consume = consumePrimitive instance Consume Word where consume = consumePrimitive instance Consume Int where consume = consumePrimitive instance Consume Double where consume = consumePrimitive instance Consume Float where consume = consumePrimitive instance Consume Rational where consume = consumePrimitive instance Consume Integer where consume = consumePrimitive instance (CoArbitrary a, RealFloat a) => Consume (Complex a) where consume = consumePrimitive deriving newtype instance Consume a => Consume (Identity a) deriving newtype instance Consume (RWST r w s m a) deriving newtype instance Consume (ReaderT r m a) deriving newtype instance Consume (StateT s m a) deriving newtype instance Consume (m (a, w)) => Consume (WriterT w m a) deriving newtype instance Consume (ContT r m a) deriving newtype instance Consume (m (Either e a)) => Consume (ExceptT e m a) deriving newtype instance Consume a => Consume (ZipList a) deriving newtype instance Consume a => Consume (Monoid.First a) deriving newtype instance Consume a => Consume (Monoid.Last a) deriving newtype instance Consume a => Consume (Semigroup.First a) deriving newtype instance Consume a => Consume (Semigroup.Last a) deriving newtype instance Consume a => Consume (Min a) deriving newtype instance Consume a => Consume (Max a) deriving newtype instance Consume a => Consume (Monoid.Sum a) deriving newtype instance Consume a => Consume (Monoid.Product a) deriving newtype instance Consume (f (g a)) => Consume (Functor.Compose f g a) deriving newtype instance Consume a => Consume (Dual a) deriving newtype instance Consume a => Consume (Const a b) instance Consume () instance Consume Bool instance Consume Ordering instance Consume a => Consume (Maybe a) instance (Consume a, Consume b) => Consume (Either a b) instance Consume a => Consume [a] deriving newtype instance Consume a => Consume (I a) deriving newtype instance Consume a => Consume (K a b) -- TODO: instances for the rest of the SOP newtypes instance (Consume (f a), Consume (g a)) => Consume (Functor.Sum f g a) where consume (InL a) = constructor 0 [consume a] consume (InR b) = constructor 1 [consume b] instance (Consume (f a), Consume (g a)) => Consume (Functor.Product f g a) where consume (Pair a b) = constructor 0 [consume a, consume b] instance (Consume a, Consume b) => Consume (Semigroup.Arg a b) where consume (Arg a b) = constructor 0 [consume a, consume b] instance Consume a => Consume (NonEmpty a) where consume (a :| as) = constructor 0 [consume a, consume as] instance Consume a => Consume (Tree a) where consume (Node a as) = constructor 0 [consume a, consume as] instance Consume v => Consume (Map k v) where consume = constructor 0 . fmap (consume . snd) . Map.toList consumeContainer :: (Consume a, Foldable t) => t a -> Input consumeContainer = constructor 0 . fmap consume . Fold.toList instance Consume v => Consume (Seq v) where consume = consumeContainer instance Consume v => Consume (Set v) where consume = consumeContainer instance Consume v => Consume (IntMap v) where consume = consumeContainer instance Consume v => Consume IntSet where consume = consumeContainer . IntSet.toList -- TODO: instances for the rest of Containers instance (Consume a, Consume b) => Consume (a, b) instance (Consume a, Consume b, Consume c) => Consume (a, b, c) instance (Consume a, Consume b, Consume c, Consume d) => Consume (a, b, c, d) instance ( Consume a, Consume b, Consume c, Consume d, Consume e ) => Consume (a, b, c, d, e) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f ) => Consume (a, b, c, d, e, f) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g ) => Consume (a, b, c, d, e, f, g) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h ) => Consume (a, b, c, d, e, f, g, h) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i ) => Consume (a, b, c, d, e, f, g, h, i) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j ) => Consume (a, b, c, d, e, f, g, h, i, j) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k ) => Consume (a, b, c, d, e, f, g, h, i, j, k) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s, Consume t ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s, Consume t, Consume u ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s, Consume t, Consume u, Consume v ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s, Consume t, Consume u, Consume v, Consume w ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s, Consume t, Consume u, Consume v, Consume w, Consume x ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s, Consume t, Consume u, Consume v, Consume w, Consume x , Consume y ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y) instance ( Consume a, Consume b, Consume c, Consume d, Consume e, Consume f , Consume g, Consume h, Consume i, Consume j, Consume k, Consume l , Consume m, Consume n, Consume o, Consume p, Consume q, Consume r , Consume s, Consume t, Consume u, Consume v, Consume w, Consume x , Consume y, Consume z ) => Consume (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_drotg (double *a, double *b, double *c, double *s) { #define BASE double #include "source_rotg.h" #undef BASE }
[STATEMENT] lemma cr_vreal_right_total[transfer_rule]: "right_total cr_vreal" [PROOF STATE] proof (prove) goal (1 subgoal): 1. right_total cr_vreal [PROOF STEP] unfolding cr_vreal_def right_total_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>y. \<exists>x. x = y\<^sub>\<real> [PROOF STEP] by simp
The 9-Line Medevac Request: Get it right the first time! Probably the most important thing for a young solider to learn is how to properly call in a Nine-Line Medevac request for serious or life-threatening injuries. In these circumstances every second counts, so there’s just not enough time to learn on the job. Protect your battle buddies by studying the Nine-Line Medevac request form regularly. Commit it to memory, and always keep a copy written on a nearby reference! Also, here’s just one more thought to keep in mind: Try to keep your radio traffic brief so that you don’t tie up the entire frequency. Other people might need to put out critical information such as the location of the enemy. Get in the habit of opening the microphone every two or three lines or so, just in case the dispatchers need to confirm your information. Line 1- Your first information needs to be the location of the pickup site. It’s important to put this out first, so that helicopters can start scrambling and heading your way as soon as possible. Make sure to give exact GPS coordinates if you can, but don’t forget that any route names or landmarks will be a big help too. Line 2- The next information to pass along is your radio frequency and issued call sign, along with the proper suffix. The command center needs to know exactly which unit they’re dealing with so that they can notify your chain of command as soon as possible. Line 4- Next, take a few seconds to list any special medical equipment that might be needed. The flight crew and the medics will start preparing their gear while they’re in the air and en route to your location. NOTE: During times of peace, Line 6 is used to list the type and number of wounds. This isn’t an excuse to get long-winded, though: Remember, every second counts. Line 7- Describe your method of marking the pick-up site. Line 9- Last, describe any possible Nuclear, Biological, or Chemical (NBC) contamination around your location. Use the letters for the appropriate threat. The actual Nine-Line Medevac form states that in peacetime, this line should be used to deliver a brief description of the terrain at the landing site. However, you should always be aware of any radiation or chemical contamination concerns. Make sure to relay any hazards to your flight crew so that they can plan accordingly and protect themselves.
[STATEMENT] lemma (in disc_equity_market) self_finance_trading_strat: assumes "trading_strategy pf" and "portfolio pf" and "borel_adapt_stoch_proc F (prices Mkt asset)" and "support_adapt Mkt pf" shows "trading_strategy (self_finance Mkt v pf asset)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. trading_strategy (self_finance Mkt v pf asset) [PROOF STEP] unfolding self_finance_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. trading_strategy (qty_sum pf (qty_single asset (remaining_qty Mkt v pf asset))) [PROOF STEP] proof (rule sum_trading_strat) [PROOF STATE] proof (state) goal (2 subgoals): 1. trading_strategy pf 2. trading_strategy (qty_single asset (remaining_qty Mkt v pf asset)) [PROOF STEP] show "trading_strategy pf" [PROOF STATE] proof (prove) goal (1 subgoal): 1. trading_strategy pf [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: trading_strategy pf portfolio pf borel_adapt_stoch_proc F (prices Mkt asset) support_adapt Mkt pf goal (1 subgoal): 1. trading_strategy pf [PROOF STEP] by simp [PROOF STATE] proof (state) this: trading_strategy pf goal (1 subgoal): 1. trading_strategy (qty_single asset (remaining_qty Mkt v pf asset)) [PROOF STEP] show "trading_strategy (qty_single asset (remaining_qty Mkt v pf asset))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. trading_strategy (qty_single asset (remaining_qty Mkt v pf asset)) [PROOF STEP] unfolding trading_strategy_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. portfolio (qty_single asset (remaining_qty Mkt v pf asset)) \<and> (\<forall>asseta\<in>support_set (qty_single asset (remaining_qty Mkt v pf asset)). borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) asseta)) [PROOF STEP] proof (intro conjI ballI) [PROOF STATE] proof (state) goal (2 subgoals): 1. portfolio (qty_single asset (remaining_qty Mkt v pf asset)) 2. \<And>asseta. asseta \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) asseta) [PROOF STEP] show "portfolio (qty_single asset (remaining_qty Mkt v pf asset))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. portfolio (qty_single asset (remaining_qty Mkt v pf asset)) [PROOF STEP] by (simp add: self_finance_def single_comp_portfolio) [PROOF STATE] proof (state) this: portfolio (qty_single asset (remaining_qty Mkt v pf asset)) goal (1 subgoal): 1. \<And>asseta. asseta \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) asseta) [PROOF STEP] show "\<And>a. a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>a. a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] proof (cases "support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}") [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] case False [PROOF STATE] proof (state) this: support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {} goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] hence eqasset: "support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {asset}" [PROOF STATE] proof (prove) using this: support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {} goal (1 subgoal): 1. support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {asset} [PROOF STEP] using single_comp_support [PROOF STATE] proof (prove) using this: support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {} support_set (qty_single ?asset ?qty) \<subseteq> {?asset} goal (1 subgoal): 1. support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {asset} [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {asset} goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] fix a [PROOF STATE] proof (state) goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] assume "a\<in> support_set (qty_single asset (remaining_qty Mkt v pf asset))" [PROOF STATE] proof (state) this: a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] hence "a = asset" [PROOF STATE] proof (prove) using this: a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) goal (1 subgoal): 1. a = asset [PROOF STEP] using eqasset [PROOF STATE] proof (prove) using this: a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {asset} goal (1 subgoal): 1. a = asset [PROOF STEP] by simp [PROOF STATE] proof (state) this: a = asset goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] hence "qty_single asset (remaining_qty Mkt v pf asset) a = (remaining_qty Mkt v pf asset)" [PROOF STATE] proof (prove) using this: a = asset goal (1 subgoal): 1. qty_single asset (remaining_qty Mkt v pf asset) a = remaining_qty Mkt v pf asset [PROOF STEP] unfolding qty_single_def [PROOF STATE] proof (prove) using this: a = asset goal (1 subgoal): 1. (qty_empty(asset := remaining_qty Mkt v pf asset)) a = remaining_qty Mkt v pf asset [PROOF STEP] by simp [PROOF STATE] proof (state) this: qty_single asset (remaining_qty Mkt v pf asset) a = remaining_qty Mkt v pf asset goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] moreover [PROOF STATE] proof (state) this: qty_single asset (remaining_qty Mkt v pf asset) a = remaining_qty Mkt v pf asset goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] have "borel_predict_stoch_proc F (remaining_qty Mkt v pf asset)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. borel_predict_stoch_proc F (remaining_qty Mkt v pf asset) [PROOF STEP] proof (rule remaining_qty_predict) [PROOF STATE] proof (state) goal (3 subgoals): 1. borel_adapt_stoch_proc F (prices Mkt asset) 2. trading_strategy pf 3. support_adapt Mkt pf [PROOF STEP] show "trading_strategy pf" [PROOF STATE] proof (prove) goal (1 subgoal): 1. trading_strategy pf [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: trading_strategy pf portfolio pf borel_adapt_stoch_proc F (prices Mkt asset) support_adapt Mkt pf goal (1 subgoal): 1. trading_strategy pf [PROOF STEP] by simp [PROOF STATE] proof (state) this: trading_strategy pf goal (2 subgoals): 1. borel_adapt_stoch_proc F (prices Mkt asset) 2. support_adapt Mkt pf [PROOF STEP] show "borel_adapt_stoch_proc F (prices Mkt asset)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. borel_adapt_stoch_proc F (prices Mkt asset) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: trading_strategy pf portfolio pf borel_adapt_stoch_proc F (prices Mkt asset) support_adapt Mkt pf goal (1 subgoal): 1. borel_adapt_stoch_proc F (prices Mkt asset) [PROOF STEP] by simp [PROOF STATE] proof (state) this: borel_adapt_stoch_proc F (prices Mkt asset) goal (1 subgoal): 1. support_adapt Mkt pf [PROOF STEP] show "support_adapt Mkt pf" [PROOF STATE] proof (prove) goal (1 subgoal): 1. support_adapt Mkt pf [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: trading_strategy pf portfolio pf borel_adapt_stoch_proc F (prices Mkt asset) support_adapt Mkt pf goal (1 subgoal): 1. support_adapt Mkt pf [PROOF STEP] by simp [PROOF STATE] proof (state) this: support_adapt Mkt pf goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: borel_predict_stoch_proc F (remaining_qty Mkt v pf asset) goal (2 subgoals): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) 2. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<noteq> {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: qty_single asset (remaining_qty Mkt v pf asset) a = remaining_qty Mkt v pf asset borel_predict_stoch_proc F (remaining_qty Mkt v pf asset) [PROOF STEP] show "borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a)" [PROOF STATE] proof (prove) using this: qty_single asset (remaining_qty Mkt v pf asset) a = remaining_qty Mkt v pf asset borel_predict_stoch_proc F (remaining_qty Mkt v pf asset) goal (1 subgoal): 1. borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] by simp [PROOF STATE] proof (state) this: borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) goal (1 subgoal): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] case True [PROOF STATE] proof (state) this: support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {} goal (1 subgoal): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] thus "\<And>a. a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<Longrightarrow> support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {} \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a)" [PROOF STATE] proof (prove) using this: support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {} goal (1 subgoal): 1. \<And>a. \<lbrakk>a \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) a) [PROOF STEP] by simp [PROOF STATE] proof (state) this: \<lbrakk>?a13 \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)); support_set (qty_single asset (remaining_qty Mkt v pf asset)) = {}\<rbrakk> \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) ?a13) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: ?a13 \<in> support_set (qty_single asset (remaining_qty Mkt v pf asset)) \<Longrightarrow> borel_predict_stoch_proc F (qty_single asset (remaining_qty Mkt v pf asset) ?a13) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: trading_strategy (qty_single asset (remaining_qty Mkt v pf asset)) goal: No subgoals! [PROOF STEP] qed
% NAME: % test_RANSAC_line_02.m % % DESC: % test to estimate the parameters of a line using real data close all clear % clc %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% load LineData % set RANSAC options options.epsilon = 1e-6; options.P_inlier = 0.99; options.sigma = 1; options.est_fun = @estimate_line; options.man_fun = @error_line; options.mode = 'MSAC'; options.Ps = []; options.notify_iters = []; options.min_iters = 100; options.fix_seed = false; options.reestimate = true; options.stabilize = false; %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % RANSAC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % run RANSAC [results, options] = RANSAC(X, options); %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Results Visualization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figure; hold on ind = results.CS; plot(X(1, ind), X(2, ind), '.g') plot(X(1, ~ind), X(2, ~ind), '.r') xlabel('x') ylabel('y') title('RANSAC results for 2D line estimation') legend('Inliers', 'Outliers') axis equal tight
------------------------------------------------ -- | -- Module : Numeric.Matrix.Integral -- Copyright : (c) Jun Yoshida 2019 -- License : BSD3 -- -- Operations on integer matrices -- ------------------------------------------------ module Numeric.Matrix.Integral ( -- Hermite normal form hermiteNF, -- Smith normal form smithNF, smithRep, ) where import Control.Monad import Control.Monad.ST (ST, runST) import Control.Monad.Loops (whileM_) import Data.STRef import qualified Numeric.LinearAlgebra as LA --import Numeric.Matrix.Integral.HNFLLL --import Numeric.Matrix.Integral.SmithNF import Numeric.Matrix.Integral.NormalForms -- Compute the submatrix containing all the non-zero diagonal entries extractMaxNZDiag :: LA.Matrix LA.Z -> (Int,LA.Matrix LA.Z) extractMaxNZDiag mx = runST $ do dRef <- newSTRef 0 let p d = d < uncurry min (LA.size mx) && (mx LA.! d LA.! d) /= 0 whileM_ (p <$> readSTRef dRef) $ modifySTRef' dRef (+1) d <- readSTRef dRef return (d,LA.subMatrix (0,0) (d,d) mx) -- D = P <> A <> Q -- | Return (d,ker,im) where -- d: the diagonal entries of Smith normal form -- ker: basis for the kernel -- im: basis for the image kerImOf :: LA.Matrix LA.Z -> (LA.Vector LA.Z,[LA.Vector LA.Z],[LA.Vector LA.Z]) kerImOf mt = let (ul,h,ur) = smithNF mt (ull,_,ulr) = smithNF ul (rk,dmt) = extractMaxNZDiag h ker' = ur LA.¿ [rk..(LA.cols ur-1)] (_,kert) = hermiteNF (LA.tr' ker') im' = (ulr LA.<> ull LA.<> h) LA.¿ [0..rk-1] (_,imt) = hermiteNF (LA.tr' im') in (LA.takeDiag dmt, LA.toRows kert, LA.toRows imt)
import numpy as np # THIS IS ULTRA SPECIFIC TO THE PROBLEM, Dont dare to use it!!!! TRUE_B = 2.3101 def SGLD(grad_log_density,grad_log_prior, X,n,chain_size=10000, thinning=1, theta=np.random.rand(2)): N = X.shape[0] X = np.random.permutation(X) samples = np.zeros((chain_size,2)) for t in range(chain_size*thinning): b=2.31 a = 0.01584 epsilon_t = a*(b+t)**(-0.55) noise = np.sqrt(epsilon_t)*np.random.randn(2) sub = np.random.choice(X, n) stupid_sum=np.array([0.0,0.0]) for data_point in sub: stupid_sum = stupid_sum+ grad_log_density(theta[0], theta[1],data_point) grad = grad_log_prior(theta) + (N/n)*stupid_sum grad = grad*epsilon_t/2 theta = theta+grad+noise samples[t] = theta return np.array(samples[::thinning]) # b=2.31 # a = 0.01584 # epsilon_t = a*(b+t)**(-0.55) # epsilon_t = np.max(min_epsilon,epsilon_t) def evSGLD(grad_log_density,grad_log_prior, X,n,epsilons, theta=None,dim=2): if theta is None: theta=np.random.randn(dim) N = X.shape[0] X = np.random.permutation(X) chain_size = len(epsilons) samples = np.zeros((chain_size,dim)) for t in range(chain_size): noise = np.sqrt(epsilons[t])*np.random.randn(dim) sub = np.random.choice(X, n) stupid_sum = np.sum(grad_log_density(theta[0],theta[1],sub),axis=0) grad = grad_log_prior(theta) + (N/n)*stupid_sum grad = grad*epsilons[t]/2 theta = theta+grad+noise samples[t] = theta return np.array(samples)