plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
OrangeOwlSolutions/Optimization-master
MultistartOptimizer.m
.m
Optimization-master/MultiStart/MultistartOptimizer.m
5,599
utf_8
fab1b5344dfe90fe389808aee837a3f8
% --- costfunctional Cost functional to be optimized function [GlobalOptimum OptFuncVal] = MultistartOptimizer(minvalues, maxvalues, N, gammap, maxiter, maxiterlocal, options, Constrained, costfunctional) % --- N Number of sampling points introduced at each iteration % --- gammap Percentage of the sampling points excluded at each iteration % --- maxiter Maximum number of allowed multistart iterations % --- maxiter Maximum number of allowed iterations for local optimization Mopt = length(minvalues); % --- Number of optimization variables SamplingPoints = cell(Mopt); % --- Current population of sampling points LocalMinima = cell(Mopt); % --- Found local minima Func_val = []; % --- Functional values corresponding to the sampling points Func_val_min = []; % --- Functional values corresponding to the local minima flag = 0; % --- Exit flag iter = 1; % --- Iteration counter FoundMinima = 0; % --- Number of local minima temp = zeros(1, Mopt); % --- Temporary array % --- Calculation of the prefactor needed for the computation of the critical distance rho = 5; % --- Relevant to the calculation of the critical distance prefactor_rk = 1; for k=1:Mopt prefactor_rk = prefactor_rk * (maxvalues(k) - minvalues(k)); end prefactor_rk = (1/sqrt(pi)) * (gamma(1+Mopt/2) * prefactor_rk * rho)^(1/Mopt); options.MaxIter = maxiterlocal; %%%%%%%%%%%%%% % ITERATIONS % %%%%%%%%%%%%%% while ((flag == 0) && iter <= maxiter) % --- Introduce sampling points uniformly distributed in the search space for k=1:Mopt SamplingPoints{k} = [SamplingPoints{k} (maxvalues(k)-minvalues(k))*rand(1,N)+minvalues(k)]; end % --- Calculate the functional values corresponding to the sampling points Func_val = zeros(1, length(SamplingPoints{1})); for p=1:length(SamplingPoints{1}), for q=1:Mopt, temp(q) = SamplingPoints{q}(p); end Func_val(p) = costfunctional(temp); end % --- Calculate the critical distance rk = prefactor_rk * (log(iter*N)/(iter*N))^(1/Mopt); % --- Sorts the functional values and the sampling points accordingly [Func_val,indices]=sort(Func_val); for k=1:Mopt SamplingPoints{k} = SamplingPoints{k}(indices); end % --- Determines the sampling points whose functional values are lower than gammap times the maximum functional value count=1; while (Func_val(count) <= gammap*Func_val(length(Func_val))); count=count+1; end count=count-1; % --- Explores all the current members of the population for pp=1:count, % --- Calculates the distance of the pp-th sampling point to all the other sampling points distance = zeros(size(SamplingPoints{1})); for k=1:Mopt distance = distance + (SamplingPoints{k}(pp) - SamplingPoints{k}).^2; end distance = sqrt(distance); % --- Filters the sampling points for which there exist at least one other sampling point spaced for less than rk and having a lower functional value indices = find((distance <= rk) & (Func_val < Func_val(pp))); if (sum(indices) == 0) for q=1:Mopt, temp(q) = SamplingPoints{q}(pp); end if (Constrained == 1) [xstar,Func_val_opt]=fmincon(costfunctional,temp,[],[],[],[],minvalues,maxvalues,[],options); else [xstar,Func_val_opt]=fminunc(costfunctional,temp,options); end % --- If the iteration is the first one, then adds the found minimum if (iter==1) for q=1:Mopt, LocalMinima{q} = [LocalMinima{q} xstar(q)]; end Func_val_min=[Func_val_min Func_val_opt]; % --- Updates the number of found local minima FoundMinima = FoundMinima + 1; else % --- Here iter > 1 % --- Calculates the distance between the found minimum and all the other minima distance = 0.; for k=1:Mopt distance = distance + (SamplingPoints{k}(pp) - SamplingPoints{k}).^2; end distance = sqrt(distance); % --- If the minimum has not been previously found, it is added to the local minima pool if ((sum(find(distance == 0 ))==0)) for q=1:Mopt, LocalMinima{q}(pp) = [LocalMinima{q}(pp) xstar(q)]; end Func_val_min=[Func_val_min Func_val_opt]; % --- Updates the number of found local minima FoundMinima = FoundMinima + 1; end end end end iter=iter + 1; % --- Exit condition ExpectedCoveredUnknownSpace = (count - FoundMinima - 1) * (count + FoundMinima) / (count * (count - 1)); ExpectedNumberLocalMinima = FoundMinima * (count - 1) / (count - FoundMinima - 2); flag = (ExpectedNumberLocalMinima < FoundMinima + 0.499) && ExpectedCoveredUnknownSpace >= 0.995; end % --- Retrieving the global optimizer [OptFuncVal, index] = min(Func_val_min); for q=1:Mopt, GlobalOptimum(q) = SamplingPoints{q}(index); end
github
kerkphil/CSL_unbalanced_growth-master
LinApp_FindSS.m
.m
CSL_unbalanced_growth-master/MATLAB code/LinApp_FindSS.m
1,699
utf_8
813e3554b8851b881ecedc0dc6bb89b6
function XYbar = LinApp_FindSS(funcname,param,guessXY,Zbar,nx,ny) % Version 1.0, written by Kerk Phillips, April 2014 % % Finds the steady state for a DSGE model numerically % % This function takes the following inputs: % funcname - is the name of the function which generates a column vector % from ny+nx dynamic equations. % The ny eqyations to be linearized into the form below in the first % ny rows. % A X(t) + B X(t-1) + C Y(t) + D Z(t) = 0 % The function must be written so as to evaluate to zero for all rows % in the steady state. % param is a vector of parameter values to be passed to funcname. % guessXY - guess for the steady state vslues of X and Y % Zbar - 1-by-nz vector of Z steady state values % nx - number of X variables % ny - number of Y variables % % This function outputs the following: % XYbar 1-by-(nx+ny) vector of X and Y steady state values, with the X % values in positions 1 - nx and an the Y values in nx+1 - nx+ny. % % Copyright: K. Phillips. Feel free to copy, modify and use at your own % risk. However, you are not allowed to sell this software or otherwise % impinge on its free distribution. % create anonlymous function f = @(XYbar) steady(XYbar, Zbar, funcname, param, nx, ny); % set options for solver options = optimoptions(@fsolve,'Display','iter',... 'MaxIterations',100000,... 'MaxFunctionEvaluations',1000000,... 'FunctionTolerance',1.0e-5); % use fsolve XYbar = fsolve(f,guessXY,options); end function out = steady(XYbar, Zbar, funcname, param, nx, ny) Xbar = XYbar(1:nx); Ybar = XYbar(1+nx:nx+ny); in = [Xbar; Xbar; Xbar; Ybar; Ybar; Zbar; Zbar]; out = funcname(in,param); end
github
cgershen/prog-master
The_Game_of_Life_Resendiz_Georgina.m
.m
prog-master/tareas/20180816-GameOfLife/The_Game_of_Life_Resendiz_Georgina.m
51,190
utf_8
e1e6669e4d81fc81026c8d73789ce858
function varargout = The_Game_of_Life_Resendiz_Georgina(varargin) % The_Game_of_Life_Resendiz_Georgina MATLAB code for The_Game_of_Life_Resendiz_Georgina.fig % The_Game_of_Life_Resendiz_Georgina, by itself, creates a new The_Game_of_Life_Resendiz_Georgina or raises the existing % singleton*. % % H = The_Game_of_Life_Resendiz_Georgina returns the handle to a new The_Game_of_Life_Resendiz_Georgina or the handle to % the existing singleton*. % % The_Game_of_Life_Resendiz_Georgina('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in The_Game_of_Life_Resendiz_Georgina.M with the given input arguments. % % The_Game_of_Life_Resendiz_Georgina('Property','Value',...) creates a new The_Game_of_Life_Resendiz_Georgina or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before The_Game_of_Life_Resendiz_Georgina_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to The_Game_of_Life_Resendiz_Georgina_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help The_Game_of_Life_Resendiz_Georgina % Last Modified by GUIDE v2.5 15-Aug-2018 21:22:10 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @The_Game_of_Life_Resendiz_Georgina_OpeningFcn, ... 'gui_OutputFcn', @The_Game_of_Life_Resendiz_Georgina_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before The_Game_of_Life_Resendiz_Georgina is made visible. function The_Game_of_Life_Resendiz_Georgina_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to The_Game_of_Life_Resendiz_Georgina (see VARARGIN) % Choose default command line output for The_Game_of_Life_Resendiz_Georgina handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes The_Game_of_Life_Resendiz_Georgina wait for user response (see UIRESUME) % uiwait(handles.figure1); %Variables condition=1; %condition for generations handles.condition=condition; guidata(hObject, handles); condition1=0; %condition1 for function draw handles.condition=condition1; guidata(hObject, handles); j=100; %Number of generations handles.j=j; guidata(hObject, handles); k=1; %Total Number of generations handles.k=k; guidata(hObject, handles); image1=[];%To show the image in the matrix handles.image1=image1; guidata(hObject, handles); A=[]; %Actual Matrix handles.A=A; guidata(hObject, handles); B=[]; %Future Matrix handles.B=B; guidata(hObject, handles); r=10; %Size of matrix handles.r=r; guidata(hObject, handles); speed=20; %Speed handles.speed=speed; guidata(hObject, handles); sigma1=2; %Sigma 1 handles.sigma1=sigma1; guidata(hObject, handles); sigma2=3; %Sigma 2 handles.sigma2=sigma2; guidata(hObject, handles); sigma3=3; %Sigma 3 handles.sigma3=sigma3; guidata(hObject, handles); cell_status_1=0; %Cell Status 1 handles.cell_status_1=cell_status_1; guidata(hObject, handles); cell_status_2=1; %Cell Status 2 handles.cell_status_2=cell_status_2; guidata(hObject, handles); cell_status_3=1; %Cell Status 3 handles.cell_status_3=cell_status_3; guidata(hObject, handles); cell_status_4=0; %Cell Status 5 handles.cell_status_4=cell_status_4; guidata(hObject, handles); density=0.5; %Density handles.density=density; guidata(hObject, handles); %Initial random matrix handles.r=str2double(get(handles.size_of_matrix_edit,'String')); %Obtein size of matrix U=rand(handles.r,handles.r); %Obtein random matrix, with values between 0 and 1 p=0.5;%Density handles.A=(U<p); %Obtein the Matrix of only 0's and 1's axes(handles.matrix_axes); handles.image1=imshow(handles.A); %Show matrix A in matrix_axes set(handles.num_living_cells_edit,'String',num2str(sum(sum(handles.A))));% Sum of all living cells (1's in matrix A) handles.B=handles.A; % Copy matrix 'A' to matrix 'B' guidata(hObject, handles); % --- Outputs from this function are returned to the command line. function varargout = The_Game_of_Life_Resendiz_Georgina_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in start_stop_togglebutton. function start_stop_togglebutton_Callback(hObject, eventdata, handles) % hObject handle to start_stop_togglebutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) sum_neighbors=0; total_generations=handles.j; handles.k=0; if strcmp(get(handles.start_stop_togglebutton, 'String'),'START'); % Togglebutton "START" comparison set(handles.start_stop_togglebutton,'String','STOP'); % Change string to "STOP" %Enable-off elements set(handles.size_of_matrix_edit,'Enable','off'); set(handles.num_generations_edit,'Enable','off'); set(handles.random_matrix_togglebutton,'Enable','off'); set(handles.clear_matrix_pushbutton,'Enable','off'); set(handles.draw_living_cells_togglebutton,'Enable','off'); set(handles.pattern_templates_menu,'Enable','off'); set(handles.recognize_pushbutton,'Enable','off'); set(handles.density_slider,'Enable','off'); set(handles.change_rules_togglebutton,'Enable','off'); set(handles.num_generations_edit,'String',0); pause(0.5); guidata(hObject, handles); while handles.k<=total_generations && get(handles.start_stop_togglebutton,'Value')==1 for x=0:handles.r-1 for y=0:handles.r-1 %Sum of all neighbors sum_neighbors=handles.A(rem(x-1+handles.r,handles.r)+1,rem(y-1+handles.r,handles.r)+1)+handles.A(rem(x-1+handles.r,handles.r)+1,rem(y+handles.r,handles.r)+1)+handles.A(rem(x-1+handles.r,handles.r)+1,rem(y+1+handles.r,handles.r)+1)+handles.A(rem(x+handles.r,handles.r)+1,rem(y-1+handles.r,handles.r)+1)+handles.A(rem(x+handles.r,handles.r)+1,rem(y+1+handles.r,handles.r)+1)+handles.A(rem(x+1+handles.r,handles.r)+1,rem(y-1+handles.r,handles.r)+1)+handles.A(rem(x+1+handles.r,handles.r)+1,rem(y+handles.r,handles.r)+1)+handles.A(rem(x+1+handles.r,handles.r)+1,rem(y+1+handles.r,handles.r)+1); if handles.A(x+1,y+1)==1 %Living cell if sum_neighbors<handles.sigma1 || sum_neighbors>handles.sigma2 % 2 or 3 living cells around handles.B(x+1,y+1)=handles.cell_status_1; % Cell dies else handles.B(x+1,y+1)=handles.cell_status_2; % Cell remains living end else %Dead Cell if sum_neighbors==handles.sigma3 % 3 living cells handles.B(x+1,y+1)=handles.cell_status_3; % Cell lives else handles.B(x+1,y+1)=handles.cell_status_4; % Cell remains dead end end guidata(hObject, handles); end end handles.A=handles.B; %Copy matrix B to A guidata(hObject, handles); %Update handles structure handles.image1=imshow(handles.A); guidata(hObject, handles); %Update handles structure set(handles.num_living_cells_edit,'String',num2str(sum(sum(handles.A)))); set(handles.num_generations_edit,'String',handles.k); guidata(hObject, handles); %Update handles structure refreshdata; drawnow; pause(1/get(handles.speed_slider,'Value')); %Speed between 1s-0.00002s handles.k=handles.k+1; %Increase by 1 to reach the total number of generations guidata(hObject, handles); end if handles.k==total_generations+1 set(handles.start_stop_togglebutton,'String','START');%Change string to "START" %Enable-on elements set(handles.start_stop_togglebutton,'Value',0); set(handles.size_of_matrix_edit,'Enable','on'); set(handles.num_generations_edit,'Enable','on'); set(handles.random_matrix_togglebutton,'Enable','on'); set(handles.clear_matrix_pushbutton,'Enable','on'); set(handles.draw_living_cells_togglebutton,'Enable','on'); set(handles.speed_slider,'Enable','on'); handles.k=1; guidata(hObject, handles); end else set(handles.start_stop_togglebutton,'String','START'); %Change string to "START" guidata(hObject, handles); %Enable-on elements set(handles.num_generations_edit,'String',handles.j); set(handles.size_of_matrix_edit,'Enable','on'); set(handles.num_generations_edit,'Enable','on'); set(handles.random_matrix_togglebutton,'Enable','on'); set(handles.clear_matrix_pushbutton,'Enable','on'); set(handles.draw_living_cells_togglebutton,'Enable','on'); set(handles.pattern_templates_menu,'Enable','on'); set(handles.recognize_pushbutton,'Enable','on'); set(handles.density_slider,'Enable','on'); set(handles.change_rules_togglebutton,'Enable','on'); guidata(hObject, handles); end % --- Executes on slider movement. function speed_slider_Callback(hObject, eventdata, handles) % hObject handle to speed_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) s=get(handles.speed_slider,'Value'); %Obtein value of speed_slider handles.speed=1/s; %Convert obteined value between 1 - 100, to speed 1 to 2x10-5 set(handles.text9,'String',handles.speed); guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function speed_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to speed_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on button press in random_matrix_togglebutton. function random_matrix_togglebutton_Callback(hObject, eventdata, handles) % hObject handle to random_matrix_togglebutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if strcmp(get(handles.random_matrix_togglebutton, 'String'),'Random Matrix');%Togglebutton, String Random Matrix set(handles.random_matrix_togglebutton,'String','Done'); set(handles.density_slider,'Enable','on'); set(handles.clear_matrix_pushbutton,'Enable','off'); set(handles.draw_living_cells_togglebutton,'Enable','off'); set(handles.pattern_templates_menu,'Enable','off'); %Generate Random Matrix while get(handles.random_matrix_togglebutton,'Value')==1 handles.r=str2double(get(handles.size_of_matrix_edit,'String')); %Obtein size of matrix U=rand(handles.r,handles.r); %Obtein random matrix, with values between 0 and 1 handles.A=(U<=get(handles.density_slider,'Value')); %Obtein the Matrix of only 0's and 1's guidata(hObject, handles); handles.image1=imshow(handles.A); %Show matrix A in matrix_axes set(handles.num_living_cells_edit,'String',num2str(sum(sum(handles.A))));% Sum of all living cells (1's in matrix A) handles.B=handles.A; % Copy matrix 'A' to matrix 'B' guidata(hObject, handles); pause(2); end else set(handles.random_matrix_togglebutton,'String','Random Matrix');%Togglebutton, string "Random Matrix" set(handles.draw_living_cells_togglebutton,'Enable','on'); set(handles.clear_matrix_pushbutton,'Enable','on'); set(handles.density_slider,'Enable','off'); set(handles.pattern_templates_menu,'Enable','on'); end guidata(hObject, handles); % --- Executes on button press in clear_matrix_pushbutton. function clear_matrix_pushbutton_Callback(hObject, eventdata, handles) % hObject handle to clear_matrix_pushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) guidata(hObject, handles); %Clear matrix (zeros matrix) handles.r=str2double(get(handles.size_of_matrix_edit,'String')); %Obtein size of matrix handles.A=zeros(handles.r,handles.r); %Obtein zeros matrix handles.image1=imshow(handles.A); %Show matrix A in matrix_axes set(handles.num_living_cells_edit,'String',num2str(sum(sum(handles.A))));% Sum of all living cells (1's in matrix A) handles.B=handles.A;%Copy matrix 'A' to matrix 'B' guidata(hObject, handles); % --- Executes on button press in draw_living_cells_togglebutton. function draw_living_cells_togglebutton_Callback(hObject, eventdata, handles) % hObject handle to draw_living_cells_togglebutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Draw Living Cells guidata(hObject, handles); imshow(handles.B); if strcmp(get(handles.draw_living_cells_togglebutton, 'String'),'Draw Living Cells'); %Togglebutton 'Draw Living Cells' set(handles.draw_living_cells_togglebutton,'String','Done'); set(handles.random_matrix_togglebutton,'Enable','off'); set(handles.clear_matrix_pushbutton,'Enable','off'); [x, y]=ginput(1); %To draw in the matrix x=round(x); y=round(y); handles.B(y,x)=1; guidata(hObject, handles); imshow(handles.B); handles.A=handles.B; guidata(hObject, handles); imshow(handles.A); set(handles.num_living_cells_edit,'String',num2str(sum(sum(handles.A))));% Sum of all living cells (1's in matrix A) else set(handles.draw_living_cells_togglebutton,'String','Draw Living Cells'); set(handles.random_matrix_togglebutton,'Enable','on'); set(handles.clear_matrix_pushbutton,'Enable','on'); end guidata(hObject, handles); function num_generations_edit_Callback(hObject, eventdata, handles) % hObject handle to num_generations_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of num_generations_edit as text % str2double(get(hObject,'String')) returns contents of num_generations_edit as a double %Number of Generations num_generations=get(handles.num_generations_edit,'String'); %Size Limits between 0 and 10000 (only positive integer numbers) if (str2double(num_generations)<0)||(str2double(num_generations)>10000)||(str2double(num_generations)~=round(str2double(num_generations)))||(isempty(str2num(num_generations))) %Limit to positive integers errordlg('Please type a positive integer number (<10000).','Error') set(handles.num_generations_edit,'String',handles.j); else handles.j=str2double(get(handles.num_generations_edit,'String'));%Set value of handles.num_generations_edit to handles.j end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function num_generations_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to num_generations_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function size_of_matrix_edit_Callback(hObject, eventdata, handles) % hObject handle to size_of_matrix_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of size_of_matrix_edit as text % str2double(get(hObject,'String')) returns contents of size_of_matrix_edit as a double size_of_matrix=get(handles.size_of_matrix_edit,'String'); %Size Limits between 1 and 10000 (only positive integer numbers) if (str2double(size_of_matrix)<1)||(str2double(size_of_matrix)>10000)||(str2double(size_of_matrix)~=round(str2double(size_of_matrix)))||(isempty(str2num(size_of_matrix))) %Limit to positive integers errordlg('Please type a positive integer number (>0 && <=10000).','Error') set(handles.size_of_matrix_edit,'String',handles.r); else %Show the random matrix with a valid size handles.r=str2double(size_of_matrix); %Obtein size of matrix U=rand(handles.r,handles.r); %Obtein random matrix, with values between 0 and 1 p=0.5;%Density handles.A=(U<p); %Obtein the Matrix of only 0's and 1's axes(handles.matrix_axes); %Use matrix_axes to show matrix handles.image1=imshow(handles.A); %Show matrix A set(handles.num_living_cells_edit,'String',num2str(sum(sum(handles.A))));% Sum of all living cells (1's in matrix A) handles.B=handles.A; % Copy matrix 'A' to matrix 'B' end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function size_of_matrix_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to size_of_matrix_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in generate_graph_pushbutton. function generate_graph_pushbutton_Callback(hObject, eventdata, handles) % hObject handle to generate_graph_pushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in exit_pushbutton. function exit_pushbutton_Callback(hObject, eventdata, handles) % hObject handle to exit_pushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) answer=questdlg('Do you want to quit "The Game of Life"?','The Game of Life'); %Exit the game if strcmp(answer,'Yes') %Clear the command window clc; %Clear the variables clearStr='clear all'; evalin('base',clearStr); %Delete the figure delete(handles.figure1); end function num_living_cells_edit_Callback(hObject, eventdata, handles) % hObject handle to num_living_cells_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of num_living_cells_edit as text % str2double(get(hObject,'String')) returns contents of num_living_cells_edit as a double % --- Executes during object creation, after setting all properties. function num_living_cells_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to num_living_cells_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % % --- Executes on button press in save_changes_pushbutton. % function save_changes_pushbutton_Callback(hObject, eventdata, handles) % % hObject handle to save_changes_pushbutton (see GCBO) % % eventdata reserved - to be defined in a future version of MATLAB % % handles structure with handles and user data (see GUIDATA) % % % % --- Executes on button press in cancel_pushbutton. % function cancel_pushbutton_Callback(hObject, eventdata, handles) % % hObject handle to cancel_pushbutton (see GCBO) % % eventdata reserved - to be defined in a future version of MATLAB % % handles structure with handles and user data (see GUIDATA) % --- Executes on selection change in pattern_templates_menu. function pattern_templates_menu_Callback(hObject, eventdata, handles) % hObject handle to pattern_templates_menu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns pattern_templates_menu contents as cell array % contents{get(hObject,'Value')} returns selected item from pattern_templates_menu %Pattern Templates set(handles.size_of_matrix_edit,'Enable','off'); guidata(hObject, handles); menu=get(hObject,'String'); a=get(hObject,'Value'); option=menu(a); switch cell2mat(option) case '1. Still Lifes' handles.r=15; set(handles.size_of_matrix_edit,'String','15'); handles.j=str2double(get(handles.num_generations_edit,'String')); guidata(hObject, handles); handles.A=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,1,1,0,0,0,1,1,0,0,0,1,1,0,0; 0,1,1,0,0,1,0,0,1,0,0,1,0,1,0; 0,0,0,0,0,0,1,1,0,0,0,0,1,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,1,1,0,0,0,0,0,0,1,0,0; 0,0,0,1,0,0,1,0,0,0,0,1,0,1,0; 0,0,0,0,1,0,1,0,0,0,0,0,1,0,0; 0,0,0,0,0,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; case '2. Oscillators' handles.r=30; set(handles.size_of_matrix_edit,'String','30'); guidata(hObject, handles); handles.A=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; case '3. Spaceships' handles.r=30; set(handles.size_of_matrix_edit,'String','30'); guidata(hObject, handles); handles.A=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; case '4. Methuselahs' handles.r=30; set(handles.size_of_matrix_edit,'String','30'); guidata(hObject, handles); handles.A=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; case '5. Guns' handles.r=40; set(handles.size_of_matrix_edit,'String','40'); guidata(hObject, handles); handles.A=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0; 0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; case '6. Pattern for recognizing' handles.r=4; set(handles.size_of_matrix_edit,'String','4'); handles.j=str2double(get(handles.num_generations_edit,'String')); guidata(hObject, handles); handles.A=[0,0,0,0; 0,1,1,0; 0,1,1,0 0,0,0,0]; end axes(handles.matrix_axes); handles.image1=imshow(handles.A); %Show matrix A in matrix_axes set(handles.num_living_cells_edit,'String',num2str(sum(sum(handles.A))));% Sum of all living cells (1's in matrix A) handles.B=handles.A; % Copy matrix 'A' to matrix 'B' guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function pattern_templates_menu_CreateFcn(hObject, eventdata, handles) % hObject handle to pattern_templates_menu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sigma1_edit_Callback(hObject, eventdata, handles) % hObject handle to sigma1_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of sigma1_edit as text % str2double(get(hObject,'String')) returns contents of sigma1_edit as a double %Value sigma 1 sigma1=get(handles.sigma1_edit,'String'); if (str2double(sigma1)<0)||(str2double(sigma1)>8)||(str2double(sigma1)~=round(str2double(sigma1)))||(isempty(str2num(sigma1))) %Limit to positive integers errordlg('Please type a positive integer number (<=8).','Error') set(handles.sigma1_edit,'String',2); else handles.sigma1=str2double(get(handles.sigma1_edit,'String')); end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function sigma1_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to sigma1_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sigma2_edit_Callback(hObject, eventdata, handles) % hObject handle to sigma2_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of sigma2_edit as text %Value sigma 2 sigma2=get(handles.sigma2_edit,'String'); if (str2double(sigma2)<0)||(str2double(sigma2)>8)||(str2double(sigma2)~=round(str2double(sigma2)))||(isempty(str2num(sigma2))) %Limit to positive integers errordlg('Please type a positive integer number (<=8).','Error') set(handles.sigma2_edit,'String',3); else handles.sigma2=str2double(get(handles.sigma2_edit,'String')); end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function sigma2_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to sigma2_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sigma3_edit_Callback(hObject, eventdata, handles) % hObject handle to sigma3_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of sigma3_edit as text % str2double(get(hObject,'String')) returns contents of sigma3_edit as a double %Value sigma3 sigma3=get(handles.sigma3_edit,'String'); if (str2double(sigma3)<0)||(str2double(sigma3)>8)||(str2double(sigma3)~=round(str2double(sigma3)))||(isempty(str2num(sigma3))) %Limit to positive integers errordlg('Please type a positive integer number (<=8).','Error') set(handles.sigma3_edit,'String',3); else handles.sigma3=str2double(get(handles.sigma3_edit,'String')); end guidata(hObject, handles); %Actualizar valores A y B % --- Executes during object creation, after setting all properties. function sigma3_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to sigma3_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in change_rules_togglebutton. function change_rules_togglebutton_Callback(hObject, eventdata, handles) % hObject handle to change_rules_togglebutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if strcmp(get(handles.change_rules_togglebutton, 'String'),'Change Rules'); %Togglebutton string "Change Rules" set(handles.change_rules_togglebutton,'String','Done');%Change String to "Done" %Enable-on elements set(handles.sigma1_edit,'Enable','on'); set(handles.sigma2_edit,'Enable','on'); set(handles.sigma3_edit,'Enable','on'); set(handles.cell_status_1_edit,'Enable','on'); set(handles.cell_status_2_edit,'Enable','on'); else set(handles.change_rules_togglebutton,'String','Change Rules');%Change String to "Change Rules" %Enable-off elements set(handles.sigma1_edit,'Enable','off'); set(handles.sigma2_edit,'Enable','off'); set(handles.sigma3_edit,'Enable','off'); set(handles.cell_status_1_edit,'Enable','off'); set(handles.cell_status_2_edit,'Enable','off'); end guidata(hObject, handles); function cell_status_1_edit_Callback(hObject, eventdata, handles) % hObject handle to cell_status_1_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of cell_status_1_edit as text % str2double(get(hObject,'String')) returns contents of cell_status_1_edit as a double %Cell status 1 cell_status_1=get(handles.cell_status_1_edit,'String'); if (str2double(cell_status_1)<0)||(str2double(cell_status_1)>1)||(str2double(cell_status_1)~=round(str2double(cell_status_1)))||(isempty(str2num(cell_status_1))) %Limit to positive integers errordlg('Please type only 0 (Cell dies) or 1 (Cell lives).','Error') set(handles.cell_status_1_edit,'String',0); handles.cell_status_1==0; else handles.cell_status_1=str2double(get(handles.cell_status_1_edit,'String')); if handles.cell_status_1==0 set(handles.cell_status_1_text,'String','Cell dies'); handles.cell_status_2=1; else set(handles.cell_status_1_text,'String','Cell lives'); handles.cell_status_2=0; end end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function cell_status_1_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to cell_status_1_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function cell_status_2_edit_Callback(hObject, eventdata, handles) % hObject handle to cell_status_2_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of cell_status_2_edit as text % str2double(get(hObject,'String')) returns contents of cell_status_2_edit as a double %Cell status 2 cell_status_2=get(handles.cell_status_2_edit,'String'); if (str2double(cell_status_2)<0)||(str2double(cell_status_2)>1)||(str2double(cell_status_2)~=round(str2double(cell_status_2)))||(isempty(str2num(cell_status_2))) %Limit to positive integers errordlg('Please type only 0 (Cell dies) or 1 (Cell lives).','Error') set(handles.cell_status_2_edit,'String',1); handles.cell_status_3==1; else handles.cell_status_3=str2double(get(handles.cell_status_2_edit,'String')); if handles.cell_status_3==0 set(handles.cell_status_2_text,'String','Cell dies'); handles.cell_status_4=1; else set(handles.cell_status_2_text,'String','Cell lives'); handles.cell_status_4=0; end end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function cell_status_2_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to cell_status_2_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function density_slider_Callback(hObject, eventdata, handles) % hObject handle to density_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % set(handles.density_slider,'Enable','off'); d=get(handles.density_slider,'Value'); %Obtein value of density_slider handles.density=d; set(handles.density_slider_text,'String',handles.density); guidata(hObject, handles); guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function density_slider_CreateFcn(hObject, eventdata, handles) % hObject handle to density_slider (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function still_lifes_edit_Callback(hObject, eventdata, handles) % hObject handle to still_lifes_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of still_lifes_edit as text % str2double(get(hObject,'String')) returns contents of still_lifes_edit as a double % --- Executes during object creation, after setting all properties. function still_lifes_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to still_lifes_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function oscillators_edit_Callback(hObject, eventdata, handles) % hObject handle to oscillators_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of oscillators_edit as text % str2double(get(hObject,'String')) returns contents of oscillators_edit as a double % --- Executes during object creation, after setting all properties. function oscillators_edit_CreateFcn(hObject, eventdata, handles) % hObject handle to oscillators_edit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in recognize_pushbutton. function recognize_pushbutton_Callback(hObject, eventdata, handles) % hObject handle to recognize_pushbutton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Recognition Still Lifes Patter Algorithm sum_neighbors=0; sum_still_life_pattern=0; %Count until 4 times, 3 neighbors num_still_life_patterns=0; for x=0:handles.r-1 for y=0:handles.r-1 %Sum of all neighbors sum_neighbors=handles.A(rem(x-1+handles.r,handles.r)+1,rem(y-1+handles.r,handles.r)+1)+handles.A(rem(x-1+handles.r,handles.r)+1,rem(y+handles.r,handles.r)+1)+handles.A(rem(x-1+handles.r,handles.r)+1,rem(y+1+handles.r,handles.r)+1)+handles.A(rem(x+handles.r,handles.r)+1,rem(y-1+handles.r,handles.r)+1)+handles.A(rem(x+handles.r,handles.r)+1,rem(y+1+handles.r,handles.r)+1)+handles.A(rem(x+1+handles.r,handles.r)+1,rem(y-1+handles.r,handles.r)+1)+handles.A(rem(x+1+handles.r,handles.r)+1,rem(y+handles.r,handles.r)+1)+handles.A(rem(x+1+handles.r,handles.r)+1,rem(y+1+handles.r,handles.r)+1); disp(sum_neighbors); if sum_neighbors==3 sum_still_life_pattern=sum_still_life_pattern+1; if sum_still_life_pattern==4; num_still_life_patterns=num_still_life_patterns+1; set(handles.still_lifes_edit,'String',num_still_life_patterns); guidata(hObject, handles); end end end end
github
fxie2/Channel_DNS-master
solveup.m
.m
Channel_DNS-master/DisMethod/SteadyWall/Matlab/solveup.m
1,914
utf_8
2c3b967830e026bcabc34bf4346e9695
global u, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh; function [u, v, w, p, pgx, pgz] = solveup(u, v, w, p, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh) [du, dv, dw] = getvel(u, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); dp = getpre(du, dv, dw, p, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); [u, v, w, p, pgx, pgz] = updateup(du, dv, dw, dp, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); end function [du, dv, dw] = getvel(u, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh) du = getu(u, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); dv = getv(du, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); dw = getw(du, dv, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); [du, dv, dw] = finish_vel(du, dv, dw, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); du = du + u; dv = dv + v; dw = dw + w; end function du = getu(u, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh) r1 = form_r1(u, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); du = solve_du(u, v, w, r1, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); end function dv = getv(du, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh) r2 = form_r2(du, v, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); dv = solve_dv(du, v, w, r2, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); end function dw = getw(du, dv, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh) r3 = form_r3(du, dv, w, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); dw = solve_dw(du, dv, w, r3, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh); end function [du, dv, dw] = finish_vel(du, dv, dw, pgx, pgz, dx, dy, dz, h, dy2dy, dy2h, dydy, dyh) %finish dv for k = 1:n3 km = mod(k-2, n3) + 1; kp = mod(k, n3) + 1; for j = 2:n2 for i = 1:n1 v1 = (v(i, j, km) + v(i, j, k)) / 2; v2 = (v(i, j, kp) + v(i, j, k)) / 2; w1 = (dw(i, j+1, k) * dy(
github
fxie2/Channel_DNS-master
ode2_solve.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/ode2_solve.m
3,485
utf_8
07235bfa79d490e3b682cf11f7b05046
%% Channel DNS Subfunction - ode2_solve %% Purpose % Solve the 2nd order diffential equation in the form: % f"(y) - k*f(y) = s(y) , y in [-1, 1] % with first kind boundary condition: % f(-1) = A, f(1) = B % or with second kind boundary condition: % f'(-1) = A, f'(1) = B %% Method % Use Chebyshev transform to solve the equation. % Let % % f(y) = sum fp*Tp(y) , p=0:P % s(y) = sum sp*Tp(y) , p=0:P % % The main equation can be written as % % k*c_p-2 * f_p-2 k * e_p+2 k * e_p+4 * f_p+2 % ---------------- - (1 + ------------ )*f_p + ------------------- % 4*p*(p-1) 2*(p^2-1) 4*p*(p+1) % % c_p-2 * s_p-2 e_p+2 * s_p e_p+4 * s_p+2 % = -( ---------------- - ------------- + --------------- ) % 4*p*(p-1) 2*(p^2-1) 4*p*(p+1) % (by Gottlib & Orszag, 1977) % ( e_p = 1 for p<=P, e_p = 0 for p>P) % and for boundary conditions % 1st kind: % sum (-1)^p * fp = A , p=0:P % sum fp = B , p=0:P % 2nd kind: % sum (-1)^p * fp' = A , p=0:P % sum fp' = B , p=0:P % cp*fp' = 2 * sum k*fk , k=p+1:P %% Parameters % Input parameters: % k ------------------------- the k factor % s ------------------------- the right term % boundary_type ------------- 1 for 1st, 2 for 2nd. % boundary_conditions ------- [A, B] 2 boundary values for (-1, +1) % input_type ---------------- 's' for spectral, 'p' for physical % output_type --------------- 's' for spectral, 'p' for physical % Output parameter: % f ------------------------- the solution %% Author % Written by Luohao Wang on 2015-9-10 % Contact : [email protected] %% Code function f = ode2_solve(k, s, boundary_type, boundary_conditons, input_type, output_type) P = length(s) - 1; if input_type == 'p' sp = FCT(s, 1); else sp = s; end %form the index array i = zeros(5*P - 3, 1); p = zeros(5*P - 3, 1); v = zeros(5*P - 3, 1); n = 1; for iter = 1:P-3 i(n:n+2) = iter*ones(1,3); p(n:n+2) = [0,2,4] + iter*ones(1,3); v(n) = k / (4*(iter + 1)*iter); v(n+1) = -(1 + k / (2*((iter+1)^2 - 1))); v(n+2) = k / (4*(iter+1)*(iter+2)); n = n + 3; end v(1) = k / 4; i(n:n+3) = [P-2,P-2,P-1,P-1]; p(n:n+3) = [P-2,P,P-1,P+1]; v(n) = k/(4*(P-1)*(P-2)); v(n+1) = -1; v(n+2) = k/(4*P*(P-1)); v(n+3) = -1; i(3*P-4:4*P-4) = P*ones(1,P+1); i(4*P-3:5*P-3) = (P+1)*ones(1,P+1); p(3*P-4:4*P-4) = [1:P+1]; p(4*P-3:5*P-3) = [1:P+1]; if boundary_type == 1 v(3*P-4:4*P-4) = (-1).^[0:P]; v(4*P-3:5*P-3) = ones(1,P+1); elseif boundary_type == 2 v(3*P-4:4*P-4) = -[0:P].^2.*(-1).^[0:P]; v(4*P-3:5*P-3) = [0:P].^2; else disp('boundary type error!'); end M = sparse(i,p,v); b = zeros(P+1,1); b(1) = -(sp(1)/4 - sp(3)/6 + sp(5)/24); for iter = 2:P-5 pp = iter + 1; b(iter) = -(sp(pp-2+1)/(4*pp*(pp-1)) - sp(pp+1)/(2*(pp^2 - 1)) + sp(pp+3)/(4*pp*(pp+1))); end b(P-4) = -(sp(P-4)/(4*(P-3)*(P-4)) - sp(P-2)/(2*((P-3)^2 - 1))); b(P-3) = -(sp(P-3)/(4*(P-2)*(P-3)) - sp(P-1)/(2*((P-2)^2 - 1))); b(P-2) = -sp(P-2)/(4*(P-1)*(P-2)); b(P-1) = -sp(P-1)/(4*(P-1)*P); b(P) = boundary_conditons(1); b(P+1) = boundary_conditons(2); if abs(k) <= eps() && boundary_type == 2 temp_ans = zeros(P+1,1); temp_ans(2:P+1) = M(2:P+1,2:P+1)\b(2:P+1); else temp_ans = M\b; end if output_type == 'p' f = FCT(temp_ans,-1); else f = temp_ans; end end
github
fxie2/Channel_DNS-master
getphi.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/getphi.m
198
utf_8
f204c79c0ab8c7d08407cc9142721436
%% Channel DNS Subfunction - getphi %% Purpose % Calculate the phi term %% Code function [phix, phiy, phiz, phit] = getphi(nx, nz, alpha, beta, Ax, kx,... cx, phi0x, Az, kz, cz, phi0z, t) end
github
fxie2/Channel_DNS-master
global_trans.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/global_trans.m
1,320
utf_8
223c90b63c4450c51f17f3d33ed1bcff
%% Channel DNS Subfunction - global_trans %% Purpose % Transform between physical space and spectral space %% Parameters % Input parameters: % u ------------------------ spectral or physical data % direction ---------------- 1 for p -> s, -1 for s -> p % Output parameter: % w ------------------------ physical or spectral result %% Author % Written by Luohao Wang on 2015-9-13 % Contact : [email protected] %% Code function w = global_trans(u, direction) [nx, ny, nz] = size(u); w = zeros(size(u)); if direction == 1 for iter_y = 1:ny temp = reshape(u(:,iter_y,:), nx, nz); temp = fft(temp); temp = fftshift(temp, 1); temp = fft(temp.'); temp = fftshift(temp, 1); w(:,iter_y,:) = temp.'; end for iter_x = 1:nx for iter_z = 1:nz w(iter_x,:,iter_z) = FCT(w(iter_x,:,iter_z), 1); end end elseif direction == -1 for iter_x = 1:nx for iter_z = 1:nz w(iter_x,:,iter_z) = FCT(u(iter_x,:,iter_z), -1); end end for iter_y = 1:ny temp = reshape(w(:,iter_y,:), nx, nz); temp = ifftshift(temp, 1); temp = ifft(temp).'; temp = ifftshift(temp,1); temp = ifft(temp).'; w(:,iter_y,:) = temp; end w = real(w); end end
github
fxie2/Channel_DNS-master
Gterm.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/Gterm.m
941
utf_8
bfcd84f4dde4cf3f98ff4c5762a5ecc6
%% Channel DNS Subfunction - Gterm %% Purpose % Calculate the G term in Pressure step %% Parameters % Input parameters: % fy -------------------------- lamb-y term % us, vs, ws ------------------ velocity term % alpha, beta ----------------- wave number % re -------------------------- reynold number % Output parameter % G --------------------------- G term %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function G = Gterm(fy, us, vs, ws, alpha, beta, re) rot_x = globe_partial(ws, 'y', 0) - globe_partial(vs, 'z', beta); rot_z = globe_partial(vs, 'x', alpha) - globe_partial(us, 'y', 0); G = fy; [nx, ~, nz] = size(fy); i = complex(0,1); parfor iter_x = 1:nx for iter_z = 1:nz G(iter_x,:,iter_z) = G(iter_x,:,iter_z) + (i*alpha*(iter_x-1-nx/2)*rot_z(iter_x,:,iter_z)... - i*beta*(iter_z-1-nz/2)*rot_x(iter_x,:,iter_z)) / re; end end end
github
fxie2/Channel_DNS-master
correct.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/correct.m
3,132
utf_8
8299ea20b644cf25bb88c8811cd0628b
%% Channel DNS Subfunction - Correct %% Purpose % Calculate the pressure and velocity correct field %% Method % The correct pressure field satisfies: % % laplace P_c+ = 0 % P_c+(y=1) = 1, P_c+(y=-1) = 0 (Selected) % % laplace P_c- = 0 % P_c-(y=1) = 0, P_c-(y=-1) = 1 % % And the correct velocity field satisfies: % % laplace V_c+ - V_c+ / niu*dt = 1/niu * P_c+ % V_c+(y = -1 and 1) = 0 (Selected) % % laplace V_c- - V_c- / niu*dt = 1/niu * P_c- % V_c-(y = -1 and 1) = 0 % % Considering the symmetry of P_c+ and P_c-, V_c+ and V_c-, % we only need to compute one pair of the equations. In this % function, the first pair of equations are solved. %% Parameters % Input parameters: % nx ----------------------- node number in x % ny ----------------------- node number in y % nz ----------------------- node number in z % alpha -------------------- wave number in x % beta --------------------- wave number in z % re ----------------------- reynold number % dt ----------------------- time space % Output parameters: % pc ----------------------- correct pressure field % uc ----------------------- correct u-velocity field % vc ----------------------- correct v-velocity field % wc ----------------------- correct w-velocity field % M ------------------------ correct matrix in physical % Note : All output parameters are in spectral space %% Author % Written by Luohao Wang on 2015-9-10 % Contact : [email protected] %% Code function [pc, uc, vc, wc, M] = correct(nx, ny, nz, alpha, beta, re, dt) pc = zeros(nx, ny, nz); uc = zeros(nx, ny, nz); vc = zeros(nx, ny, nz); wc = zeros(nx, ny, nz); M = zeros(nx, nz, 2, 2); s = zeros(1, ny); gamma0 = 11/6; %Pressure correct for iter_x = 0:nx-1 for iter_z = 0:nz-1 k = alpha^2*(iter_x - nx/2)^2 + beta^2*(iter_z - nz/2)^2; pc(iter_x+1,:,iter_z+1) = ode2_solve(k, s, 1, [0,1], 'p', 's'); end end %Velocity correct d_p_dx = globe_partial(pc, 'x', alpha); d_p_dy = globe_partial(pc, 'y', 0); d_p_dz = globe_partial(pc, 'z', beta); for iter_x = 0:nx-1 for iter_z = 0:nz-1 uc(iter_x+1,:,iter_z+1) = ode2_solve(gamma0/dt, d_p_dx(iter_x+1,:,iter_z+1), 1, [0,0], 's', 's'); vc(iter_x+1,:,iter_z+1) = ode2_solve(gamma0/dt, d_p_dy(iter_x+1,:,iter_z+1), 1, [0,0], 's', 's'); wc(iter_x+1,:,iter_z+1) = ode2_solve(gamma0/dt, d_p_dz(iter_x+1,:,iter_z+1), 1, [0,0], 's', 's'); end end uc = re * uc; vc = re * vc; wc = re * wc; %form correct matrix div_V = globe_partial(uc, 'x', alpha) + globe_partial(vc, 'y', 0) ... + globe_partial(wc, 'z', beta); div_V = y_trans(div_V, -1); for iter_x = 1:nx for iter_z = 1:nz M(iter_x, iter_z, 1, 1) = div_V(iter_x, 1, iter_z); M(iter_x, iter_z, 1, 2) = div_V(iter_x, ny, iter_z); M(iter_x, iter_z, 2, 1) = div_V(iter_x, ny, iter_z); M(iter_x, iter_z, 2, 2) = div_V(iter_x, 1, iter_z); end end %transform to physical space pc = y_trans(pc, -1); uc = y_trans(uc, -1); vc = y_trans(vc, -1); wc = y_trans(wc, -1); end
github
fxie2/Channel_DNS-master
partial.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/partial.m
1,054
utf_8
b51691935828ded1c7bd1f4b70a1543b
%% Channel DNS Subfunction - partial %% Purpose % Calculate the partial derivative in spectral space %% Parameters % Input parameters: % f ------------------------- input data in spectral space % direction ----------------- 'x' for d_dx, and so is others % parameter ----------------- alpha for 'x', beta for 'z', % nothing for 'y' %% Author % Written by Luohao Wang on 2015-9-11 % Contact : [email protected] %% Code function d = partial(f, direction, parameter) len = length(f); if direction == 'x' %now parameter == alpha d = complex(0,1)*parameter.*(-len/2:len/2-1).*f; elseif direction == 'z' %now parameter == beta d = complex(0,1)*parameter.*(-len/2:len/2-1).*f; elseif direction == 'y' %now parameter is useless, can be anything P = len - 1; [~,N] = size(f); if N == 1 f = transpose(f); end d = zeros(size(f)); d(1) = sum((1:2:P).*f((1:2:P)+1)); for p = 2:P d(p) = 2*sum((p:2:P).*f((p:2:P)+1)); end if N == 1 d = transpose(d); end end end
github
fxie2/Channel_DNS-master
globe_partial.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/globe_partial.m
1,021
utf_8
0a9e12cca4a4256d24243d88813e50f9
%% Channel DNS Subfunction - globe_partial %% Purpose % Calculate the parital derivative of the hole field %% Parameters % Input parameters: % f ------------------------- spectral data in 3-D % direction ----------------- 'x' for d_dx, and so on % parameter ----------------- alpha for 'x', beta for 'z', nothing for % 'y' %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function df = globe_partial(f, direction, parameter) [nx, ~, nz] = size(f); df = zeros(size(f)); if direction == 'x' for iter_x = 0:nx-1 df(iter_x+1,:,:) = complex(0,1).*parameter.*f(iter_x+1,:,:).*(iter_x - nx/2); end elseif direction == 'z' for iter_z = 0:nz-1 df(:,:,iter_z+1) = complex(0,1).*parameter.*f(:,:,iter_z+1).*(iter_z - nz/2); end elseif direction == 'y' for iter_x = 1:nx for iter_z = 1:nz df(iter_x,:,iter_z) = partial(f(iter_x,:,iter_z), 'y', 0); end end else disp('direction error'); end end
github
fxie2/Channel_DNS-master
initialize.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/initialize.m
762
utf_8
5201f72699bd17b93a2f32b35f527d85
%% Channel DNS Subfunction - initialize %% Purpose % Initialize the fluid field at the start time %% Parameters % nx, ny, nz ----------------------------- mesh size % alpha, beta ---------------------------- wave number in x and z %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function [p, u, v, w] = initialize(nx, ny, nz, alpha, dpdx) p = zeros(nx, ny, nz); u = zeros(nx, ny, nz); v = zeros(nx, ny, nz); w = zeros(nx, ny, nz); %Use theoretical Poiseuille flow field to initialize %Velocity initialize for iter_y = 1:ny y = cos((iter_y-1)*pi/(ny-1)); u(:, iter_y, :) = 1 - y^2; end %Pressure initialize for iter_x = 2:nx p(iter_x,:,:) = p(iter_x-1,:,:) - dpdx*2*pi/alpha/nx; end end
github
fxie2/Channel_DNS-master
lamb.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/lamb.m
824
utf_8
50918fd8bcceff06447f45d84c8ed52a
%% Channel DNS Subfunction - lamb %% Purpose % Calculate the lamb term F = V X w. %% Parameters % Input parameters: % us , vs, ws ------------------------- spectral velocity in 3-D % alpha, beta ------------------------- wave number in x and z % Output parameters: % fx, fy, fz -------------------------- convective term in spectral %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function [fx, fy, fz] = lamb(us, vs, ws, alpha, beta) rot_x = globe_partial(ws, 'y', 0) - globe_partial(vs, 'z', beta); rot_y = globe_partial(us, 'z', beta) - globe_partial(ws, 'x', alpha); rot_z = globe_partial(vs, 'x', alpha) - globe_partial(us, 'y', 0); fx = fcl(vs, rot_z) - fcl(ws, rot_y); fy = fcl(ws, rot_x) - fcl(us, rot_z); fz = fcl(us, rot_y) - fcl(vs, rot_x); end
github
fxie2/Channel_DNS-master
wallmove.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/wallmove.m
2,073
utf_8
b961d4f3acb681353aa595816e5ce1aa
%% Channel DNS Subfunction - wallmove %% Purpose % Generate physical shape of both upper and lower wall % with form: % % etau(x,z,t) = sum Ax_n*sin(kx_n*x - cx_n*t + phi0x_n) % sum Az_n*sin(kz_n*z - cz_n*t + phi0z_n), n = 1,2,... % % etad(x,z,t) has the same form. %% Parameters % Input parameters: % nx, nz ---------------------------- node number in x, z % alpha, beta ----------------------- wave number in x, z % Ax, Az ---------------------------- wave amptitude % kx, kz ---------------------------- wall wave number % cx, cz ---------------------------- wall wave phase spead % phi0x, phi0z ---------------------- wall wave initial phase % Output parameters: % etau, etad ------------------------ physical wall movement %% Author % Written by Luohao Wang on 2015-9-28 % Contact : [email protected] %% Code function [etau, etad] = wallmove(nx, nz, alpha, beta, Ax, kx, cx, phi0x, ... Az, kz, cz, phi0z, t) x = linspace(0, 2*pi/alpha, nx+1); x = x(1:nx); z = linspace(0, 2*pi/beta, nz+1); z = z(1:nz); etau = zeros(nx, nz); etad = zeros(nx, nz); [len1, len2] = size(Ax); [len3, len4] = size(Az); if (len1 ~= 4 || len3 ~= 4) disp('Dimension error for A in wallmove function!'); else %calculate in x direction for iter_z = 1:nz for iter_wave = 1:len2 etau(:,iter_z) = etau(:,iter_z) + Ax(iter_wave, 1)*... sin(kx(iter_wave, 1)*x - cx(iter_wave, 1)*t + phi0x(iter_wave, 1)); etad(:,iter_z) = etad(:,iter_z) + Ax(iter_wave, 2)*... sin(kx(iter_wave, 2)*x - cx(iter_wave, 2)*t + phi0x(iter_wave, 2)); end end %calculate in z direction for iter_x = 1:nx for iter_wave = 1:len4 etau(iter_x,:) = etau(iter_x,:) + Az(iter_wave, 1)*... sin(kz(iter_wave, 1)*z - cz(iter_wave, 1)*t + phi0z(iter_wave, 1)); etad(iter_x,:) = etad(iter_x,:) + Az(iter_wave, 2)*... sin(kz(iter_wave, 2)*z - cz(iter_wave, 1)*t + phi0z(iter_wave, 1)); end end end end
github
fxie2/Channel_DNS-master
fcl.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/fcl.m
2,248
utf_8
9b2c970ce79cf19b19812669babe5139
%% Channel DNS Subfunction - fcl %% Purpose % Compute u_i*v_i in spectral space using FFT instead of convolution %% Method % See 3/2 rule %% Parameters % Input parameters: % u, v ------------------------ spectral data in 3-D for convolution % Output parameter: % w --------------------------- spectral result in 3-D %% Attention % For 3-D reason, we cannot directly perform fft2 or ifft2 on the slice % like u(:,iter,:) which will lead to dimension error. So we have to use % a temporary matrix to store the slice, mannuly do twice fft and % fftshift, and return the result to the initial slice. %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function w = fcl(u, v) [nx, ny, nz] = size(u); U_trans_y = zeros(size(u)); V_trans_y = zeros(size(v)); for iter_x = 0:nx-1 for iter_z = 0:nz-1 U_trans_y(iter_x+1,:,iter_z+1) = FCT(u(iter_x+1,:,iter_z+1),-1); V_trans_y(iter_x+1,:,iter_z+1) = FCT(v(iter_x+1,:,iter_z+1),-1); end end U_extend = zeros(nx/2*3, ny, nz/2*3); V_extend = zeros(nx/2*3, ny, nz/2*3); U_extend(nx/4+1:nx/4+nx,:,nz/4+1:nz/4+nz) = U_trans_y; V_extend(nx/4+1:nx/4+nx,:,nz/4+1:nz/4+nz) = V_trans_y; U_real = zeros(size(U_extend)); V_real = zeros(size(V_extend)); for iter_y = 0:ny-1 temp = reshape(U_extend(:,iter_y+1,:), nx/2*3, nz/2*3); temp = ifftshift(temp,1); temp = ifft(temp).'; temp = ifftshift(temp,1); temp = ifft(temp).'; U_real(:,iter_y+1,:) = temp; temp = reshape(V_extend(:,iter_y+1,:), nx/2*3, nz/2*3); temp = ifftshift(temp,1); temp = ifft(temp).'; temp = ifftshift(temp,1); temp = ifft(temp).'; V_real(:,iter_y+1,:) = temp; %temp here is only for coefficient shift end W_real = U_real.*V_real; W_extend = zeros(size(U_extend)); for iter_y = 0:ny-1 temp = reshape(W_real(:,iter_y+1,:), nx/2*3, nz/2*3); temp = fft(temp); temp = fftshift(temp,1).'; temp = fft(temp); temp = fftshift(temp,1).'; W_extend(:,iter_y+1,:) = temp; end W_trans_y = W_extend(nx/4+1:nx/4+nx,:,nz/4+1:nz/4+nz); w = zeros(size(u)); for iter_x = 0:nx-1 for iter_z = 0:nz-1 w(iter_x+1,:,iter_z+1) = FCT(W_trans_y(iter_x+1,:,iter_z+1),1); end end w = 9/4*w; end
github
fxie2/Channel_DNS-master
FCT.m
.m
Channel_DNS-master/SpcMethod/MoveWall/Matlab/FCT.m
2,444
utf_8
86deacb16830af48ce9e19167ec1a22b
%% Fast Chebyshev Transform %% Introduction % This function is used to transform a series of data from % physical space into spectral space (or inverse), which is % useful in solving boundary problems by spectral method. %% Theory % Suppose we have a series of data, {f_k}, k = 0,1,2,...,N, % which is generated from a function f(x) on Chebyshev- % Gauss-Lobatto Nodes x=cos(k*pi/N). Let T_k(x) be the k-th % Chebyshev polynomial, which is cos(k * arccos(x)). Now % we can expand f(x) as Chebyshev series, % % f(x) = sum a_m * T_m(x), m = 0:N % % Since T_m(x_k) = cos(m*n*pi/N), we can get % % f_k = sum a_m * cos(m*n*pi/N), m = 0:N % % Observing this formula, we can discover its relationship % with DFT. To make this clear, we construct a new sequence, % which is {f_0, f_1, ... , f_N , f_N-1, ... , f_2}, and perform % 2N IDFT on it, we get % % f_k = sum a_m * exp(2*pi*i * m*k/2*N), m = 0:2N % % Since f_k = f_2N-k, we get % % sum a_m * i * sin(2*pi * m*k/2*N) = 0, m = 0:2N % % This indicates that the IDFT above only contains real part. % And we get % % f_k = sum a_m * cos(pi*m*n/N), m = 0:2N % % Note that exp(2*pi*i * m*(2N-k)/2N) = exp(2*pi*i * (2N-m)*k/2N), % we can get a_m = a_2N-m. So that % % f_k = a_0 + sum 2*a_m*cos(m*k*pi/N) + a_N*cos(N*k*pi/N), % m = 1:N-1 % and we now get the answer for the formal problem. %% Parameters % A ---------------- Input data in coloum % B ---------------- Output data in coloum % direction -------- 1 for physical -> spectral % -1 for spectral -> physical %% Author % Written by Luohao Wang on 2015-9-10 % Contact : [email protected] %% Acknowledgement % Inspired by fcgltran by Greg von Winckel, fixed a few bugs. % Website : http://www.mathworks.com/matlabcentral/fileexchange/4591-fast-chebyshev-transform--1d- %% Code function B = FCT(A, direction) [N,~] = size(A); if N == 1 B = transpose(FCT(transpose(A), direction)); else if direction == 1 % physical -> spectral F=ifft([A(1:N,:);A(N-1:-1:2,:)]); B=([F(1,:); 2*F(2:(N-1),:); F(N,:)]); elseif direction == -1 % physical -> spectral F=fft([A(1,:);A(2:N-1,:)/2;A(N,:);A(N-1:-1:2,:)/2]); B=(F(1:N,:)); else disp('Direction identifier can only be -1 or 1! Please check your program.'); end end end
github
fxie2/Channel_DNS-master
ode2_solve.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/ode2_solve.m
3,689
utf_8
ba5e7b3b7cc1e99fabbee3a08fb4dce1
%% Channel DNS Subfunction - ode2_solve %% Purpose % Solve the 2nd order diffential equation in the form: % f"(y) - k*f(y) = s(y) , y in [-1, 1] % with first kind boundary condition: % f(-1) = A, f(1) = B % or with second kind boundary condition: % f'(-1) = A, f'(1) = B %% Method % Use Chebyshev transform to solve the equation. % Let % % f(y) = sum fp*Tp(y) , p=0:P % s(y) = sum sp*Tp(y) , p=0:P % % The main equation can be written as % % k*c_p-2 * f_p-2 k * e_p+2 k * e_p+4 * f_p+2 % ---------------- - (1 + ------------ )*f_p + ------------------- % 4*p*(p-1) 2*(p^2-1) 4*p*(p+1) % % c_p-2 * s_p-2 e_p+2 * s_p e_p+4 * s_p+2 % = -( ---------------- - ------------- + --------------- ) % 4*p*(p-1) 2*(p^2-1) 4*p*(p+1) % (by Gottlib & Orszag, 1977) % ( e_p = 1 for p<=P, e_p = 0 for p>P) % and for boundary conditions % 1st kind: % sum (-1)^p * fp = A , p=0:P % sum fp = B , p=0:P % 2nd kind: % sum (-1)^p * fp' = A , p=0:P % sum fp' = B , p=0:P % cp*fp' = 2 * sum k*fk , k=p+1:P %% Parameters % Input parameters: % k ------------------------- the k factor % s ------------------------- the right term % boundary_type ------------- 1 for 1st, 2 for 2nd. % boundary_conditions ------- [A, B] 2 boundary values for (-1, +1) % input_type ---------------- 's' for spectral, 'p' for physical % output_type --------------- 's' for spectral, 'p' for physical % Output parameter: % f ------------------------- the solution %% Author % Written by Luohao Wang on 2015-9-10 % Contact : [email protected] %% Code function f = ode2_solve(k, s, boundary_type, boundary_conditons, input_type, output_type) P = length(s) - 1; if input_type == 'p' sp = FCT(s, 1); else sp = s; end %form the index array i = zeros(5*P - 3, 1); p = zeros(5*P - 3, 1); v = zeros(5*P - 3, 1); n = 1; for iter = 1:P-5 i(n:n+2) = iter*ones(1,3); p(n:n+2) = [0,2,4] + iter*ones(1,3); v(n) = k / (4*(iter + 1)*iter); v(n+1) = -(1 + k / (2*((iter+1)^2 - 1))); v(n+2) = k / (4*(iter+1)*(iter+2)); n = n + 3; end for iter = P-4:P-3 i(n:n+2) = iter*ones(1,3); p(n:n+2) = [0,2,4] + iter*ones(1,3); v(n) = k / (4*(iter + 1)*iter); v(n+1) = -(1 + k / (2*((iter+1)^2 - 1))); v(n+2) = 0; n = n + 3; end v(1) = k / 4; i(n:n+3) = [P-2,P-2,P-1,P-1]; p(n:n+3) = [P-2,P,P-1,P+1]; v(n) = k/(4*(P-1)*(P-2)); v(n+1) = -1; v(n+2) = k/(4*P*(P-1)); v(n+3) = -1; i(3*P-4:4*P-4) = P*ones(1,P+1); i(4*P-3:5*P-3) = (P+1)*ones(1,P+1); p(3*P-4:4*P-4) = 1:P+1; p(4*P-3:5*P-3) = 1:P+1; if boundary_type == 1 v(3*P-4:4*P-4) = (-1).^(0:P); v(4*P-3:5*P-3) = ones(1,P+1); elseif boundary_type == 2 v(3*P-4:4*P-4) = -(0:P).^2.*(-1).^(0:P); v(4*P-3:5*P-3) = (0:P).^2; else disp('boundary type error!'); end M = sparse(i,p,v); b = zeros(P+1,1); b(1) = -(sp(1)/4 - sp(3)/6 + sp(5)/24); for iter = 2:P-5 pp = iter + 1; b(iter) = -(sp(pp-2+1)/(4*pp*(pp-1)) - sp(pp+1)/(2*(pp^2 - 1)) + sp(pp+3)/(4*pp*(pp+1))); end b(P-4) = -(sp(P-4)/(4*(P-3)*(P-4)) - sp(P-2)/(2*((P-3)^2 - 1))); b(P-3) = -(sp(P-3)/(4*(P-2)*(P-3)) - sp(P-1)/(2*((P-2)^2 - 1))); b(P-2) = -sp(P-2)/(4*(P-1)*(P-2)); b(P-1) = -sp(P-1)/(4*(P-1)*P); b(P) = boundary_conditons(1); b(P+1) = boundary_conditons(2); if abs(k) <= eps() && boundary_type == 2 temp_ans = zeros(P+1,1); temp_ans(2:P+1) = M(2:P+1,2:P+1)\b(2:P+1); else temp_ans = M\b; end if output_type == 'p' f = FCT(temp_ans,-1); else f = temp_ans; end end
github
fxie2/Channel_DNS-master
global_trans.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/global_trans.m
1,476
utf_8
c2edfd66d6832abd467b2fe915955e21
%% Channel DNS Subfunction - global_trans %% Purpose % Transform between physical space and spectral space %% Parameters % Input parameters: % u ------------------------ spectral or physical data % direction ---------------- 1 for p -> s, -1 for s -> p % Output parameter: % w ------------------------ physical or spectral result %% Author % Written by Luohao Wang on 2015-9-13 % Contact : [email protected] %% Code function w = global_trans(u, direction) [nx, ny, nz] = size(u); w = zeros(size(u)); if direction == 1 for iter_y = 1:ny temp = reshape(u(:,iter_y,:), nx, nz); % temp = fft(temp); % temp = fftshift(temp, 1); % temp = fft(temp.'); % temp = fftshift(temp, 1); % w(:,iter_y,:) = temp.'; temp = fftshift(fft2(temp)); w(:,iter_y,:) = temp; end for iter_x = 1:nx for iter_z = 1:nz w(iter_x,:,iter_z) = FCT(w(iter_x,:,iter_z), 1); end end elseif direction == -1 for iter_x = 1:nx for iter_z = 1:nz w(iter_x,:,iter_z) = FCT(u(iter_x,:,iter_z), -1); end end for iter_y = 1:ny temp = reshape(w(:,iter_y,:), nx, nz); % temp = ifftshift(temp, 1); % temp = ifft(temp).'; % temp = ifftshift(temp,1); % temp = ifft(temp).'; % w(:,iter_y,:) = temp; temp = ifft2(ifftshift(temp)); w(:,iter_y,:) = temp; end w = real(w); end end
github
fxie2/Channel_DNS-master
Gterm.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/Gterm.m
941
utf_8
bfcd84f4dde4cf3f98ff4c5762a5ecc6
%% Channel DNS Subfunction - Gterm %% Purpose % Calculate the G term in Pressure step %% Parameters % Input parameters: % fy -------------------------- lamb-y term % us, vs, ws ------------------ velocity term % alpha, beta ----------------- wave number % re -------------------------- reynold number % Output parameter % G --------------------------- G term %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function G = Gterm(fy, us, vs, ws, alpha, beta, re) rot_x = globe_partial(ws, 'y', 0) - globe_partial(vs, 'z', beta); rot_z = globe_partial(vs, 'x', alpha) - globe_partial(us, 'y', 0); G = fy; [nx, ~, nz] = size(fy); i = complex(0,1); parfor iter_x = 1:nx for iter_z = 1:nz G(iter_x,:,iter_z) = G(iter_x,:,iter_z) + (i*alpha*(iter_x-1-nx/2)*rot_z(iter_x,:,iter_z)... - i*beta*(iter_z-1-nz/2)*rot_x(iter_x,:,iter_z)) / re; end end end
github
fxie2/Channel_DNS-master
correct.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/correct.m
3,172
utf_8
5448b3d830a487cfe2874f301c895edc
%% Channel DNS Subfunction - Correct %% Purpose % Calculate the pressure and velocity correct field %% Method % The correct pressure field satisfies: % % laplace P_c+ = 0 % P_c+(y=1) = 1, P_c+(y=-1) = 0 (Selected) % % laplace P_c- = 0 % P_c-(y=1) = 0, P_c-(y=-1) = 1 % % And the correct velocity field satisfies: % % laplace V_c+ - V_c+ / niu*dt = 1/niu * P_c+ % V_c+(y = -1 and 1) = 0 (Selected) % % laplace V_c- - V_c- / niu*dt = 1/niu * P_c- % V_c-(y = -1 and 1) = 0 % % Considering the symmetry of P_c+ and P_c-, V_c+ and V_c-, % we only need to compute one pair of the equations. In this % function, the first pair of equations are solved. %% Parameters % Input parameters: % nx ----------------------- node number in x % ny ----------------------- node number in y % nz ----------------------- node number in z % alpha -------------------- wave number in x % beta --------------------- wave number in z % re ----------------------- reynold number % dt ----------------------- time space % Output parameters: % pc ----------------------- correct pressure field % uc ----------------------- correct u-velocity field % vc ----------------------- correct v-velocity field % wc ----------------------- correct w-velocity field % M ------------------------ correct matrix in physical % Note : All output parameters are in spectral space %% Author % Written by Luohao Wang on 2015-9-10 % Contact : [email protected] %% Code function [pc, uc, vc, wc, M] = correct(nx, ny, nz, alpha, beta, re, dt) pc = zeros(nx, ny, nz); uc = zeros(nx, ny, nz); vc = zeros(nx, ny, nz); wc = zeros(nx, ny, nz); M = zeros(nx, nz, 2, 2); s = zeros(1, ny); gamma0 = 11/6; %Pressure correct for iter_x = 0:nx-1 for iter_z = 0:nz-1 k = alpha^2*(iter_x - nx/2)^2 + beta^2*(iter_z - nz/2)^2; pc(iter_x+1,:,iter_z+1) = ode2_solve(k, s, 1, [0,1], 'p', 's'); end end %Velocity correct d_p_dx = globe_partial(pc, 'x', alpha); d_p_dy = globe_partial(pc, 'y', 0); d_p_dz = globe_partial(pc, 'z', beta); for iter_x = 0:nx-1 for iter_z = 0:nz-1 k = re*gamma0/dt + alpha^2*(iter_x - nx/2)^2 + beta^2*(iter_z - nz/2)^2; uc(iter_x+1,:,iter_z+1) = ode2_solve(k, re * d_p_dx(iter_x+1,:,iter_z+1), 1, [0,0], 's', 's'); vc(iter_x+1,:,iter_z+1) = ode2_solve(k, re * d_p_dy(iter_x+1,:,iter_z+1), 1, [0,0], 's', 's'); wc(iter_x+1,:,iter_z+1) = ode2_solve(k, re * d_p_dz(iter_x+1,:,iter_z+1), 1, [0,0], 's', 's'); end end %form correct matrix div_V = globe_partial(uc, 'x', alpha) + globe_partial(vc, 'y', 0) ... + globe_partial(wc, 'z', beta); div_V = y_trans(div_V, -1); for iter_x = 1:nx for iter_z = 1:nz M(iter_x, iter_z, 1, 1) = div_V(iter_x, 1, iter_z); M(iter_x, iter_z, 1, 2) = div_V(iter_x, ny, iter_z); M(iter_x, iter_z, 2, 1) = div_V(iter_x, ny, iter_z); M(iter_x, iter_z, 2, 2) = div_V(iter_x, 1, iter_z); end end % %transform to physical space % pc = y_trans(pc, -1); % uc = y_trans(uc, -1); % vc = y_trans(vc, -1); % wc = y_trans(wc, -1); end
github
fxie2/Channel_DNS-master
partial.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/partial.m
1,054
utf_8
b51691935828ded1c7bd1f4b70a1543b
%% Channel DNS Subfunction - partial %% Purpose % Calculate the partial derivative in spectral space %% Parameters % Input parameters: % f ------------------------- input data in spectral space % direction ----------------- 'x' for d_dx, and so is others % parameter ----------------- alpha for 'x', beta for 'z', % nothing for 'y' %% Author % Written by Luohao Wang on 2015-9-11 % Contact : [email protected] %% Code function d = partial(f, direction, parameter) len = length(f); if direction == 'x' %now parameter == alpha d = complex(0,1)*parameter.*(-len/2:len/2-1).*f; elseif direction == 'z' %now parameter == beta d = complex(0,1)*parameter.*(-len/2:len/2-1).*f; elseif direction == 'y' %now parameter is useless, can be anything P = len - 1; [~,N] = size(f); if N == 1 f = transpose(f); end d = zeros(size(f)); d(1) = sum((1:2:P).*f((1:2:P)+1)); for p = 2:P d(p) = 2*sum((p:2:P).*f((p:2:P)+1)); end if N == 1 d = transpose(d); end end end
github
fxie2/Channel_DNS-master
dpdx_correct.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/dpdx_correct.m
1,174
utf_8
92b0138e9e1ba91082d0bfcbf390c997
%% Channel DNS Subroutine - dpdx_correct %% Puporse % Correct the gradient of pressure according to the constant mass flow % boundary condition %% Method % Treat dpdx as the function of mass flow rate, use secant method to find % the sloution %% Code function dpdx = dpdx_correct(u, dpdx_u, u_hist, dpdx_hist, q_set, beta) [nx, ny, nz] = size(u); u_p = global_trans(u, -1); u_hist_p = global_trans(u_hist, -1); u_diff = u_p(nx, :, :) - u_hist_p(nx, :, :); u_diff = reshape(u_diff, ny, nz); if ~(max(max(abs(u_diff))) >= 1e-6 && abs(dpdx_u-dpdx_hist) > eps()) dpdx = dpdx_u; else dz = 2*pi/beta/nz; q_u = 0; q_hist = 0; for iter_z = 1:nz u_ys_temp = reshape(FCT(u_p(nx, :, iter_z), 1), 1, ny); u_hist_ys_temp = reshape(FCT(u_hist_p(nx, :, iter_z), 1), 1, ny); for iter_y = 1:2:ny n = iter_y - 1; q_u = q_u + u_ys_temp(iter_y) * 2 / (1-n^2) * dz; q_hist = q_hist + u_hist_ys_temp(iter_y) * 2 / (1-n^2) * dz; end end if abs(q_u - q_hist) <= 1e-6 dpdx = dpdx_u; else dpdx = dpdx_u + (q_set - q_u) * (dpdx_u - dpdx_hist) / (q_u - q_hist); end end end
github
fxie2/Channel_DNS-master
globe_partial.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/globe_partial.m
1,021
utf_8
0a9e12cca4a4256d24243d88813e50f9
%% Channel DNS Subfunction - globe_partial %% Purpose % Calculate the parital derivative of the hole field %% Parameters % Input parameters: % f ------------------------- spectral data in 3-D % direction ----------------- 'x' for d_dx, and so on % parameter ----------------- alpha for 'x', beta for 'z', nothing for % 'y' %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function df = globe_partial(f, direction, parameter) [nx, ~, nz] = size(f); df = zeros(size(f)); if direction == 'x' for iter_x = 0:nx-1 df(iter_x+1,:,:) = complex(0,1).*parameter.*f(iter_x+1,:,:).*(iter_x - nx/2); end elseif direction == 'z' for iter_z = 0:nz-1 df(:,:,iter_z+1) = complex(0,1).*parameter.*f(:,:,iter_z+1).*(iter_z - nz/2); end elseif direction == 'y' for iter_x = 1:nx for iter_z = 1:nz df(iter_x,:,iter_z) = partial(f(iter_x,:,iter_z), 'y', 0); end end else disp('direction error'); end end
github
fxie2/Channel_DNS-master
initialize.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/initialize.m
762
utf_8
5201f72699bd17b93a2f32b35f527d85
%% Channel DNS Subfunction - initialize %% Purpose % Initialize the fluid field at the start time %% Parameters % nx, ny, nz ----------------------------- mesh size % alpha, beta ---------------------------- wave number in x and z %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function [p, u, v, w] = initialize(nx, ny, nz, alpha, dpdx) p = zeros(nx, ny, nz); u = zeros(nx, ny, nz); v = zeros(nx, ny, nz); w = zeros(nx, ny, nz); %Use theoretical Poiseuille flow field to initialize %Velocity initialize for iter_y = 1:ny y = cos((iter_y-1)*pi/(ny-1)); u(:, iter_y, :) = 1 - y^2; end %Pressure initialize for iter_x = 2:nx p(iter_x,:,:) = p(iter_x-1,:,:) - dpdx*2*pi/alpha/nx; end end
github
fxie2/Channel_DNS-master
lamb.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/lamb.m
824
utf_8
50918fd8bcceff06447f45d84c8ed52a
%% Channel DNS Subfunction - lamb %% Purpose % Calculate the lamb term F = V X w. %% Parameters % Input parameters: % us , vs, ws ------------------------- spectral velocity in 3-D % alpha, beta ------------------------- wave number in x and z % Output parameters: % fx, fy, fz -------------------------- convective term in spectral %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function [fx, fy, fz] = lamb(us, vs, ws, alpha, beta) rot_x = globe_partial(ws, 'y', 0) - globe_partial(vs, 'z', beta); rot_y = globe_partial(us, 'z', beta) - globe_partial(ws, 'x', alpha); rot_z = globe_partial(vs, 'x', alpha) - globe_partial(us, 'y', 0); fx = fcl(vs, rot_z) - fcl(ws, rot_y); fy = fcl(ws, rot_x) - fcl(us, rot_z); fz = fcl(us, rot_y) - fcl(vs, rot_x); end
github
fxie2/Channel_DNS-master
fcl.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/fcl.m
2,372
utf_8
42f6311dd63f57c3781427680d1fd651
%% Channel DNS Subfunction - fcl %% Purpose % Compute u_i*v_i in spectral space using FFT instead of convolution %% Method % See 3/2 rule %% Parameters % Input parameters: % u, v ------------------------ spectral data in 3-D for convolution % Output parameter: % w --------------------------- spectral result in 3-D %% Attention % For 3-D reason, we cannot directly perform fft2 or ifft2 on the slice % like u(:,iter,:) which will lead to dimension error. So we have to use % a temporary matrix to store the slice, mannuly do twice fft and % fftshift, and return the result to the initial slice. %% Author % Written by Luohao Wang on 2015-9-12 % Contact : [email protected] %% Code function w = fcl(u, v) [nx, ny, nz] = size(u); U_trans_y = zeros(size(u)); V_trans_y = zeros(size(v)); for iter_x = 0:nx-1 for iter_z = 0:nz-1 U_trans_y(iter_x+1,:,iter_z+1) = FCT(u(iter_x+1,:,iter_z+1),-1); V_trans_y(iter_x+1,:,iter_z+1) = FCT(v(iter_x+1,:,iter_z+1),-1); end end U_extend = zeros(nx/2*3, ny, nz/2*3); V_extend = zeros(nx/2*3, ny, nz/2*3); U_extend(nx/4+1:nx/4+nx,:,nz/4+1:nz/4+nz) = U_trans_y; V_extend(nx/4+1:nx/4+nx,:,nz/4+1:nz/4+nz) = V_trans_y; U_real = zeros(size(U_extend)); V_real = zeros(size(V_extend)); for iter_y = 0:ny-1 temp = reshape(U_extend(:,iter_y+1,:), nx/2*3, nz/2*3); % temp = ifftshift(temp,1); % temp = ifft(temp).'; % temp = ifftshift(temp,1); % temp = ifft(temp).'; temp = ifft(ifftshift(temp)); U_real(:,iter_y+1,:) = temp; temp = reshape(V_extend(:,iter_y+1,:), nx/2*3, nz/2*3); % temp = ifftshift(temp,1); % temp = ifft(temp).'; % temp = ifftshift(temp,1); % temp = ifft(temp).'; temp = ifft(ifftshift(temp)); V_real(:,iter_y+1,:) = temp; %temp here is only for coefficient shift end W_real = U_real.*V_real; W_extend = zeros(size(U_extend)); for iter_y = 0:ny-1 temp = reshape(W_real(:,iter_y+1,:), nx/2*3, nz/2*3); % temp = fft(temp); % temp = fftshift(temp,1).'; % temp = fft(temp); % temp = fftshift(temp,1).'; temp = fftshift(fft(temp)); W_extend(:,iter_y+1,:) = temp; end W_trans_y = W_extend(nx/4+1:nx/4+nx,:,nz/4+1:nz/4+nz); w = zeros(size(u)); for iter_x = 0:nx-1 for iter_z = 0:nz-1 w(iter_x+1,:,iter_z+1) = FCT(W_trans_y(iter_x+1,:,iter_z+1),1); end end w = 9/4*w; end
github
fxie2/Channel_DNS-master
FCT.m
.m
Channel_DNS-master/SpcMethod/SteadyWall/Matlab/FCT.m
2,444
utf_8
86deacb16830af48ce9e19167ec1a22b
%% Fast Chebyshev Transform %% Introduction % This function is used to transform a series of data from % physical space into spectral space (or inverse), which is % useful in solving boundary problems by spectral method. %% Theory % Suppose we have a series of data, {f_k}, k = 0,1,2,...,N, % which is generated from a function f(x) on Chebyshev- % Gauss-Lobatto Nodes x=cos(k*pi/N). Let T_k(x) be the k-th % Chebyshev polynomial, which is cos(k * arccos(x)). Now % we can expand f(x) as Chebyshev series, % % f(x) = sum a_m * T_m(x), m = 0:N % % Since T_m(x_k) = cos(m*n*pi/N), we can get % % f_k = sum a_m * cos(m*n*pi/N), m = 0:N % % Observing this formula, we can discover its relationship % with DFT. To make this clear, we construct a new sequence, % which is {f_0, f_1, ... , f_N , f_N-1, ... , f_2}, and perform % 2N IDFT on it, we get % % f_k = sum a_m * exp(2*pi*i * m*k/2*N), m = 0:2N % % Since f_k = f_2N-k, we get % % sum a_m * i * sin(2*pi * m*k/2*N) = 0, m = 0:2N % % This indicates that the IDFT above only contains real part. % And we get % % f_k = sum a_m * cos(pi*m*n/N), m = 0:2N % % Note that exp(2*pi*i * m*(2N-k)/2N) = exp(2*pi*i * (2N-m)*k/2N), % we can get a_m = a_2N-m. So that % % f_k = a_0 + sum 2*a_m*cos(m*k*pi/N) + a_N*cos(N*k*pi/N), % m = 1:N-1 % and we now get the answer for the formal problem. %% Parameters % A ---------------- Input data in coloum % B ---------------- Output data in coloum % direction -------- 1 for physical -> spectral % -1 for spectral -> physical %% Author % Written by Luohao Wang on 2015-9-10 % Contact : [email protected] %% Acknowledgement % Inspired by fcgltran by Greg von Winckel, fixed a few bugs. % Website : http://www.mathworks.com/matlabcentral/fileexchange/4591-fast-chebyshev-transform--1d- %% Code function B = FCT(A, direction) [N,~] = size(A); if N == 1 B = transpose(FCT(transpose(A), direction)); else if direction == 1 % physical -> spectral F=ifft([A(1:N,:);A(N-1:-1:2,:)]); B=([F(1,:); 2*F(2:(N-1),:); F(N,:)]); elseif direction == -1 % physical -> spectral F=fft([A(1,:);A(2:N-1,:)/2;A(N,:);A(N-1:-1:2,:)/2]); B=(F(1:N,:)); else disp('Direction identifier can only be -1 or 1! Please check your program.'); end end end
github
zhangyaonju/SCOPE-master
leafangles.m
.m
SCOPE-master/SCOPE_v1.xx/code/leafangles.m
2,171
utf_8
f75c20fd775190446a1b01537666fe9b
function [lidf]= leafangles(a,b) % Subroutine FluorSail_dladgen % Version 2.3 % For more information look to page 128 of "theory of radiative transfer models applied in optical remote sensing of % vegetation canopies" % % FluorSail for Matlab % FluorSail is created by Wout Verhoef, % National Aerospace Laboratory (NLR) % Present e-mail: [email protected] % % This code was created by Joris Timmermans, % International institute for Geo-Information Science and Earth Observation. (ITC) % Email: [email protected] % %% main function F = zeros(1,13); for i=1:8 theta = i*10; % theta_l = 10:80 F(i) = dcum(a,b,theta); % F(theta) end for i=9:12 theta = 80 + (i-8)*2; % theta_l = 82:88 F(i) = dcum(a,b,theta); % F(theta) end for i=13:13 % theta_l = 90:90 F(i) = 1; % F(theta) end lidf = zeros(13,1); for i=13:-1:2 lidf(i) = F(i) - F(i-1); % lidf = dF/dtheta; end lidf(1) = F(1); % Boundary condition %% SubRoutines function [F] = dcum(a,b,theta) rd = pi/180; % Geometrical constant if a>1 F = 1 - cos(theta*rd); else eps = 1e-8; delx = 1; x = 2*rd *theta; theta2 = x; % while max(delx > eps) y = a*sin(x) + 0.5*b*sin(2*x); dx = 0.5*(y - x + theta2); x = x + dx; delx= abs(dx); end F = (2*y + theta2)/pi; % Cumulative leaf inclination density function %pag 139 thesis says: F = 2*(y+p)/pi. %Since theta2=theta*2 (in rad), this makes F=(2*y + 2*theta)/pi end
github
zhangyaonju/SCOPE-master
resistances.m
.m
SCOPE-master/SCOPE_v1.xx/code/resistances.m
7,021
utf_8
d6ca3e4e301c369a6c4d0c7ca8630dd1
function [resist_out] = resistances(resist_in) % % function resistances calculates aerodynamic and boundary resistances % for soil and vegetation % % Date: 01 Feb 2008 % Authors: Anne Verhoef ([email protected]) % Christiaan van der Tol ([email protected]) % Joris Timmermans ([email protected]) % Source: Wallace and Verhoef (2000) 'Modelling interactions in % mixed-plant communities: light, water and carbon dioxide', in: Bruce % Marshall, Jeremy A. Roberts (ed), 'Leaf Development and Canopy Growth', % Sheffield Academic Press, UK. ISBN 0849397693 % % ustar: Tennekes, H. (1973) 'The logaritmic wind profile', J. % Atmospheric Science, 30, 234-238 % Psih: Paulson, C.A. (1970), The mathematical % representation of wind speed and temperature in the % unstable atmospheric surface layer. J. Applied Meteorol. 9, % 857-861 % % Note: Equation numbers refer to equation numbers in Wallace and Verhoef (2000) % % Usage: % [resist_out] = resistances(resist_in) % % The input and output are structures. These structures are further % specified in a readme file. % % Input: % resist_in aerodynamic resistance parameters and wind speed % % The strucutre resist_in contains the following elements: % u = windspeed % L = stability % LAI = Leaf Area Index % rbs = Boundary Resistance of soil [s m-1] % rss = Surface resistance of soil for vapour transport [s m-1] % rwc = Within canopy Aerodynamic Resistance canopy [s m-1] % z0m = Roughness lenght for momentum for the vegetation [m] % d = Displacement height (Zero plane) [m] % z = Measurement height [m] % h = Vegetation height [m] % % Output: % resist_out aeorodynamic resistances % % The strucutre resist_out contains the following elements: % ustar = Friction velocity [m s-1] % raa = Aerodynamic resistance above the canopy [s m-1] % rawc = Total resistance within the canopy (canopy) [s m-1] % raws = Total resistance within the canopy (soil) [s m-1] % rai = Aerodynamic resistance in inertial sublayer [s m-1] % rar = Aerodynamic resistance in roughness sublayer [s m-1] % rac = Aerodynamic resistance in canopy layer (above z0+d) [s m-1] % rbc = Boundary layer resistance (canopy) [s m-1] % rwc = Aerodynamic Resistance within canopy(canopy)(Update)[s m-1] % rbs = Boundary layer resistance (soil) (Update) [s m-1] % rws = Aerodynamic resistance within canopy(soil) [s m-1] % rss = Surface resistance vapour transport(soil)(Update) [s m-1] % uz0 = windspeed at z0 [m s-1] % Kh = Diffusivity for heat [m2s-1] %% parameters global constants kappa = constants. kappa; Cd = resist_in.Cd; u = resist_in.u; L = resist_in.L; LAI = resist_in.LAI; rbs = resist_in.rbs; %rss = resist_in.rss; rwc = resist_in.rwc; z0m = resist_in.zo; d = resist_in.d; z = resist_in.z; h = resist_in.hc; w = resist_in.w; % derived parameters %zr: top of roughness sublayer, bottom of intertial sublayer zr = 2.5*h; % [m] %n: dimensionless wind extinction coefficient W&V Eq 33 n = Cd*LAI/(2*kappa^2); % [] %% stability correction for non-neutral conditions %neu = find(L >= -.001 & L <= .001); unst = find(L < -4); st = find(L > 4E3); % stability correction functions, friction velocity and Kh=Km=Kv pm_z = psim(z -d,L,unst,st); ph_z = psih(z -d,L,unst,st); pm_h = psim(h -d,L,unst,st); %ph_h = psih(h -d,L,unst,st); ph_zr = psih(zr-d,L,unst,st).*(z>=zr) + ph_z.*(z<zr); phs_zr = phstar(zr,zr,d,L,st,unst); phs_h = phstar(h ,zr,d,L,st,unst); ustar = max(.001,kappa*u./(log((z-d)/z0m) - pm_z));% W&V Eq 30 Kh = kappa*ustar*(zr-d); % W&V Eq 35 resist_out.Kh(unst) = kappa*ustar(unst)*(zr-d).*(1-16*(h-d)./L(unst)).^.5;% W&V Eq 35 resist_out.Kh(st) = kappa*ustar(st) *(zr-d).*(1+ 5*(h-d)./L(st) ).^-1;% W&V Eq 35 %% wind speed at height h and z0m uh = max(ustar/kappa .* (log((h-d)/z0m) - pm_h ),.01); uz0 = uh*exp(n*((z0m+d)/h-1)); % W&V Eq 32 %% resistances resist_out.uz0 = uz0; resist_out.ustar = ustar; rai = (z>zr).*(1./(kappa*ustar).*(log((z-d) /(zr-d)) - ph_z + ph_zr));% W&V Eq 41 rar = 1./(kappa*ustar).*((zr-h)/(zr-d)) - phs_zr + phs_h;% W&V Eq 39 rac = h*sinh(n)./(n*Kh)*(log((exp(n)-1)/(exp(n)+1)) - log((exp(n*(z0m+ d )/h)-1)/(exp(n*(z0m +d )/h)+1))); % W&V Eq 42 rws = h*sinh(n)./(n*Kh)*(log((exp(n*(z0m+d)/h)-1)/(exp(n*(z0m+d)/h)+1)) - log((exp(n*(.01 )/h)-1)/(exp(n*(.01 )/h)+1))); % W&V Eq 43 rbc = 70/LAI * sqrt(w./uz0); % W&V Eq 31, but slightly different resist_out.rai = rai; resist_out.rar = rar; resist_out.rac = rac; resist_out.rws = rws; resist_out.rbc = rbc; raa = rai + rar + rac; rawc = rwc + rbc; raws = rws + rbs; resist_out.raa = raa; % aerodynamic resistance above the canopy W&V Figure 8.6 resist_out.rawc = rawc; % aerodynamic resistance within the canopy (canopy) resist_out.raws = raws; % aerodynamic resistance within the canopy (soil) resist_out.raa = min(4E2,raa); % to prevent unrealistically high resistances resist_out.rawc = min(4E2,rawc); % to prevent unrealistically high resistances resist_out.raws = min(4E2,raws); % to prevent unrealistically high resistances return %% subfunction pm for stability correction (eg. Paulson, 1970) function pm = psim(z,L,unst,st) x = (1-16*z./L(unst)).^(1/4); pm = zeros(size(L)); pm(unst) = 2*log((1+x)/2)+log((1+x.^2)/2) -2*atan(x)+pi/2; % unstable pm(st) = -5*z./L(st); % stable return %% subfunction ph for stability correction (eg. Paulson, 1970) function ph = psih(z,L,unst,st) x = (1-16*z./L(unst)).^(1/4); ph = zeros(size(L)); ph(unst) = 2*log((1+x.^2)/2); % unstable ph(st) = -5*z./L(st); % stable return %% subfunction ph for stability correction (eg. Paulson, 1970) function phs = phstar(z,zR,d,L,st,unst) x = (1-16*z./L(unst)).^0.25; phs = zeros(size(L)); phs(unst) = (z-d)/(zR-d)*(x.^2-1)./(x.^2+1); phs(st) = -5*z./L(st); return
github
zhangyaonju/SCOPE-master
biochemical.m
.m
SCOPE-master/SCOPE_v1.xx/code/biochemical.m
10,627
utf_8
e0b5410e1075fd373aa45f0ef7de85f1
function biochem_out = biochemical(biochem_in) % % Date: 21 Sep 2012 % Update: 20 Feb 2013 % Update: Aug 2013: correction of L171: Ci = Ci*1e6 ./ p .* 1E3; % % Authors: Joe Berry and Christiaan van der Tol, contributions of others. % Sources: % Farquhar et al. 1980, Collatz et al (1991, 1992). % % This function calculates: % - stomatal resistance of a leaf or needle (s m-1) % - photosynthesis of a leaf or needle (umol m-2 s-1) % - fluorescence of a leaf or needle (fraction of fluor. in the dark) % % Usage: % biochem_out = biochemical(biochem_in) % the function was tested for Matlab 7.2.0.232 (R2006a) % % Calculates net assimilation rate A, fluorescence F using biochemical model % % Input (units are important): % structure 'biochem_in' with the following elements: % Fluorescence_model integer with % 0: with sustained quenching after drought, as in Lee et al. (2013) % 1: calibrated for cotton data set: no drought % Cs % [umol m-3] initial estimate of conc. of CO2 in the % ...bounary layer of the leaf % Q % [umol photons m-2 s-1]net radiation, PAR % T % [oC or K] leaf temperature % eb % [hPa] intial estimate of the vapour pressure in leaf boundary layer % O % [mmol m-3] concentration of O2 (in the boundary % ...layer, but no problem to use ambient) % p % [hPa] air pressure % Vcmo % [umol/m2/s] maximum carboxylation capacity % m % [] Ball-Berry coefficient 'm' for stomatal regulation % Type % [] text parameter, either 'C3' for C3 or any % ...other text for C4 % tempcor % [] boolean (0 or 1) whether or not % ...temperature correction to Vcmax has to be applied. % Tsparams % [],[],[K],[K],[K] vector of 5 temperature correction % parameters, look in spreadsheet of PFTs. Only if tempcor=1, otherwise use % dummy values % Rdparam % [] respiration as fraction of Vcmax % stressfactor [] optional input: stress factor to reduce Vcmax (for % example soil moisture, leaf age). Default value = 1. % % Note: always use the prescribed units. Temperature can be either oC or K % Note: input can be single numbers, vectors, or n-dimensional % matrices % % Output: % structure 'biochem_out' with the following elements: % A % [umol/m2/s] net assimilation rate of the leaves % Cs % [umol/m3] CO2 concentration in the boundary layer % eta0 % [] fluorescence as fraction of dark % ...adapted (fs/fo) % rcw % [s m-1] stomatal resistance % qE % [] non photochemical quenching % fs % [] fluorescence as fraction of PAR % Ci % [umol/m3] internal CO2 concentration % Kn % [] rate constant for excess heat % fo % [] dark adapted fluorescence (fraction of aPAR) % fm % [] light saturated fluorescence (fraction of aPAR) % qQ % [] photochemical quenching % Vcmax % [umol/m2/s] carboxylation capacity after % ... temperature correction %% input Rdparam = biochem_in.Rdparam; %[umol/m2/s] dark respiration rate at 25 oC as fraction of Vcmax Tparams = biochem_in.Tparams; %[] temperature sensitivities of Vcmax, etc (dummy values of applTcorr was selected above) Cs = biochem_in.Cs; Q = biochem_in.Q; T = biochem_in.T; eb = biochem_in.eb; O = biochem_in.O; p = biochem_in.p; Vcmo = biochem_in.Vcmo; m = biochem_in.m; Type = biochem_in.Type; tempcor = biochem_in.tempcor; stressfactor = biochem_in.stressfactor; model_choice = biochem_in.Fluorescence_model; T = T+273.15*(T<100); % convert temperatures to K if not already rhoa = 1.2047; % [kg m-3] specific mass of air Mair = 28.96; % [g mol-1] molecular mass of dry air %% parameters (at optimum temperature) Kcopt = 350; % [ubar] kinetic coefficient for CO2 (Von Caemmerer and Furbank, 1999) Koopt = 450; % [mbar] kinetic coeeficient for O2 (Von Caemmerer and Furbank, 1999) Kf = 0.05; % [] rate constant for fluorescence %Kd = 0.95; % [] rate constant for thermal deactivation at Fm Kp = 4.0; % [] rate constant for photochemisty kpopt = Vcmo/56*1E6; % [] PEPcase rate constant for C02, used here: Collatz et al: Vcmo = 39 umol m-1 s-1; kp = 0.7 mol m-1 s-1. if isfield(biochem_in,'atheta') atheta = biochem_in.atheta; else atheta = 0.8; end if biochem_in.Fluorescence_model==0 % default drought values: Knparams = [5.01, 1.93, 10]; else % default general values (cotton dataset) Knparams = [2.48, 2.83, 0.114]; end %% temperature definitions Tref = 25+273.15; % [K] absolute temperature at 25 oC slti = Tparams(1); %shti = Tparams(2); Thl = Tparams(3); %Thh = Tparams(4); Trdm = Tparams(5); %% convert all to bar Cs = Cs * 1e-6 .* p .*1E-3; O = O * 1e-3 .* p .*1E-3 * ~strcmp('C4',Type); % forced to be zero for C4 vegetation (this is a trick to prevent oxygenase) Kcopt = Kcopt * 1e-6; Koopt = Koopt * 1e-3; %% temperature corrections qt = 0.1 * (T-Tref) * tempcor; %TH = 1 + tempcor* exp(shti .* (T -Thh)); TH = 1 + tempcor* exp((-220E3+703*T)./(8.314*T)); TL = 1 + tempcor* exp(slti .* (Thl -T)); Kc = Kcopt * 2.1.^qt; Ko = Koopt * 1.2.^qt; kp = kpopt.* 1.8.^qt; Kd = max(0.0301*(T-273.15)+ 0.0773,0.8738); Rd = Rdparam * Vcmo .* 1.8.^qt ./(1+exp(1.3*(T-Trdm))); switch Type case 'C3' Vcmax = Vcmo .* 2.1.^qt ./TH * stressfactor; otherwise Vcmax = Vcmo .* 2.1.^qt ./(TL.*TH) * stressfactor; end spfy = 2600 * 0.75 .^qt; % This is, in theory, Vcmax/Vomax.*Ko./Kc, but used as a separate parameter %% calculation of potential electron transport rate po0 = Kp./(Kf+Kd+Kp); % dark photochemistry fraction (Genty et al., 1989) Je = 0.5*po0 .* Q; % electron transport rate %% calculation of the intersection of enzyme and light limited curves % this is the original Farquhar model gam = 0.5 ./spfy .*O; %[bar] compensation point [bar] %% calculation of internal CO2 concentration, photosynthesis RH = eb./satvap(T-273.15); % a = 5; % D0 = 5; % gs0 = 1E-6; switch Type case 'C3' Ci = max(.3*Cs,Cs.*(1-1./(m.*RH))); Vc = Vcmax.*(Ci-gam)./((Kc .* (1+O./Ko)) + Ci); Vs = Vcmo/2 .* 1.8.^qt; % effcon = 0.2; otherwise %C4 %if biochem_in.A == -999 Ci = max(.1*Cs,Cs.*(1-1./(m.*RH))); %else % gs = gs0 + a*max(0,biochem_in.A)./((Cs-gam) .* (1+(1-RH).*satvap(T-273.15)./D0)); % Ci = Cs - biochem_in.A./gs; %end Vc = Vcmax; Vs = kp.*Ci; effcon = 0.17; % Berry and Farquhar (1978): 1/0.167 end Ve = Je.*(Ci-gam)./(Ci+2*gam) .* effcon; [a1,a2] = abc(atheta,-(Vc+Ve),Vc.*Ve); V = min(a1,a2).*(Ci>gam) + max(a1,a2).*(Ci<=gam); [a1,a2] = abc(0.98,-(V+Vs),V.*Vs); Ag = min(a1,a2); A = Ag - Rd; Ja = Ag ./((Ci-gam)./(Ci+2*gam))./effcon; % actual electron transport rate rcw = 0.625*(Cs-Ci)./A *rhoa/Mair*1E3 * 1e6 ./ p .* 1E3; rcw(A<=0) = 0.625*1E6; %% fluorescence (Replace this part by Magnani or other model if needed ps = po0.*Ja./Je; % this is the photochemical yield ps(isnan(ps)) = 0.8; [eta,qE,qQ,fs,fo,fm,fo0,fm0,Kn] = Fluorescencemodel(ps,Kp,Kf,Kd,Knparams); Kpa = ps./fs*Kf; %% convert back to ppm Ci = Ci*1e6 ./ p .* 1E3; %% Collect outputs biochem_out.A = A; biochem_out.Ci = Ci; biochem_out.eta = eta; biochem_out.rcw = rcw; biochem_out.qE = qE; biochem_out.fs = fs; biochem_out.Kn = Kn; biochem_out.fo0 = fo0; biochem_out.fm0 = fm0; biochem_out.fo = fo; biochem_out.fm = fm; biochem_out.qQ = qQ; biochem_out.Vcmax = Vcmax; biochem_out.Kp = Kpa; biochem_out.ps = ps; biochem_out.Ja = Ja; biochem_in.A = A; return; %%% end of function biochemical %% abc formula function [x2,x1] = abc(a,b,c) if a == 0 x1 = -c./b; x2 = x1; else x1 = (-b+sqrt(b.^2-4.*a.*c))./(2.*a); x2 = (-b-sqrt(b.^2-4.*a.*c))./(2.*a); end return; %%% end of abc formula function [eta,qE,qQ,fs,fo,fm,fo0,fm0,Kn] = Fluorescencemodel(ps,Kp,Kf,Kd,Knparams) po0 = Kp./(Kf+Kd+Kp); % dark photochemistry fraction (Genty et al., 1989) x = 1-ps./po0 ; % degree of light saturation Kno = Knparams(1); alpha = Knparams(2); beta = Knparams(3); % using exp(-beta) expands the interesting region between 0-1 %beta = exp(-beta); x_alpha = x.^alpha; % this is the most expensive operation in this fn; doing it twice almost doubles the time spent here (MATLAB 2013b doesn't optimize the duplicate code) Kn = Kno * (1+beta).* x_alpha./(beta + x_alpha); fo0 = Kf./(Kf+Kp+Kd); % dark adapted fluorescence yield Fo fo = Kf./(Kf+Kp+Kd+Kn); % dark adapted fluorescence yield Fo fm = Kf./(Kf +Kd+Kn); % light adapted fluorescence yield Fm fm0 = Kf./(Kf +Kd); % light adapted fluorescence yield Fm fs = fm.*(1-ps); eta = fs./fo0; qQ = 1-(fs-fo)./(fm-fo); % photochemical quenching qE = 1-(fm-fo)./(fm0-fo0); % non-photochemical quenching eta = (1+5)/5*eta-1/5; return
github
zhangyaonju/SCOPE-master
progressbar.m
.m
SCOPE-master/SCOPE_v1.xx/code/progressbar.m
11,767
utf_8
06705e480618e134da62478338e8251c
function progressbar(varargin) % Description: % progressbar() provides an indication of the progress of some task using % graphics and text. Calling progressbar repeatedly will update the figure and % automatically estimate the amount of time remaining. % This implementation of progressbar is intended to be extremely simple to use % while providing a high quality user experience. % % Features: % - Can add progressbar to existing m-files with a single line of code. % - Supports multiple bars in one figure to show progress of nested loops. % - Optional labels on bars. % - Figure closes automatically when task is complete. % - Only one figure can exist so old figures don't clutter the desktop. % - Remaining time estimate is accurate even if the figure gets closed. % - Minimal execution time. Won't slow down code. % - Randomized color. When a programmer gets bored... % % Example Function Calls For Single Bar Usage: % progressbar % Initialize/reset % progressbar(0) % Initialize/reset % progressbar('Label') % Initialize/reset and label the bar % progressbar(0.5) % Update % progressbar(1) % Close % % Example Function Calls For Multi Bar Usage: % progressbar(0, 0) % Initialize/reset two bars % progressbar('A', '') % Initialize/reset two bars with one label % progressbar('', 'B') % Initialize/reset two bars with one label % progressbar('A', 'B') % Initialize/reset two bars with two labels % progressbar(0.3) % Update 1st bar % progressbar(0.3, []) % Update 1st bar % progressbar([], 0.3) % Update 2nd bar % progressbar(0.7, 0.9) % Update both bars % progressbar(1) % Close % progressbar(1, []) % Close % progressbar(1, 0.4) % Close % % Notes: % For best results, call progressbar with all zero (or all string) inputs % before any processing. This sets the proper starting time reference to % calculate time remaining. % Bar color is choosen randomly when the figure is created or reset. Clicking % the bar will cause a random color change. % % Demos: % % Single bar % m = 500; % progressbar % Init single bar % for i = 1:m % pause(0.01) % Do something important % progressbar(i/m) % Update progress bar % end % % % Simple multi bar (update one bar at a time) % m = 4; % n = 3; % p = 100; % progressbar(0,0,0) % Init 3 bars % for i = 1:m % progressbar([],0) % Reset 2nd bar % for j = 1:n % progressbar([],[],0) % Reset 3rd bar % for k = 1:p % pause(0.01) % Do something important % progressbar([],[],k/p) % Update 3rd bar % end % progressbar([],j/n) % Update 2nd bar % end % progressbar(i/m) % Update 1st bar % end % % % Fancy multi bar (use labels and update all bars at once) % m = 4; % n = 3; % p = 100; % progressbar('Monte Carlo Trials','Simulation','Component') % Init 3 bars % for i = 1:m % for j = 1:n % for k = 1:p % pause(0.01) % Do something important % % Update all bars % frac3 = k/p; % frac2 = ((j-1) + frac3) / n; % frac1 = ((i-1) + frac2) / m; % progressbar(frac1, frac2, frac3) % end % end % end % % Author: % Steve Hoelzer % % Revisions: % 2002-Feb-27 Created function % 2002-Mar-19 Updated title text order % 2002-Apr-11 Use floor instead of round for percentdone % 2002-Jun-06 Updated for speed using patch (Thanks to waitbar.m) % 2002-Jun-19 Choose random patch color when a new figure is created % 2002-Jun-24 Click on bar or axes to choose new random color % 2002-Jun-27 Calc time left, reset progress bar when fractiondone == 0 % 2002-Jun-28 Remove extraText var, add position var % 2002-Jul-18 fractiondone input is optional % 2002-Jul-19 Allow position to specify screen coordinates % 2002-Jul-22 Clear vars used in color change callback routine % 2002-Jul-29 Position input is always specified in pixels % 2002-Sep-09 Change order of title bar text % 2003-Jun-13 Change 'min' to 'm' because of built in function 'min' % 2003-Sep-08 Use callback for changing color instead of string % 2003-Sep-10 Use persistent vars for speed, modify titlebarstr % 2003-Sep-25 Correct titlebarstr for 0% case % 2003-Nov-25 Clear all persistent vars when percentdone = 100 % 2004-Jan-22 Cleaner reset process, don't create figure if percentdone = 100 % 2004-Jan-27 Handle incorrect position input % 2004-Feb-16 Minimum time interval between updates % 2004-Apr-01 Cleaner process of enforcing minimum time interval % 2004-Oct-08 Seperate function for timeleftstr, expand to include days % 2004-Oct-20 Efficient if-else structure for sec2timestr % 2006-Sep-11 Width is a multiple of height (don't stretch on widescreens) % 2010-Sep-21 Major overhaul to support multiple bars and add labels % persistent progfig progdata lastupdate % Get inputs if nargin > 0 input = varargin; ninput = nargin; else % If no inputs, init with a single bar input = {0}; ninput = 1; end % If task completed, close figure and clear vars, then exit if input{1} == 1 if ishandle(progfig) delete(progfig) % Close progress bar end clear progfig progdata lastupdate % Clear persistent vars drawnow return end % Init reset flag resetflag = false; % Set reset flag if first input is a string if ischar(input{1}) resetflag = true; end % Set reset flag if all inputs are zero if input{1} == 0 % If the quick check above passes, need to check all inputs if all([input{:}] == 0) && (length([input{:}]) == ninput) resetflag = true; end end % Set reset flag if more inputs than bars if ninput > length(progdata) resetflag = true; end % If reset needed, close figure and forget old data if resetflag if ishandle(progfig) delete(progfig) % Close progress bar end progfig = []; progdata = []; % Forget obsolete data end % Create new progress bar if needed if ishandle(progfig) else % This strange if-else works when progfig is empty (~ishandle() does not) % Define figure size and axes padding for the single bar case height = 0.03; width = height * 8; hpad = 0.02; vpad = 0.25; % Figure out how many bars to draw nbars = max(ninput, length(progdata)); % Adjust figure size and axes padding for number of bars heightfactor = (1 - vpad) * nbars + vpad; height = height * heightfactor; vpad = vpad / heightfactor; % Initialize progress bar figure left = (1 - width) / 2; bottom = (1 - height) / 2; progfig = figure(... 'Units', 'normalized',... 'Position', [left bottom width height],... 'NumberTitle', 'off',... 'Resize', 'off',... 'MenuBar', 'none' ); % Initialize axes, patch, and text for each bar left = hpad; width = 1 - 2*hpad; vpadtotal = vpad * (nbars + 1); height = (1 - vpadtotal) / nbars; for ndx = 1:nbars % Create axes, patch, and text bottom = vpad + (vpad + height) * (nbars - ndx); progdata(ndx).progaxes = axes( ... 'Position', [left bottom width height], ... 'XLim', [0 1], ... 'YLim', [0 1], ... 'Box', 'on', ... 'ytick', [], ... 'xtick', [] ); progdata(ndx).progpatch = patch( ... 'XData', [0 0 0 0], ... 'YData', [0 0 1 1] ); progdata(ndx).progtext = text(0.99, 0.5, '', ... 'HorizontalAlignment', 'Right', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); progdata(ndx).proglabel = text(0.01, 0.5, '', ... 'HorizontalAlignment', 'Left', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); if ischar(input{ndx}) set(progdata(ndx).proglabel, 'String', input{ndx}) input{ndx} = 0; end % Set callbacks to change color on mouse click set(progdata(ndx).progaxes, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progpatch, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progtext, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).proglabel, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) % Pick a random color for this patch changecolor([], [], progdata(ndx).progpatch) % Set starting time reference if ~isfield(progdata(ndx), 'starttime') || isempty(progdata(ndx).starttime) progdata(ndx).starttime = clock; end end % Set time of last update to ensure a redraw lastupdate = clock - 1; end % Process inputs and update state of progdata for ndx = 1:ninput if ~isempty(input{ndx}) progdata(ndx).fractiondone = input{ndx}; progdata(ndx).clock = clock; end end % Enforce a minimum time interval between graphics updates myclock = clock; if abs(myclock(6) - lastupdate(6)) < 0.01 % Could use etime() but this is faster return end % Update progress patch for ndx = 1:length(progdata) set(progdata(ndx).progpatch, 'XData', ... [0, progdata(ndx).fractiondone, progdata(ndx).fractiondone, 0]) end % Update progress text if there is more than one bar if length(progdata) > 1 for ndx = 1:length(progdata) set(progdata(ndx).progtext, 'String', ... sprintf('%1d%%', floor(100*progdata(ndx).fractiondone))) end end % Update progress figure title bar if progdata(1).fractiondone > 0 runtime = etime(progdata(1).clock, progdata(1).starttime); timeleft = runtime / progdata(1).fractiondone - runtime; timeleftstr = sec2timestr(timeleft); titlebarstr = sprintf('%2d%% %s remaining', ... floor(100*progdata(1).fractiondone), timeleftstr); else titlebarstr = ' 0%'; end set(progfig, 'Name', titlebarstr) % Force redraw to show changes drawnow % Record time of this update lastupdate = clock; % ------------------------------------------------------------------------------ function changecolor(h, e, progpatch) %#ok<INUSL> % Change the color of the progress bar patch % Prevent color from being too dark or too light colormin = 1.5; colormax = 2.8; thiscolor = rand(1, 3); while (sum(thiscolor) < colormin) || (sum(thiscolor) > colormax) thiscolor = rand(1, 3); end set(progpatch, 'FaceColor', thiscolor) % ------------------------------------------------------------------------------ function timestr = sec2timestr(sec) % Convert a time measurement from seconds into a human readable string. % Convert seconds to other units w = floor(sec/604800); % Weeks sec = sec - w*604800; d = floor(sec/86400); % Days sec = sec - d*86400; h = floor(sec/3600); % Hours sec = sec - h*3600; m = floor(sec/60); % Minutes sec = sec - m*60; s = floor(sec); % Seconds % Create time string if w > 0 if w > 9 timestr = sprintf('%d week', w); else timestr = sprintf('%d week, %d day', w, d); end elseif d > 0 if d > 9 timestr = sprintf('%d day', d); else timestr = sprintf('%d day, %d hr', d, h); end elseif h > 0 if h > 9 timestr = sprintf('%d hr', h); else timestr = sprintf('%d hr, %d min', h, m); end elseif m > 0 if m > 9 timestr = sprintf('%d min', m); else timestr = sprintf('%d min, %d sec', m, s); end else timestr = sprintf('%d sec', s); end
github
zhangyaonju/SCOPE-master
biochemical_MD12.m
.m
SCOPE-master/SCOPE_v1.xx/code/biochemical_MD12.m
25,299
utf_8
88ceb939a207d7f9a5771afca4788999
function biochem_out = biochemical_MD12(biochem_in) %[A,Ci,eta] = biochemical_VCM(Cs,Q,T,eb,O,p,Vcmo,m,Type,Rdparam,stress,Tyear,beta,qLs,NPQs) % Date: 21 Sep 2012 % Update: 28 Jun 2013 Adaptation for use of Farquhar model of C3 photosynthesis (Farquhar et al 1980) % 18 Jul 2013 Inclusion of von Caemmerer model of C4 photosynthesis (von Caemmerer 2000, 2013) % 15 Aug 2013 Modified computation of CO2-limited electron transport in C4 species for consistency with light-limited value % 22 Oct 2013 Included effect of qLs on Jmax and electron transport; value of kNPQs re-scaled in input as NPQs % % Authors: Federico Magnani, with contributions from Christiaan van der Tol % % This function calculates: % - CO2 concentration in intercellular spaces (umol/mol == ppmv) % - leaf net photosynthesis (umol/m2/s) of C3 or C4 species % - fluorescence yield of a leaf (fraction of reference fluorescence yield in dark-adapted and un-stressed leaf) % % Usage: % function [A,Cs,eb,f,rcw] = biochemical(C,Cs,Q,T,ea,eb,O,p,Vcmo,gcparam,Type,tempcor,ra,Tparams,Rdparam,stressfactor,Tyear,beta,qLs,NPQs) % the function was tested for Matlab 7.2.0.232 (R2006a) % % Input (units are important; when not otherwise specified, mol refers to mol C): % Cs % [umol/mol] CO2 concentration at leaf surface % Q % [uE/m2/s] photochemically active radiation absorbed by the leaf % T % [oC or K] leaf temperature % eb % [hPa] vapour pressure in leaf boundary layer % O % [mmol/mol] ambient O2 concentration % p % [Pa] air pressure % Vcmo % [umol/m2/s] maximum carboxylation capacity % m % [mol/mol] Ball-Berry coefficient 'm' for stomatal regulation % Type % [] text parameter, either 'C3' for C3 or any other text for C4 % Rdparam % [mol/mol] respiration at reference temperature as fraction of Vcmax % stress % [] optional input: stress factor to reduce Vcmax (for example soil moisture, leaf age). Default value = 1 (no stress). % Tyear % [oC] mean annual temperature % beta % [] fraction of photons partitioned to PSII (0.507 for C3, 0.4 for C4; Yin et al. 2006; Yin and Struik 2012) % qLs % [] fraction of functional reaction centres (Porcar-Castell 2011) % NPQs % [s-1] rate constant of sustained thermal dissipation, normalized to (kf+kD) (=kNPQs'; Porcar-Castell 2011) % % Note: always use the prescribed units. Temperature can be either oC or K % Note: input can be single numbers, vectors, or n-dimensional matrices % Note: For consistency reasons, in C4 photosynthesis electron transport rates under CO2-limited conditions are computed by inverting the equation % applied for light-limited conditions(Ubierna et al 2013). A discontinuity would result when computing J from ATP requirements of Vp and Vco, as a % fixed electron transport partitioning is assumed for light-limited conditions % % Output: % A % [umol/m2/s] net assimilation rate of the leaves % Ci % [umol/mol] CO2 concentration in intercellular spaces (assumed to be the same as at carboxylation sites in C3 species) % eta % [] amplification factor to be applied to PSII fluorescence yield spectrum % relative to the dark-adapted, un-stressed yield calculated with either Fluspect or FluorMODleaf %--------------------------------------------------------------------------------------------------------- %% Start p=biochem_in.p.*1e2; m=biochem_in.m; O=biochem_in.O; Type=biochem_in.Type; Tyear=biochem_in.Tyear; beta=biochem_in.beta; qLs=biochem_in.qLs; NPQs=biochem_in.NPQs; stress=biochem_in.stressfactor; Cs=biochem_in.Cs; Q=biochem_in.Q; T=biochem_in.T; eb=biochem_in.eb; Vcmo=biochem_in.Vcmo; Rdparam=biochem_in.Rdparam; %% Global and site-specific constants R = 8.31; % [J/K/mol] universal gas constant %--------------------------------------------------------------------------------------------------------- %% Unit conversion and computation of environmental variables T = T+273.15*(T<100); % [K] convert temperatures to K if not already RH = eb./satvap(T-273.15); % [] relative humidity (decimal) Cs = Cs .* p .*1E-11; % [bar] 1E-6 to convert from ppm to fraction, 1E-5 to convert from Pa to bar O = O .* p .*1E-08; % [bar] 1E-3 to convert from mmol/mol to fraction, 1E-5 to convert from Pa to bar %--------------------------------------------------------------------------------------------------------- %% Define photosynthetic parameters (at reference temperature) SCOOP = 2862.; % [mol/mol] Relative Rubisco specificity for CO2 vs O2 at ref temp (Cousins et al. 2010) Rdopt = Rdparam * Vcmo; % [umol/m2/s] dark respiration at ref temperature from correlation with Vcmo switch Type case 'C3' % C3 species Jmo = Vcmo * 2.68; % [umol/m2/s] potential e-transport at ref temp from correlation with Vcmo (Leuning 1997) otherwise % C4 species Jmo = Vcmo * 40/6; % [umole-/m2/s] maximum electron transport rate (ratio as in von Caemmerer 2000) Vpmo = Vcmo * 2.33; % [umol/m2/s] maximum PEP carboxylase activity (Yin et al. 2011) Vpr = 80; % [umol/m2/s] PEP regeneration rate, constant (von Caemmerer 2000) gbs = (0.0207*Vcmo+0.4806)*1000.; % [umol/m2/s] bundle sheath conductance to CO2 (Yin et al. 2011) x = 0.4; % [] partitioning of electron transport to mesophyll (von Caemmerer 2013) alpha = 0; % [] bundle sheath PSII activity (=0 in maize/sorghum; >=0.5 in other cases; von Caemmerer 2000) end %--------------------------------------------------------------------------------------------------------- %% Parameters for temperature corrections TREF = 25+273.15; % [K] reference temperature for photosynthetic processes HARD = 46.39; % [kJ/mol] activation energy of Rd CRD = 1000.*HARD/(R*TREF); % [] scaling factor in RD response to temperature HAGSTAR = 37.83; % [kJ/mol] activation energy of Gamma_star CGSTAR = 1000.*HAGSTAR/(R*TREF); % [] scaling factor in GSTAR response to temperature switch Type case 'C3' % C3 species HAJ = 49.88; % [kJ/mol] activation energy of Jm (Kattge & Knorr 2007) HDJ = 200; % [kJ/mol] deactivation energy of Jm (Kattge & Knorr 2007) DELTASJ = (-0.75*Tyear+660)/1000; % [kJ/mol/K] entropy term for J (Kattge and Knorr 2007) HAVCM = 71.51; % [kJ/mol] activation energy of Vcm (Kattge and Knorr 2007) HDVC = 200; % [kJ/mol] deactivation energy of Vcm (Kattge & Knorr 2007) DELTASVC= (-1.07*Tyear+668)/1000; % [kJ/mol/K] entropy term for Vcmax (Kattge and Knorr 2007) KCOP = 404.9; % [umol/mol] Michaelis-Menten constant for CO2 at ref temp (Bernacchi et al 2001) HAKC = 79.43; % [kJ/mol] activation energy of Kc (Bernacchi et al 2001) KOOP = 278.4; % [mmol/mol] Michaelis-Menten constant for O2 at ref temp (Bernacchi et al 2001) HAKO = 36.38; % [kJ/mol] activation energy of Ko (Bernacchi et al 2001) otherwise % C4 species (values can be different as noted by von Caemmerer 2000) HAJ = 77.9; % [kJ/mol] activation energy of Jm (Massad et al 2007) HDJ = 191.9; % [kJ/mol] deactivation energy of Jm (Massad et al 2007) DELTASJ = 0.627; % [kJ/mol/K] entropy term for Jm (Massad et al 2007). No data available on acclimation to temperature. HAVCM = 67.29; % [kJ/mol] activation energy of Vcm (Massad et al 2007) HDVC = 144.57; % [kJ/mol] deactivation energy of Vcm (Massad et al 2007) DELTASVC= 0.472; % [kJ/mol/K] entropy term for Vcm (Massad et al 2007). No data available on acclimation to temperature. HAVPM = 70.37; % [kJ/mol] activation energy of Vpm (Massad et al 2007) HDVP = 117.93; % [kJ/mol] deactivation energy of Vpm (Massad et al 2007) DELTASVP= 0.376; % [kJ/mol/K] entropy term for Vpm (Massad et al 2007). No data available on acclimation to temperature. KCOP = 944.; % [umol/mol] Michaelis-Menten constant for CO2 at ref temp (Chen et al 1994; Massad et al 2007) Q10KC = 2.1; % [] Q10 for temperature response of Kc (Chen et al 1994; Massad et al 2007) KOOP = 633.; % [mmol/mol] Michaelis-Menten constant for O2 at ref temp (Chen et al 1994; Massad et al 2007) Q10KO = 1.2; % [] Q10 for temperature response of Ko (Chen et al 1994; Massad et al 2007) KPOP = 82.; % [umol/mol] Michaelis-Menten constant of PEP carboxylase at ref temp (Chen et al 1994; Massad et al 2007) Q10KP = 2.1; % [] Q10 for temperature response of Kp (Chen et al 1994; Massad et al 2007) end %--------------------------------------------------------------------------------------------------------- %% Corrections for effects of temperature and non-stomatal limitations dum1 = R./1000.*T; % [kJ/mol] dum2 = R./1000.*TREF; % [kJ/mol] Rd = Rdopt.*exp(CRD-HARD./dum1); % [umol/m2/s] mitochondrial respiration rates adjusted for temperature (Bernacchi et al. 2001) SCO = SCOOP./exp(CGSTAR-HAGSTAR./dum1); % [] Rubisco specificity for CO2 adjusted for temperature (Bernacchi et al. 2001) Jmax = Jmo .* exp(HAJ.*(T-TREF)./(TREF*dum1)); Jmax = Jmax.*(1.+exp((TREF*DELTASJ-HDJ)./dum2)); Jmax = Jmax./(1.+exp((T.*DELTASJ-HDJ)./dum1)); % [umol e-/m2/s] max electron transport rate at leaf temperature (Kattge and Knorr 2007; Massad et al. 2007) Vcmax = Vcmo .* exp(HAVCM.*(T-TREF)./(TREF*dum1)); Vcmax = Vcmax.*(1+exp((TREF*DELTASVC-HDVC)/dum2)); Vcmax = Vcmax./(1+exp((T.*DELTASVC-HDVC)./dum1)); % [umol/m2/s] max carboxylation rate at leaf temperature (Kattge and Knorr 2007; Massad et al. 2007) switch Type case 'C3' % C3 species CKC = 1000.*HAKC/(R*TREF); % [] scaling factor in KC response to temperature Kc = KCOP.*exp(CKC-HAKC./dum1).*1e-11.*p; % [bar] Michaelis constant of carboxylation adjusted for temperature (Bernacchi et al. 2001) CKO = 1000.*HAKO/(R*TREF); % [] scaling factor in KO response to temperature Ko = KOOP.*exp(CKO-HAKO./dum1).*1e-8.*p; % [bar] Michaelis constant of oxygenation adjusted for temperature (Bernacchi et al. 2001) otherwise % C4 species Vpmax = Vpmo .* exp(HAVPM.*(T-TREF)./(TREF*dum1)); Vpmax = Vpmax.*(1+exp((TREF*DELTASVP-HDVP)/dum2)); Vpmax = Vpmax./(1+exp((T.*DELTASVP-HDVP)./dum1));% [umol/m2/s] max carboxylation rate at leaf temperature (Massad et al. 2007) Kc = KCOP.*Q10KC .^ ((T-TREF)/10.)*1e-11*p; % [bar] Michaelis constant of carboxylation temperature corrected (Chen et al 1994; Massad et al 2007) Ko = KOOP.*Q10KO .^ ((T-TREF)/10.)*1e-8*p; % [bar] Michaelis constant of oxygenation temperature corrected (Chen et al 1994; Massad et al 2007) Kp = KPOP.*Q10KP .^ ((T-TREF)/10.)*1e-11*p; % [bar] Michaelis constant of PEP carboxyl temperature corrected (Chen et al 1994; Massad et al 2007) end %--------------------------------------------------------------------------------------------------------- %% Define electron transport and fluorescence parameters kf = 3.E7; % [s-1] rate constant for fluorescence kD = 1.E8; % [s-1] rate constant for thermal deactivation at Fm kd = 1.95E8; % [s-1] rate constant of energy dissipation in closed RCs (for theta=0.7 under un-stressed conditions) po0max = 0.88; % [mol e-/E] maximum PSII quantum yield, dark-acclimated in the absence of stress (Pfundel 1998) kPSII = (kD+kf) * po0max/(1.-po0max); % [s-1] rate constant for photochemisty (Genty et al. 1989) fo0 = kf./(kf+kPSII+kD); % [E/E] reference dark-adapted PSII fluorescence yield under un-stressed conditions kps = kPSII * qLs; % [s-1] rate constant for photochemisty under stressed conditions (Porcar-Castell 2011) kNPQs = NPQs * (kf+kD); % [s-1] rate constant of sustained thermal dissipation (Porcar-Castell 2011) kds = kd * qLs; kDs = kD + kNPQs; Jms = Jmax * qLs; % [umol e-/m2/s] potential e-transport rate reduced for PSII photodamage po0 = kps ./(kps+kf+kDs); % [mol e-/E] maximum PSII quantum yield, dark-acclimated in the presence of stress THETA = (kps-kds)./(kps+kf+kDs); % [] convexity factor in J response to PAR %--------------------------------------------------------------------------------------------------------- %% Calculation of electron transport rate Q2 = beta * Q * po0; J = (Q2+Jms-sqrt((Q2+Jms).^2-4*THETA.*Q2.*Jms))./(2*THETA); % [umol e-/m2/s] electron transport rate under light-limiting conditions %--------------------------------------------------------------------------------------------------------- %% Calculation of net photosynthesis switch Type case 'C3' % C3 species, based on Farquhar model (Farquhar et al. 1980) GSTAR = 0.5*O./SCO; % [bar] CO2 compensation point in the absence of mitochondrial respiration Ci = max(GSTAR,Cs.*(1-1.6./(m.*RH*stress))); % [bar] intercellular CO2 concentration from Ball-Berry model (Ball et al. 1987) Cc = Ci; % [bar] CO2 concentration at carboxylation sites (neglecting mesophyll resistance) Wc = Vcmax .* Cc ./ (Cc + Kc .* (1+O./Ko)); % [umol/m2/s] RuBP-limited carboxylation Wj = J.*Cc ./ (4.5*Cc + 10.5*GSTAR); % [umol/m2/s] electr transp-limited carboxyl W = min(Wc,Wj); % [umol/m2/s] carboxylation rate Ag = (1 - GSTAR./Cc) .*W; % [umol/m2/s] gross photosynthesis rate A = Ag - Rd; % [umol/m2/s] net photosynthesis rate Ja = J.*W ./Wj; % [umole-/m2/s] actual linear electron transport rate otherwise % C4 species, based on von Caemmerer model (von Caemmerer 2000) Ci = max(9.9e-6*(p*1e-5),Cs.*(1-1.6./(m.*RH*stress))); % [bar] intercellular CO2 concentration from Ball-Berry model (Ball et al. 1987) Cm = Ci; % [bar] mesophyll CO2 concentration (neglecting mesophyll resistance) Rs = 0.5 .* Rd; % [umol/m2/s] bundle sheath mitochondrial respiration (von Caemmerer 2000) Rm = Rs; % [umol/m2/s] mesophyll mitochondrial respiration gam = 0.5./SCO; % [] half the reciprocal of Rubisco specificity for CO2 Vpc = Vpmax .* Cm./(Cm+Kp); % [umol/m2/s] PEP carboxylation rate under limiting CO2 (saturating PEP) Vp = min(Vpc,Vpr); % [umol/m2/s] PEP carboxylation rate % Complete model proposed by von Caemmerer (2000) dum1 = alpha/0.047; % dummy variables, to reduce computation time dum2 = Kc./Ko; dum3 = Vp-Rm+gbs.*Cm; dum4 = Vcmax-Rd; dum5 = gbs.*Kc.*(1+O./Ko); dum6 = gam.*Vcmax; dum7 = x*J./2. - Rm + gbs.*Cm; dum8 = (1.-x).*J./3.; dum9 = dum8 - Rd; dum10 = dum8 + Rd * 7/3; a = 1. - dum1 .* dum2; b = -(dum3+dum4+dum5+dum1.*(dum6+Rd.*dum2)); c = dum4.*dum3-dum6.*gbs*O+Rd.*dum5; Ac = (-b - sqrt(b.^2-4.*a.*c))./(2.*a); % [umol/m2/s] CO2-limited net photosynthesis a = 1.- 7./3.*gam.*dum1; b = -(dum7+dum9 + gbs.*gam.*O.*7./3. + dum1.*gam.*dum10); c = dum7.*dum9 - gbs.*gam.*O.*dum10; Aj = (-b - sqrt(b.^2-4.*a.*c))./(2.*a); % [umol/m2/s] light-limited net photosynthesis (assuming that an obligatory Q cycle operates) A = min(Ac,Aj); % [umol/m2/s] net photosynthesis Ja = J; % [umole-/m2/s] actual electron transport rate, CO2-limited if any(A==Ac) %IPL 03/09/2013 ind=A==Ac; a(ind) = x.*(1-x)./6./A(ind); b(ind) = (1-x)/3.*(gbs(ind)./A(ind).*(Cm(ind)-Rm(ind)./gbs(ind)-gam(ind).*O)-1-alpha.*gam(ind)./0.047)-x./2.*(1.+Rd(ind)./A(ind)); c(ind) = (1+Rd(ind)./A(ind)).*(Rm(ind)-gbs(ind).*Cm(ind)-7.*gbs(ind).*gam(ind).*O./3)+(Rd(ind)+A(ind)).*(1-7.*alpha.*gam(ind)./3./0.047); Ja(ind) = (-b(ind) + sqrt(b(ind).^2-4.*a(ind).*c(ind)))./(2.*a(ind)); % [umole-/m2/s] actual electron transport rate, CO2-limited end % Simplified model (von Caemmerer 2000), should be chosen ONLY if computation times are excessive % dum3 = Vp-Rm+gbs*Cm; % dum4 = Vcmax-Rd; % dum7 = x*J./2. - Rm + gbs*Cm; % dum8 = (1.-x)*J./3.; % dum9 = dum8 - Rd; % % Ac = min(dum3,dum4); % [umol/m2/s] light saturated CO2 assimilation rate % Aj = min(dum7,dum9); % [umol/m2/s] light-limited CO2 assimilation rate % % A = min(Ac,Aj); % [umol/m2/s] net photosynthesis rate % Ja = J .* A./ Aj; % [umole-/m2/s] actual electron transport rate (simple empirical formulation based on results) end %--------------------------------------------------------------------------------------------------------- %% Calculation of PSII quantum yield and fluorescence ps = Ja ./(beta.*Q); % [mol e-/E] PSII photochemical quantum yield [fs] = MD12(ps,Ja,Jms,kps,kf,kds,kDs); % [E/E] PSII fluorescence yield eta = fs./fo0; % [] scaled PSII fluorescence yield %% JP add rhoa = 1.2047; % [kg m-3] specific mass of air Mair = 28.96; % [g mol-1] molecular mass of dry air rcw = 0.625*(Cs-Ci)./A *rhoa/Mair*1E3 * 1e6 ./ p .* 1E5; rcw(A<=0) = 0.625*1E6; %% convert back to ppm Ci = Ci*1e6 ./ p .* 1E5; %% biochem_out.A = A; biochem_out.Ci = Ci; biochem_out.ps = ps; biochem_out.eta = eta; biochem_out.fs = fs; biochem_out.rcw = rcw; biochem_out.qE = rcw*NaN; % dummy output, to be consistent with SCOPE return; %%% end of function biochemical %--------------------------------------------------------------------------------------------------------- %% MD12 algorithm for the computation of fluorescence yield function [fs] = MD12(ps,Ja,Jms,kps,kf,kds,kDs) fs1 = ps .* (kf./kps) ./ (1. - Ja./Jms); % [E/E] PSII fluorescence yield under CO2-limited conditions par1 = kps./(kps-kds); % [E/E] empirical parameter in the relationship under light-limited conditions par2 = par1.* (kf+kDs+kds)./kf; % [E/E] empirical parameter in the relationship under light-limited conditions fs2 = (par1-ps)./par2; % [E/E] PSII fluorescence yield under light-limited conditions fs = min(fs1,fs2); % [E/E] PSII fluorescence yield % Sources: % Ball J. T., I. E. Woodrow and J. A. Berry. (1987) A model predicting stomatal conductance and its contribution to the control of photosynthesis % under different environmental conditions. In: Progress in Photosynthesis Research (Ed. J. Biggens), p. 221-224, The Netherlands:Martinus Nijhoff. % Bernacchi C.J., E.L. Singsaas, C. Pimentel, A.R. Portis and S.P. Long (2001) Improved temperature response functions for models of Rubisco-limited % photosynthesis. Plant Cell Envir 24:253-259. % Bernacchi C.J., C. Pimentel and S.P. Long (2003) In vivo temperature response functions of parameters required to model RuBP-limited photosynthesis. % Plant Cell Envir 26 (9):1419-1430. % Chen D.X., M.B. Coughenour, A.K. Knapp, and C.E. Owensby (1994) Mathematical simulation of C4 grass photosynthesis in ambient and elevated CO2. % Ecol.Model. 73:63-80, 1994. % Cousins A.B., O. Ghannoum, S. von Caemmerer, and M.R. Badger (2010) Simultaneous determination of Rubisco carboxylase and oxygenase kinetic parameters % in Triticum aestivum and Zea mays using membrane inlet mass spectrometry. Plant Cell Envir 33:444-452. % Farquhar G.D., S. von Caemmerer and J.A. Berry (1980) A biochemical model of photosynthetic CO2 assimilation in leaves of C3 species. Planta 149:78-90. % Genty B., J.-M. Briantais and N. R. Baker (1989) The relationship between quantum yield of photosynthetic electron transport and quenching of % chlorophyll fluorescence. Biochimica et Biophysica Acta 990:87-92. % Kattge J. and W. Knorr (2007) Temperature acclimation in a biochemical model of photosynthesis: a reanalysis of data from 36 species. % Plant Cell Envir 30:1176-1190. % Leuning R. (1997) Scaling to a common temperature improves the correlation between the photosynthesis parameters Jmax and Vcmax. % J.Exp.Bot. 48 (307):345-347. % Massad R.S., A. Tuzet and O. Bethenod (2007) The effect of temperature on C4-type leaf photosynthesis parameters. Plant Cell Envir 30:1191-1204. % Pfundel E. (1998) Estimating the contribution of Photosystem I to total leaf chlorophyll fluorescence. Photosynthesis Research 56:185-195. % Porcar-Castell A. (2011) A high-resolution portrait of the annual dynamics of photochemical and non-photochemical quenching in needles of Pinus sylvestris. % Physiol.Plant. 143:139-153. % von Caemmerer S. (2000) Biochemical Models of Leaf Photosynthesis, Canberra:CSIRO Publishing. % von Caemmerer S. (2013) Steady-state models of photosynthesis. Plant Cell Envir, in press. % Yin X., Z. Sun, P.C. Struik, P.E.L. van der Putten, W. van Ieperen and J. Harbinson (2011) Using a biochemical C4 photosynthesis model and combined % gas exchange and chlorophyll fluorescence measurements to estimate bundle-sheath conductance of maize leaves differing in age and nitrogen content. % Plant Cell Envir 34:2183-2199. %
github
zhangyaonju/SCOPE-master
RTMt_sb_new.m
.m
SCOPE-master/SCOPE_v1.xx/code/RTMt_sb_new.m
10,022
utf_8
c94416960d57cf938cdf22c7fe8686c3
function [rad] = RTMt_sb(spectral,rad,soil,leafopt,canopy,gap,angles,Tcu,Tch,Tsu,Tsh,obsdir) % function 'RTMt_sb' calculates total outgoing radiation in hemispherical % direction and total absorbed radiation per leaf and soil component. % Radiation is integrated over the whole thermal spectrum with % Stefan-Boltzman's equation. This function is a simplified version of % 'RTMt_planck', and is less time consuming since it does not do the % calculation for each wavelength separately. % % Authors: Wout Verhoef and Christiaan van der Tol ([email protected]) % date: 5 Nov 2007 % update: 13 Nov 2007 % 16 Nov 2007 CvdT improved calculation of net radiation % 27 Mar 2008 JT added directional calculation of radiation % 24 Apr 2008 JT Introduced dx as thickness of layer (see parameters) % 31 Oct 2008 JT introduced optional directional calculation % 31 Oct 2008 JT changed initialisation of F1 and F2 -> zeros % 07 Nov 2008 CvdT changed layout % 16 Mar 2009 CvdT removed Tbright calculation % Feb 2013 WV introduces structures for version 1.40 % % Table of contents of the function % 0 preparations % 0.0 globals % 0.1 initialisations % 0.2 parameters % 0.3 geometric factors of Observer % 0.4 geometric factors associated with extinction and scattering % 0.5 geometric factors to be used later with rho and tau % 0.6 fo for all leaf angle/azumith classes % 1 calculation of upward and downward fluxes % 2 total net fluxes % Appendix A. Stefan-Boltzmann % % usage: % [rad] = RTMt_sb(options,spectral,rad,soil,leafopt,canopy,gap,angles,Tcu,Tch,Tsu,Tsh) % % Most input and output are structures. These structures are further % specified in a readme file. The temperatures Tcu, Tch, Tsu and Tsh are % variables. % % Input: % options calculation options % spectral information about wavelengths and resolutions % rad a large number of radiative fluxes: spectrally distributed % and integrated, and canopy radiative transfer coefficients % soil soil properties % leafopt leaf optical properties % canopy canopy properties (such as LAI and height) % gap probabilities of direct light penetration and viewing % angles viewing and observation angles % Tcu Temperature of sunlit leaves (oC), [13x36x60] % Tch Temperature of shaded leaves (oC), [13x36x60] % Tsu Temperature of sunlit soil (oC), [1] % Tsh Temperature of shaded soil (oC), [1] % % Output: % rad a large number of radiative fluxes: spectrally distributed % and integrated, and canopy radiative transfer coefficients. % Here, thermal fluxes are added %% 0.0 globals global constants %% 0.1 parameters IT = find(spectral.wlS == 10000); % Take 10 microns as representative wavelength for the thermal deg2rad = constants.deg2rad; nl = canopy.nlayers; lidf = canopy.lidf; litab = canopy.litab; lazitab = canopy.lazitab; nlazi = length(lazitab); nlinc = length(litab); nlori = nlinc * nlazi; tto = angles.tto; psi = angles.psi; Ps = gap.Ps; K = gap.K; layers = 1:nl; rho = leafopt.refl(IT); % [nwl] Leaf/needle reflection tau = leafopt.tran(IT); % [nwl] Leaf/needle transmission rs = soil.refl(IT); % [nwl] Soil reflectance epsc = 1-rho-tau; % [nwl] Emissivity vegetation epss = 1-rs; % [nwl] Emissivity soil crit = max(1E-2); % [1] Desired minimum accuracy LAI = canopy.LAI; dx = 1/nl; iLAI = LAI*dx; %% 0.2 initialiations Rnhc = zeros(nl,1); % [nl] Rnuc = zeros(size(Tcu)); % [13,36,nl] %% 0.3 geometric factors of observer if obsdir cos_tto = cos(tto*deg2rad); % [1] cos observation angle sin_tto = sin(tto*deg2rad); % [1] sin observation angle end %% 0.4 geometric factors associated with extinction and scattering cos_ttl = cos(litab*deg2rad); if obsdir sin_ttl = sin(litab*deg2rad); cos_ttlo= cos((lazitab-psi)*deg2rad); end bfli = cos_ttl.^2; bf = bfli'*lidf; %% 0.5 geometric factors to be used later with rho and tau, f1 f2 of pag 304: ddb = 0.5*(1+bf); % f1^2 + f2^2 ddf = 0.5*(1-bf); % 2*f1*f2 if obsdir dob = 0.5*(K+bf); % fo*f1 dof = 0.5*(K-bf); % fo*f1 end %% 0.6 fo for all leaf angle/azumith classes if obsdir Co = cos_ttl*cos_tto; % [nli] pag 305 So = sin_ttl*sin_tto; % [nli] pag 305 cos_deltao = Co*ones(1,nlazi) + So*cos_ttlo;% [nli, nlazi] projection of leaves in in direction of sun (pag 125-126) fo = cos_deltao/abs(cos_tto);% [nli, nlazi] leaf area projection factors in direction of observation end %% 1. calculation of upward and downward fluxes pag 305 sigb = ddb*rho + ddf*tau; % [nwlt] Diffuse backscatter scattering coefficient sigf = ddf*rho + ddb*tau; % [nwlt] Diffuse forward scattering coefficient if obsdir vb = dob*rho + dof*tau; % [nwlt] Directional backscatter scattering coefficient for diffuse incidence vf = dof*rho + dob*tau; % [nwlt] Directional forward scattering coefficient for diffuse incidence end a = 1-sigf; % [nwlt] Attenuation m = sqrt(a*a-sigb*sigb);% [nwlt] rinf = (a-m)/sigb; % [nwlt] Reflection coefficient for infinite thick canopy rinf2 = rinf*rinf; % [nwlt] fHs = (1-rinf2)*(1-rs)/(1-rinf*rs); fHc = iLAI*m*(1-rinf); fbottom = (rs-rinf)/(1-rs*rinf); %1.1 radiance by components Hcsu3 = Stefan_Boltzmann(Tcu);% Radiance by sunlit leaves Hcsh = Stefan_Boltzmann(Tch);% Radiance by shaded leaves Hssu = Stefan_Boltzmann(Tsu);% Radiance by sunlit soil Hssh = Stefan_Boltzmann(Tsh);% Radiance by shaded soil % 1.2 radiance by leaf layers Hv and by soil Hs (modified by JAK 2015-01) v1 = repmat( 1/size(Hcsu3, 2), 1, size(Hcsu3, 2)); % vector for computing the mean Hcsu2 = reshape(Hcsu3, size(Hcsu3, 1), []); % create a block matrix from the 3D array Hcsu = (v1 * reshape(Hcsu2'*lidf, size(Hcsu3, 2), []))'; % compute column means for each level Hc = Hcsu.*Ps(1:nl) + Hcsh.*(1-Ps(1:nl)); % hemispherical emittance by leaf layers Hs = Hssu.*Ps(nl+1) + Hssh.*(1-Ps(nl+1)); % hemispherical emittance by soil surface % 1.3 Diffuse radiation cont = 1; % continue iteration (1:yes, 0:no) counter = 0; % number of iterations F1 = zeros(nl+1,1); F2 = zeros(nl+1,1); F1top = 0; while cont F1topn = -rinf*F2(1); F1(1) = F1topn; for j = 1:nl F1(j+1) = F1(j)*(1-m*iLAI)+ fHc*Hc(j); end F2(nl+1) = fbottom*F1(nl+1) + fHs*Hs; for j = nl:-1:1 F2(j) = F2(j+1)*(1-m*iLAI) + fHc*Hc(j); end cont = abs(F1topn-F1top)>crit; F1top = F1topn; counter = counter + 1; end Emin = (F1+rinf*F2)/(1-rinf2); Eplu = (F2+rinf*F1)/(1-rinf2); % 1.4 Directional radiation if obsdir piLo1 = iLAI*epsc*K*Hcsh'*(gap.Po(1:nl)-gap.Pso(1:nl)); % directional emitted radation by shaded leaves % JAK 2015-01: replaced earlier loop by this: all-at-once with more efficient mean absfo_rep = repmat(abs(fo), 1, nl); piLo2 = iLAI*epsc*(v1 * reshape( (Hcsu2.*absfo_rep)'*lidf, size(Hcsu3, 2), []))'.*gap.Pso(1:nl); % compute column means for each level % WV 2015-03: Alternative without using repmat %Qso = (gap.Pso(layers)+gap.Pso(layers+1))/2 %out = Qso * reshape(absfo,1,nlori); %piLo2 = iLAI*epsc * mean(reshape(out .* reshape(Hcsu3,nl,nlori),nl,nlinc,nlazi),3) * lidf; piLo3 = iLAI*((vb*Emin(1:nl) + vf*Eplu(1:nl))'*gap.Po(1:nl)); % directional scattered radiation by vegetation for diffuse incidence piLo4 = epss*Hssh*(gap.Po(nl+1)-gap.Pso(nl+1)); % directional emitted radiation by shaded soil piLo5 = epss*Hssu*gap.Pso(nl+1); % directional emitted radiation by sunlit soil piLo6 = rs*Emin(nl+1)*gap.Po(nl+1); % directional scattered radiation by soil for diffuse incidence [1] piLot = piLo1 + sum(piLo2) + piLo3 + piLo4 + piLo5 + piLo6; else piLot = NaN; end Lot = piLot/pi; %% 2. total net fluxes % net radiation per component, in W m-2 (leaf or soil surface) for j = 1:nl Rnuc(:,:,j) = (Emin(j) + Eplu(j+1) - 2*Hcsu3(:,:,j))*epsc; % sunlit leaf Rnhc(j) = (Emin(j) + Eplu(j+1) - 2*Hcsh(j))*epsc; % shaded leaf end Rnus = (Emin(nl+1) - Hssu)*epss; % sunlit soil Rnhs = (Emin(nl+1) - Hssh)*epss; % shaded soil %% 3. Write the output to the rad structure rad.Emint = Emin; rad.Eplut = Eplu; rad.Eoutte = Eplu(1); rad.Lot = Lot; rad.Rnuct = Rnuc; rad.Rnhct = Rnhc; rad.Rnust = Rnus; rad.Rnhst = Rnhs; return %% Appendix A. Stefan-Boltzmann function H = Stefan_Boltzmann(T_C) global constants; C2K = constants.C2K; sigmaSB = constants.sigmaSB; H = sigmaSB*(T_C + C2K).^4; return
github
zhangyaonju/SCOPE-master
RTMo.m
.m
SCOPE-master/SCOPE_v1.xx/code/RTMo.m
29,666
utf_8
d59333054d811ca125ec7398fca68705
function [rad,gap,profiles] = RTMo(spectral,atmo,soil,leafopt,canopy,angles,meteo,rad,options) %% function RTMo % calculates the spectra of hemisperical and directional observed visible % and thermal radiation (fluxes E and radiances L), as well as the single % and bi-directional gap probabilities % % the function does not require any non-standard Matlab functions. No % changes to the code have to be made to operate the function for a % particular canopy. All necessary parameters and variables are input or % global and need to be specified elsewhere. % % Authors: Wout Verhoef ([email protected]) % Christiaan van der Tol ([email protected]) % Joris Timmermans ([email protected]) % % updates: 10 Sep 2007 (CvdT) - calculation of Rn % 5 Nov 2007 - included observation direction % 12 Nov 2007 - included abs. PAR spectrum output % - improved calculation efficiency % 13 Nov 2007 - written readme lines % 11 Feb 2008 (WV&JT) - changed Volscat % (JT) - small change in calculation Po,Ps,Pso % - introduced parameter 'lazitab' % - changed nomenclature % - Appendix IV: cosine rule % 04 Aug 2008 (JT) - Corrections for Hotspot effect in the probabilities % 05 Nov 2008 (CvdT) - Changed layout % 04 Jan 2011 (JT & CvdT) - Included Pso function (Appendix IV) % - removed the analytical function (for checking) % 02 Oct 2012 (CvdT) - included incident PAR in output % % Jan/Feb 2013 (WV) - Major revision towards SCOPE version 1.40: % - Parameters passed using structures % - Improved interface with MODTRAN atmospheric data % - Now also calculates 4-stream % reflectances rso, rdo, rsd and rdd % analytically % Apri 2013 (CvT) - improvements in variable names % and descriptions % % Table of contents of the function % % 0. Preparations % 0.1 parameters % 0.2 initialisations % 1. Geometric quantities % 1.1 general geometric quantities % 1.2 geometric factors associated with extinction and scattering % 1.3 geometric factors to be used later with rho and tau % 1.4 solar irradiance factor for all leaf orientations % 1.5 probabilities Ps, Po, Pso % 2. Calculation of upward and downward fluxes % 3. Outgoing fluxes, hemispherical and in viewing direction, spectrum % 4. Net fluxes, spectral and total, and incoming fluxes % A1 functions J1 and J2 (introduced for stable solutions) % A2 function volscat % A3 function e2phot % A4 function Pso % % references: %{1} Verhoef (1998), 'Theory of radiative transfer models applied in % optical remote sensing of vegetation canopies'. PhD Thesis Univ. Wageninegn %{2} Verhoef, W., Jia, L., Xiao, Q. and Su, Z. (2007) Unified optical - % thermal four - stream radiative transfer theory for homogeneous % vegetation canopies. IEEE Transactions on geoscience and remote % sensing, 45,6. %{3} Verhoef (1985), 'Earth Observation Modeling based on Layer Scattering % Matrices', Remote sensing of Environment, 17:167-175 % % Usage: % function [rad,gap,profiles] = RTMo(spectral,atmo,soil,leafopt,canopy,angles,meteo,rad,options) % % The input and output are structures. These structures are further % specified in a readme file. % % Input: % spectral information about wavelengths and resolutions % atmo MODTRAN atmospheric parameters % soil soil properties % leafopt leaf optical properties % canopy canopy properties (such as LAI and height) % angles viewing and observation angles % meteo has the meteorological variables. Is only used to correct % the total irradiance if a specific value is provided % instead of the usual Modtran output. % rad initialization of the structure of the output 'rad' % options simulation options. Here, the option % 'calc_vert_profiles' is used, a boolean that tells whether % or not to output data of 60 layers separately. % % Output: % gap probabilities of direct light penetration and viewing % rad a large number of radiative fluxes: spectrally distributed % and integrated, and canopy radiative transfer coefficients. % profiles vertical profiles of radiation variables such as absorbed % PAR. %% 0. Preparations deg2rad = pi/180; wl = spectral.wlS'; % SCOPE wavelengths as a column-vector nwl = length(wl); wlP = spectral.wlP; wlT = spectral.wlT; wlPAR = spectral.wlPAR'; % PAR wavelength range minPAR = min(wlPAR); maxPAR = max(wlPAR); Ipar = find(wl>=minPAR & wl<=maxPAR); % Indices for PAR wavelenghts within wl tts = angles.tts; % solar zenith angle tto = angles.tto; % observer zenith angle psi = angles.psi; % relative azimuth anglee nl = canopy.nlayers; % number of canopy layers (60) litab = canopy.litab; % SAIL leaf inclibation angles lazitab = canopy.lazitab; % leaf azimuth angles relative to the sun nli = canopy.nlincl; % numler of leaf inclinations (13) nlazi = canopy.nlazi; % number of azimuth angles (36) LAI = canopy.LAI; % leaf area index lidf = canopy.lidf; % leaf inclination distribution function x = canopy.x; % all levels except for the top dx = 1/nl; kChlrel = leafopt.kChlrel; rho = leafopt.refl; % [nwl] leaf/needle reflection tau = leafopt.tran; % [nwl] leaf/needle transmission rs = soil.refl; % [nwl,nsoils] soil reflectance spectra epsc = 1-rho-tau; % [nwl] emissivity of leaves epss = 1-rs; % [nwl] emissivity of soil iLAI = LAI/nl; % [1] LAI of elementary layer xl = [0; x]; % [nl+1] all levels + soil % 0.2 initialisations (allocation of memory) Rndif = zeros(nl,1); % [nl+1] abs. diffuse rad soil+veg [Pdif,Pndif,Pndif_Cab,Rndif_PAR] = deal(zeros(nl,1)); % [nl] incident and net PAR veg [Emin_,Eplu_] = deal(zeros(nl+1,nwl)); % [nl+1,nwl] up and down diff. rad. [Rndif_] = zeros(nl,nwl); % [nl,nwl] abs diff and PAR veg. [Pndif_,Pndif_Cab_,Rndif_PAR_] = deal(zeros(nl,length(Ipar))); [Puc,Rnuc,Pnuc,Pnuc_Cab,Rnuc_PAR] = deal(zeros(nli,nlazi,nl)); % [nli,nlazi,nl] inc and net rad and PAR sunlit %% 1.0 Geometric quantities % 1.1 general geometric quantities % these variables are scalars cos_tts = cos(tts*deg2rad); % cos solar angle tan_tto = tan(tto*deg2rad); % tan observation angle cos_tto = cos(tto*deg2rad); % cos observation angle sin_tts = sin(tts*deg2rad); % sin solar angle tan_tts = tan(tts*deg2rad); % tan observation angle psi = abs(psi-360*round(psi/360)); % (to ensure that volscatt is symmetric for psi=90 and psi=270) dso = sqrt(tan_tts.^2 + tan_tto.^2 - 2*tan_tts.*tan_tto.*cos(psi*deg2rad)); % 1.2 geometric factors associated with extinction and scattering [chi_s,chi_o,frho,ftau]=volscat(tts,tto,psi,litab); % volume scattering cos_ttlo = cos(lazitab*deg2rad); % [1,36] cos leaf azimuth angles cos_ttli = cos(litab*deg2rad); % [13] cos leaf angles sin_ttli = sin(litab*deg2rad); % [13] sinus leaf angles ksli = chi_s./cos_tts; % [13] p306{1} extinction coefficient in direction of sun per leaf angle koli = chi_o./cos_tto; % [13] p307{1} extinction coefficient in direction of observer per leaf angle sobli = frho*pi/(cos_tts*cos_tto); % [13] pag 309{1} area scattering coefficient fractions sofli = ftau*pi/(cos_tts*cos_tto); % [13] pag 309{1} bfli = cos_ttli.^2; % [13] %integration over angles (using a vector inproduct) -> scalars k = ksli'*lidf; % pag 306{1} extinction coefficient in direction of sun. K = koli'*lidf; % pag 307{1} extinction coefficient in direction of observer bf = bfli'*lidf; % sob = sobli'*lidf; % weight of specular2directional back scatter coefficient sof = sofli'*lidf; % weight of specular2directional forward scatter coefficient % 1.3 geometric factors to be used later with rho and tau, f1 f2 of pag 304: % these variables are scalars sdb = 0.5*(k+bf); % fs*f1 sdf = 0.5*(k-bf); % fs*f2 weight of specular2diffuse foward scatter coefficient ddb = 0.5*(1+bf); % f1^2+f2^2 weight of diffuse2diffuse back scatter coefficient ddf = 0.5*(1-bf); % 2*f1*f2 weight of diffuse2diffuse forward scatter coefficient dob = 0.5*(K+bf); % fo*f1 weight of diffuse2directional back scatter coefficient dof = 0.5*(K-bf); % fo*f2 weight of diffuse2directional forward scatter coefficient % 1.4 solar irradiance factor for all leaf orientations Cs = cos_ttli*cos_tts; % [nli] pag 305 modified by Joris Ss = sin_ttli*sin_tts; % [nli] pag 305 modified by Joris cos_deltas = Cs*ones(1,nlazi) + Ss*cos_ttlo; % [nli,nlazi] fs = abs(cos_deltas/cos_tts); % [nli,nlazi] pag 305 % 1.5 probabilities Ps, Po, Pso Ps = exp(k*xl*LAI); % [nl+1] p154{1} probability of viewing a leaf in solar dir Po = exp(K*xl*LAI); % [nl+1] p154{1} probability of viewing a leaf in observation dir Ps(1:nl) = Ps(1:nl) *(1-exp(-k*LAI*dx))/(k*LAI*dx); % Correct Ps/Po for finite dx Po(1:nl) = Po(1:nl) *(1-exp(-K*LAI*dx))/(K*LAI*dx); % Correct Ps/Po for finite dx q = canopy.hot; Pso = zeros(size(Po)); for j=1:length(xl) Pso(j,:)= quad(@(y)Psofunction(K,k,LAI,q,dso,y),xl(j)-dx,xl(j))/dx; %#ok<FREMO> end Pso(Pso>Po)= min([Po(Pso>Po),Ps(Pso>Po)],[],2); %takes care of rounding error Pso(Pso>Ps)= min([Po(Pso>Ps),Ps(Pso>Ps)],[],2); %takes care of rounding error gap.Pso = Pso; %% 2. Calculation of upward and downward fluxes % the following are vectors with lenght nwl sigb = ddb*rho + ddf*tau; % [nwl] sigmab, p305{1} diffuse backscatter scattering coefficient for diffuse incidence sigf = ddf*rho + ddb*tau; % [nwl] sigmaf, p305{1} diffuse forward scattering coefficient for forward incidence sb = sdb*rho + sdf*tau; % [nwl] sb, p305{1} diffuse backscatter scattering coefficient for specular incidence sf = sdf*rho + sdb*tau; % [nwl] sf, p305{1} diffuse forward scattering coefficient for specular incidence vb = dob*rho + dof*tau; % [nwl] vb, p305{1} directional backscatter scattering coefficient for diffuse incidence vf = dof*rho + dob*tau; % [nwl] vf, p305{1} directional forward scattering coefficient for diffuse incidence w = sob*rho + sof*tau; % [nwl] w, p309{1} bidirectional scattering coefficent (directional-directional) a = 1-sigf; % [nwl] attenuation m = sqrt(a.^2-sigb.^2); % [nwl] rinf = (a-m)./sigb; % [nwl] rinf2 = rinf.*rinf; % [nwl] % direct solar radiation J1k = calcJ1(-1, m,k,LAI); % [nwl] J2k = calcJ2( 0, m,k,LAI); % [nwl] J1K = calcJ1(-1, m,K,LAI); % [nwl] % added for calculation of rdo J2K = calcJ2( 0, m,K,LAI); % [nwl] % added for calculation of rdo e1 = exp(-m*LAI); % [nwl] e2 = e1.^2; % [nwl] re = rinf.*e1; % [nwl] denom = 1-rinf2.*e2; % [nwl] s1 = sf+rinf.*sb; s2 = sf.*rinf+sb; v1 = vf+rinf.*vb; v2 = vf.*rinf+vb; Pss = s1.*J1k; % [nwl] Qss = s2.*J2k; % [nwl] Poo = v1.*J1K; % (nwl) % added for calculation of rdo Qoo = v2.*J2K; % [nwl] % added for calculation of rdo tau_ss = exp(-k*LAI); % [1] tau_oo = exp(-K*LAI); % [1] Z = (1 - tau_ss * tau_oo)/(K + k); % needed for analytic rso tau_dd = (1-rinf2).*e1 ./denom; % [nwl] rho_dd = rinf.*(1-e2) ./denom; % [nwl] tau_sd = (Pss-re.*Qss) ./denom; % [nwl] tau_do = (Poo-re.*Qoo) ./denom; % [nwl] rho_sd = (Qss-re.*Pss) ./denom; % [nwl] rho_do = (Qoo-re.*Poo) ./denom; % (nwl) T1 = v2.*s1.*(Z-J1k*tau_oo)./(K+m)+v1.*s2.*(Z-J1K*tau_ss)./(k+m); T2 = -(Qoo.*rho_sd+Poo.*tau_sd).*rinf; rho_sod = (T1+T2)./(1-rinf2); rho_sos = w * sum(Pso(1:nl))*iLAI; rho_so = rho_sod + rho_sos; Pso2w = Pso(nl+1); % Analytical rso following SAIL rso = rho_so + rs * Pso2w ... + ((tau_sd+tau_ss*rs.*rho_dd)*tau_oo+(tau_sd+tau_ss).*tau_do) ... .*rs./denom; % Extract MODTRAN atmosphere parameters at the SCOPE wavelengths t1 = atmo.M(:,1); t3 = atmo.M(:,2); t4 = atmo.M(:,3); t5 = atmo.M(:,4); t12 = atmo.M(:,5); t16 = atmo.M(:,6); % radiation fluxes, downward and upward (these all have dimenstion [nwl] % first calculate hemispherical reflectances rsd and rdd according to SAIL % these are assumed for the reflectance of the surroundings % rdo is computed with SAIL as well denom = 1-rs.*rho_dd; % SAIL analytical reflectances rsd = rho_sd + (tau_ss + tau_sd).*rs.*tau_dd./denom; rdd = rho_dd + tau_dd.*rs.*tau_dd./denom; rdo = rho_do + (tau_oo + tau_do).*rs.*tau_dd./denom; % assume Fd of surroundings = 0 for the momemnt % initial guess of temperature of surroundings from Ta; Fd = zeros(nwl,1); Ls = Planck(wl,atmo.Ta+273.15); % Solar and sky irradiance using 6 atmosperic functions %keyboard Esun_ = pi*t1.*t4; Esky_ = pi./(1-t3.*rdd).*(t1.*(t5+t12.*rsd)+Fd+(1-rdd).*Ls.*t3+t16); % fractional contributions of Esun and Esky to total incident radiation in % optical and thermal parts of the spectrum [fEsuno,fEskyo,fEsunt,fEskyt] = deal(0*Esun_); %initialization J_o = wl<3000; %find optical spectrum Esunto = 0.001 * Sint(Esun_(J_o),wl(J_o)); %Calculate optical sun fluxes (by Integration), including conversion mW >> W Eskyto = 0.001 * Sint(Esky_(J_o),wl(J_o)); %Calculate optical sun fluxes (by Integration) Etoto = Esunto + Eskyto; %Calculate total fluxes fEsuno(J_o) = Esun_(J_o)/Etoto; %fraction of contribution of Sun fluxes to total light fEskyo(J_o) = Esky_(J_o)/Etoto; %fraction of contribution of Sky fluxes to total light J_t = wl>=3000; %find thermal spectrum Esuntt = 0.001 * Sint(Esun_(J_t),wl(J_t)); %Themal solar fluxes Eskytt = 0.001 * Sint(Esky_(J_t),wl(J_t)); %Thermal Sky fluxes Etott = Eskytt + Esuntt; %Total fEsunt(J_t) = Esun_(J_t)/Etott; %fraction from Esun fEskyt(J_t) = Esky_(J_t)/Etott; %fraction from Esky if meteo.Rin ~= -999 Esun_(J_o) = fEsuno(J_o)*meteo.Rin; Esky_(J_o) = fEskyo(J_o)*meteo.Rin; Esun_(J_t) = fEsunt(J_t)*meteo.Rli; Esky_(J_t) = fEskyt(J_t)*meteo.Rli; end Eplu_1 = rs.*((tau_ss+tau_sd).*Esun_+tau_dd.*Esky_)./denom; Eplu0 = rho_sd.*Esun_ + rho_dd.*Esky_ + tau_dd.*Eplu_1; Emin_1 = tau_sd.*Esun_ + tau_dd.*Esky_ + rho_dd.*Eplu_1; delta1 = Esky_ - rinf.*Eplu0; delta2 = Eplu_1 - rinf.*Emin_1; % calculation of the fluxes in the canopy for i = 1:nwl J1kx = calcJ1(xl,m(i),k,LAI); % [nl] J2kx = calcJ2(xl,m(i),k,LAI); % [nl] F1 = Esun_(i)*J1kx*(sf(i)+rinf(i)*sb(i)) + delta1(i)*exp( m(i)*LAI*xl); %[nl] F2 = Esun_(i)*J2kx*(sb(i)+rinf(i)*sf(i)) + delta2(i)*exp(-m(i)*LAI*(xl+1)); %[nl] Emin_(:,i) = (F1+rinf(i)*F2)/(1-rinf2(i));% [nl,nwl] Eplu_(:,i) = (F2+rinf(i)*F1)/(1-rinf2(i));% [nl,nwl] end % Incident and absorbed solar radiation Psun = 0.001 * Sint(e2phot(wlPAR*1E-9,Esun_(Ipar)),wlPAR); % Incident solar PAR in PAR units Asun = 0.001 * Sint(Esun_.*epsc,wl); % Total absorbed solar radiation Pnsun = 0.001 * Sint(e2phot(wlPAR*1E-9,Esun_(Ipar).*epsc(Ipar)),wlPAR); % Absorbed solar radiation in PAR range in moles m-2 s-1 Rnsun_PAR = 0.001 * Sint(Esun_(Ipar).*epsc(Ipar),wlPAR); Pnsun_Cab = 0.001 * Sint(e2phot(wlPAR*1E-9,kChlrel(Ipar).*Esun_(Ipar).*epsc(Ipar)),wlPAR); % Absorbed solar radiation by Cab in PAR range in moles m-2 s-1 %% 3. outgoing fluxes, hemispherical and in viewing direction, spectrum % (CvdT 071105: compared with analytical solution: is OK) % hemispherical, spectral Eout_ = Eplu_(1,:)'; % [nwl] % in viewing direction, spectral piLoc_ = (vb.*(Emin_(1:nl,:)'*Po(1:nl)) +... vf.*(Eplu_(1:nl,:)'*Po(1:nl)) +... w.*Esun_*sum(Pso(1:nl)))*iLAI; piLos_ = rs.*Emin_(nl+1,:)'*Po(nl+1) + rs.*Esun_*Pso(nl+1); piLo_ = piLoc_ + piLos_; % [nwl] Lo_ = piLo_/pi; % up and down and hemispherical out, cumulative over wavelenght IwlP = spectral.IwlP; IwlT = spectral.IwlT; Eouto = 0.001 * Sint(Eout_(IwlP),wlP); % [1] hemispherical out, in optical range (W m-2) Eoutt = 0.001 * Sint(Eout_(IwlT),wlT); % [1] hemispherical out, in thermal range (W m-2) %% 4. net fluxes, spectral and total, and incoming fluxes % incident PAR at the top of canopy, spectral and spectrally integrated P_ = e2phot(wl(Ipar)*1E-9,(Esun_(Ipar)+Esky_(Ipar))); P = .001 * Sint(P_,wlPAR); % total direct radiation (incident and net) per leaf area (W m-2 leaf) Pdir = fs * Psun; % [13 x 36] incident Rndir = fs * Asun; % [13 x 36] net Pndir = fs * Pnsun; % [13 x 36] net PAR Pndir_Cab = fs * Pnsun_Cab; % [13 x 36] net PAR Cab Rndir_PAR = fs * Rnsun_PAR; % [13 x 36] net PAR energy units % canopy layers, diffuse radiation for j = 1:nl % diffuse incident radiation for the present layer 'j' (mW m-2 um-1) E_ = .5*(Emin_(j,:) + Emin_(j+1,:)+ Eplu_(j,:)+ Eplu_(j+1,:)); % incident PAR flux, integrated over all wavelengths (moles m-2 s-1) Pdif(j) = .001 * Sint(e2phot(wlPAR*1E-9,E_(Ipar)'),wlPAR); % [nl] , including conversion mW >> W % net radiation (mW m-2 um-1) and net PAR (moles m-2 s-1 um-1), per wavelength Rndif_(j,:) = E_.*epsc'; % [nl,nwl] Net (absorbed) radiation by leaves Pndif_(j,:) = .001 *(e2phot(wlPAR*1E-9, Rndif_(j,Ipar)'))'; % [nl,nwl] Net (absorbed) as PAR photons Pndif_Cab_(j,:) = .001 *(e2phot(wlPAR*1E-9, kChlrel(Ipar).*Rndif_(j,Ipar)'))'; % [nl,nwl] Net (absorbed) as PAR photons by Cab Rndif_PAR_(j,:) = Rndif_(j,Ipar); % [nl,nwlPAR] Net (absorbed) as PAR energy % net radiation (W m-2) and net PAR (moles m-2 s-1), integrated over all wavelengths Rndif(j) = .001 * Sint(Rndif_(j,:),wl); % [nl] Full spectrum net diffuse flux Pndif(j) = Sint(Pndif_(j,Ipar),wlPAR); % [nl] Absorbed PAR Pndif_Cab(j) = Sint(Pndif_Cab_(j,Ipar),wlPAR); % [nl] Absorbed PAR by Cab integrated Rndif_PAR(j) = .001 * Sint(Rndif_PAR_(j,Ipar),wlPAR); % [nl] Absorbed PAR by Cab integrated end % soil layer, direct and diffuse radiation Rndirsoil = .001 * Sint(Esun_.*epss,wl); % [1] Absorbed solar flux by the soil Rndifsoil = .001 * Sint(Emin_(nl+1,:).*epss',wl); % [1] Absorbed diffuse downward flux by the soil (W m-2) % net (n) radiation R and net PAR P per component: sunlit (u), shaded (h) soil(s) and canopy (c), % [W m-2 leaf or soil surface um-1] Rnhc = Rndif; % [nl] shaded leaves or needles Pnhc = Pndif; % [nl] shaded leaves or needles Pnhc_Cab = Pndif_Cab; % [nl] shaded leaves or needles Rnhc_PAR = Rndif_PAR; % [nl] shaded leaves or needles for j = 1:nl Puc(:,:,j) = Pdir + Pdif(j); % [13,36,nl] Total fluxes on sunlit leaves or needles Rnuc(:,:,j) = Rndir + Rndif(j); % [13,36,nl] Total fluxes on sunlit leaves or needles Pnuc(:,:,j) = Pndir + Pndif(j); % [13,36,nl] Total fluxes on sunlit leaves or needles Pnuc_Cab(:,:,j) = Pndir_Cab + Pndif_Cab(j);% [13,36,nl] Total fluxes on sunlit leaves or needles Rnuc_PAR(:,:,j) = Rndir_PAR + Rndif_PAR(j);% [13,36,nl] Total fluxes on sunlit leaves or needles end Rnhs = Rndifsoil; % [1] shaded soil Rnus = Rndifsoil + Rndirsoil; % [1] sunlit soil %% if options.calc_vert_profiles [Pnu1d ] = meanleaf(canopy,Pnuc, 'angles'); % [nli,nlo,nl] mean net radiation sunlit leaves [Pnu1d_Cab ] = meanleaf(canopy,Pnuc_Cab, 'angles'); % [nli,nlo,nl] mean net radiation sunlit leaves profiles.Pn1d = ((1-Ps(1:nl)).*Pnhc + Ps(1:nl).*(Pnu1d)); %[nl] mean photos leaves, per layer profiles.Pn1d_Cab = ((1-Ps(1:nl)).*Pnhc_Cab + Ps(1:nl).*(Pnu1d_Cab)); %[nl] mean photos leaves, per layer else profiles = struct; end %% place output in structure rad gap.k = k; gap.K = K; gap.Ps = Ps; gap.Po = Po; rad.rsd = rsd; rad.rdd = rdd; rad.rdo = rdo; rad.rso = rso; rad.vb = vb; rad.vf = vf; rad.Esun_ = Esun_; % [2162x1 double] incident solar spectrum (mW m-2 um-1) rad.Esky_ = Esky_; % [2162x1 double] incident sky spectrum (mW m-2 um-1) rad.inPAR = P; % [1 double] incident spectrally integrated PAR (moles m-2 s-1) rad.fEsuno = fEsuno; % [2162x1 double] normalized spectrum of direct light (optical) rad.fEskyo = fEskyo; % [2162x1 double] normalized spectrum of diffuse light (optical) rad.fEsunt = fEsunt; % [2162x1 double] normalized spectrum of direct light (thermal) rad.fEskyt = fEskyt; % [2162x1 double] normalized spectrum of diffuse light (thermal) rad.Eplu_ = Eplu_; % [61x2162 double] upward diffuse radiation in the canopy (mW m-2 um-1) rad.Emin_ = Emin_; % [61x2162 double] downward diffuse radiation in the canopy (mW m-2 um-1) rad.Lo_ = Lo_; % [2162x1 double] TOC radiance in observation direction (mW m-2 um-1 sr-1) rad.Eout_ = Eout_; % [2162x1 double] TOC upward radiation (mW m-2 um-1) rad.Eouto = Eouto; % [1 double] TOC spectrally integrated upward optical ratiation (W m-2) rad.Eoutt = Eoutt; % [1 double] TOC spectrally integrated upward thermal ratiation (W m-2) rad.Rnhs = Rnhs; % [1 double] net radiation (W m-2) of shaded soil rad.Rnus = Rnus; % [1 double] net radiation (W m-2) of sunlit soil rad.Rnhc = Rnhc; % [60x1 double] net radiation (W m-2) of shaded leaves rad.Rnuc = Rnuc; % [13x36x60 double] net radiation (W m-2) of sunlit leaves rad.Pnh = Pnhc; % [60x1 double] net PAR (moles m-2 s-1) of shaded leaves rad.Pnu = Pnuc; % [13x36x60 double] net PAR (moles m-2 s-1) of sunlit leaves rad.Pnh_Cab = Pnhc_Cab; % [60x1 double] net PAR absorbed by Cab (moles m-2 s-1) of shaded leaves rad.Pnu_Cab = Pnuc_Cab; % [13x36x60 double] net PAR absorbed by Cab (moles m-2 s-1) of sunlit leaves rad.Rnh_PAR = Rnhc_PAR; % [60x1 double] net PAR absorbed by Cab (moles m-2 s-1) of shaded leaves rad.Rnu_PAR = Rnuc_PAR; % [13x36x60 double] net PAR absorbed (W m-2) of sunlit rad.Etoto = Etoto; %% APPENDIX I functions J1 and J2 (introduced for numerically stable solutions) function J1 = calcJ1(x,m,k,LAI) if abs(m-k)>1E-3; J1 = (exp(m*LAI*x)-exp(k*LAI*x))./(k-m); else J1 = -.5*(exp(m*LAI*x)+exp(k*LAI*x))*LAI.*x.*(1-1/12*(k-m).^2*LAI^2.*x.^2); end return function J2 = calcJ2(x,m,k,LAI) J2 = (exp(k*LAI*x)-exp(-k*LAI)*exp(-m*LAI*(1+x)))./(k+m); return; %% APPENDIX II function volscat function [chi_s,chi_o,frho,ftau] = volscat(tts,tto,psi,ttli) %Volscatt version 2. %created by W. Verhoef %edited by Joris Timmermans to matlab nomenclature. % date: 11 February 2008 %tts [1] Sun zenith angle in degrees %tto [1] Observation zenith angle in degrees %psi [1] Difference of azimuth angle between solar and viewing position %ttli [ttli] leaf inclination array deg2rad = pi/180; nli = length(ttli); psi_rad = psi*deg2rad*ones(nli,1); cos_psi = cos(psi*deg2rad); % cosine of relative azimuth angle cos_ttli = cos(ttli*deg2rad); % cosine of normal of upperside of leaf sin_ttli = sin(ttli*deg2rad); % sine of normal of upperside of leaf cos_tts = cos(tts*deg2rad); % cosine of sun zenith angle sin_tts = sin(tts*deg2rad); % sine of sun zenith angle cos_tto = cos(tto*deg2rad); % cosine of observer zenith angle sin_tto = sin(tto*deg2rad); % sine of observer zenith angle Cs = cos_ttli*cos_tts; % p305{1} Ss = sin_ttli*sin_tts; % p305{1} Co = cos_ttli*cos_tto; % p305{1} So = sin_ttli*sin_tto; % p305{1} As = max([Ss,Cs],[],2); Ao = max([So,Co],[],2); bts = acos(-Cs./As); % p305{1} bto = acos(-Co./Ao); % p305{2} chi_o = 2/pi*((bto-pi/2).*Co + sin(bto).*So); chi_s = 2/pi*((bts-pi/2).*Cs + sin(bts).*Ss); delta1 = abs(bts-bto); % p308{1} delta2 = pi-abs(bts + bto - pi); % p308{1} Tot = psi_rad + delta1 + delta2; % pag 130{1} bt1 = min([psi_rad,delta1],[],2); bt3 = max([psi_rad,delta2],[],2); bt2 = Tot - bt1 - bt3; T1 = 2.*Cs.*Co + Ss.*So.*cos_psi; T2 = sin(bt2).*(2*As.*Ao + Ss.*So.*cos(bt1).*cos(bt3)); Jmin = ( bt2).*T1 - T2; Jplus = (pi-bt2).*T1 + T2; frho = Jplus/(2*pi^2); ftau = -Jmin /(2*pi^2); % pag.309 wl-> pag 135{1} frho = max([zeros(nli,1),frho],[],2); ftau = max([zeros(nli,1),ftau],[],2); return %% APPENDIX III function e2phot function molphotons = e2phot(lambda,E) %molphotons = e2phot(lambda,E) calculates the number of moles of photons %corresponding to E Joules of energy of wavelength lambda (m) global constants; A = constants.A; e = ephoton(lambda); photons = E./e; molphotons = photons./A; return; function E = ephoton(lambda) %E = phot2e(lambda) calculates the energy content (J) of 1 photon of %wavelength lambda (m) global constants; h = constants.h; % [J s] Planck's constant c = constants.c; % [m s-1] speed of light E = h*c./lambda; % [J] energy of 1 photon return; %% APPENDIX IV function Pso function pso = Psofunction(K,k,LAI,q,dso,xl) if dso~=0 alf = (dso/q) *2/(k+K); pso = exp((K+k)*LAI*xl + sqrt(K*k)*LAI/(alf )*(1-exp(xl*(alf ))));% [nl+1] factor for correlation of Ps and Po else pso = exp((K+k)*LAI*xl - sqrt(K*k)*LAI*xl);% [nl+1] factor for correlation of Ps and Po end
github
zhangyaonju/SCOPE-master
fluspect_bcar.m
.m
SCOPE-master/SCOPE_v1.xx/code/fluspect_bcar.m
9,764
utf_8
1d6d75758809d255fcab68e39cfc66f0
function [leafopt] = fluspect_bcar(spectral,leafbio,optipar) % % Fluspect simulated reflectance, transmittance and fluorescence of leaves % Copyright (C) 2015 Wout Verhoef and Christiaan van der Tol % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/>. % function [leafopt] = fluspect(spectral,leafbio,optipar) % calculates reflectance and transmittance spectra of a leaf using FLUSPECT, % plus four excitation-fluorescence matrices % % Authors: Wout Verhoef, Christiaan van der Tol ([email protected]), Joris Timmermans, % Date: 2007 % Update from PROSPECT to FLUSPECT: January 2011 (CvdT) % % Nov 2012 (CvdT) Output EF-matrices separately for PSI and PSII % 31 Jan 2013 (WV) Adapt to SCOPE v_1.40, using structures for I/O % 30 May 2013 (WV) Repair bug in s for non-conservative scattering % 24 Nov 2013 (WV) Simplified doubling routine % 25 Nov 2013 (WV) Restored piece of code that takes final refl and % tran outputs as a basis for the doubling routine % 03 Dec 2013 (WV) Major upgrade. Border interfaces are removed before % the fluorescence calculation and later added again % 23 Dec 2013 (WV) Correct a problem with N = 1 when calculating k % and s; a test on a = Inf was included % 01 Apr 2014 (WV) Add carotenoid concentration (Cca and Kca) % % usage: % [leafopt] = fluspect_b(spectral,leafbio,optipar) % % inputs: % Cab = leafbio.Cab; % Cca = leafbio.Cca; % Cw = leafbio.Cw; % Cdm = leafbio.Cdm; % Cs = leafbio.Cs; % N = leafbio.N; % fqe = leafbio.fqe; % % nr = optipar.nr; % Kdm = optipar.Kdm; % Kab = optipar.Kab; % Kca = optipar.Kca; % Kw = optipar.Kw; % Ks = optipar.Ks; % phiI = optipar.phiI; % phiII = optipar.phiII; % % outputs: % refl reflectance % tran transmittance % Mb backward scattering fluorescence matrix, I for PSI and II for PSII % Mf forward scattering fluorescence matrix, I for PSI and II for PSII %% parameters % fixed parameters for the fluorescence module ndub = 15; % number of doublings applied % Fluspect parameters Cab = leafbio.Cab; Cca = leafbio.Cca; Cw = leafbio.Cw; Cdm = leafbio.Cdm; Cs = leafbio.Cs; N = leafbio.N; fqe = leafbio.fqe; nr = optipar.nr; Kdm = optipar.Kdm; Kab = optipar.Kab; Kca = optipar.Kca; Kw = optipar.Kw; Ks = optipar.Ks; phiI = optipar.phiI; phiII = optipar.phiII; %% PROSPECT calculations Kall = (Cab*Kab + Cca*Kca + Cdm*Kdm + Cw*Kw + Cs*Ks)/N; % Compact leaf layer j = find(Kall>0); % Non-conservative scattering (normal case) t1 = (1-Kall).*exp(-Kall); t2 = Kall.^2.*expint(Kall); tau = ones(size(t1)); tau(j) = t1(j)+t2(j); kChlrel = zeros(size(t1)); kChlrel(j) = Cab*Kab(j)./(Kall(j)*N); talf = calctav(59,nr); ralf = 1-talf; t12 = calctav(90,nr); r12 = 1-t12; t21 = t12./(nr.^2); r21 = 1-t21; % top surface side denom = 1-r21.*r21.*tau.^2; Ta = talf.*tau.*t21./denom; Ra = ralf+r21.*tau.*Ta; % bottom surface side t = t12.*tau.*t21./denom; r = r12+r21.*tau.*t; % Stokes equations to compute properties of next N-1 layers (N real) % Normal case D = sqrt((1+r+t).*(1+r-t).*(1-r+t).*(1-r-t)); rq = r.^2; tq = t.^2; a = (1+rq-tq+D)./(2*r); b = (1-rq+tq+D)./(2*t); bNm1 = b.^(N-1); % bN2 = bNm1.^2; a2 = a.^2; denom = a2.*bN2-1; Rsub = a.*(bN2-1)./denom; Tsub = bNm1.*(a2-1)./denom; % Case of zero absorption j = find(r+t >= 1); Tsub(j) = t(j)./(t(j)+(1-t(j))*(N-1)); Rsub(j) = 1-Tsub(j); % Reflectance and transmittance of the leaf: combine top layer with next N-1 layers denom = 1-Rsub.*r; tran = Ta.*Tsub./denom; refl = Ra+Ta.*Rsub.*t./denom; leafopt.refl = refl; leafopt.tran = tran; leafopt.kChlrel = kChlrel; % From here a new path is taken: The doubling method used to calculate % fluoresence is now only applied to the part of the leaf where absorption % takes place, that is, the part exclusive of the leaf-air interfaces. The % reflectance (rho) and transmittance (tau) of this part of the leaf are % now determined by "subtracting" the interfaces Rb = (refl-ralf)./(talf.*t21+(refl-ralf).*r21); % Remove the top interface Z = tran.*(1-Rb.*r21)./(talf.*t21); % Derive Z from the transmittance rho = (Rb-r21.*Z.^2)./(1-(r21.*Z).^2); % Reflectance and transmittance tau = (1-Rb.*r21)./(1-(r21.*Z).^2).*Z; % of the leaf mesophyll layer t = tau; r = max(rho,0); % Avoid negative r % Derive Kubelka-Munk s and k I_rt = (r+t)<1; D(I_rt) = sqrt((1 + r(I_rt) + t(I_rt)) .* ... (1 + r(I_rt) - t(I_rt)) .* ... (1 - r(I_rt) + t(I_rt)) .* ... (1 - r(I_rt) - t(I_rt))); a(I_rt) = (1 + r(I_rt).^2 - t(I_rt).^2 + D(I_rt)) ./ (2*r(I_rt)); b(I_rt) = (1 - r(I_rt).^2 + t(I_rt).^2 + D(I_rt)) ./ (2*t(I_rt)); a(~I_rt) = 1; b(~I_rt) = 1; s = r./t; I_a = (a>1 & a~=Inf); s(I_a) = 2.*a(I_a) ./ (a(I_a).^2 - 1) .* log(b(I_a)); k = log(b); k(I_a) = (a(I_a)-1) ./ (a(I_a)+1) .* log(b(I_a)); kChl = kChlrel .* k; %% Fluorescence of the leaf mesophyll layer if fqe > 0 wle = spectral.wlE'; % excitation wavelengths, transpose to column wlf = spectral.wlF'; % fluorescence wavelengths, transpose to column wlp = spectral.wlP; % PROSPECT wavelengths, kept as a row vector minwle = min(wle); maxwle = max(wle); minwlf = min(wlf); maxwlf = max(wlf); % indices of wle and wlf within wlp Iwle = find(wlp>=minwle & wlp<=maxwle); Iwlf = find(wlp>=minwlf & wlp<=maxwlf); eps = 2^(-ndub); % initialisations te = 1-(k(Iwle)+s(Iwle)) * eps; tf = 1-(k(Iwlf)+s(Iwlf)) * eps; re = s(Iwle) * eps; rf = s(Iwlf) * eps; sigmoid = 1./(1+exp(-wlf/10)*exp(wle'/10)); % matrix computed as an outproduct % Other factor .5 deleted, since these are the complete efficiencies % for either PSI or PSII, not a linear combination [MfI, MbI] = deal(fqe(1) * ((.5*phiI( Iwlf))*eps) * kChl(Iwle)'.*sigmoid); [MfII, MbII] = deal(fqe(2) * ((.5*phiII(Iwlf))*eps) * kChl(Iwle)'.*sigmoid); Ih = ones(1,length(te)); % row of ones Iv = ones(length(tf),1); % column of ones % Doubling routine for i = 1:ndub xe = te./(1-re.*re); ten = te.*xe; ren = re.*(1+ten); xf = tf./(1-rf.*rf); tfn = tf.*xf; rfn = rf.*(1+tfn); A11 = xf*Ih + Iv*xe'; A12 = (xf*xe').*(rf*Ih + Iv*re'); A21 = 1+(xf*xe').*(1+rf*re'); A22 = (xf.*rf)*Ih+Iv*(xe.*re)'; MfnI = MfI .* A11 + MbI .* A12; MbnI = MbI .* A21 + MfI .* A22; MfnII = MfII .* A11 + MbII .* A12; MbnII = MbII .* A21 + MfII .* A22; te = ten; re = ren; tf = tfn; rf = rfn; MfI = MfnI; MbI = MbnI; MfII = MfnII; MbII = MbnII; end % Here we add the leaf-air interfaces again for obtaining the final % leaf level fluorescences. g1 = MbI; g2 = MbII; f1 = MfI; f2 = MfII; Rb = rho + tau.^2.*r21./(1-rho.*r21); Xe = Iv * (talf(Iwle)./(1-r21(Iwle).*Rb(Iwle)))'; Xf = t21(Iwlf)./(1-r21(Iwlf).*Rb(Iwlf)) * Ih; Ye = Iv * (tau(Iwle).*r21(Iwle)./(1-rho(Iwle).*r21(Iwle)))'; Yf = tau(Iwlf).*r21(Iwlf)./(1-rho(Iwlf).*r21(Iwlf)) * Ih; A = Xe .* (1 + Ye.*Yf) .* Xf; B = Xe .* (Ye + Yf) .* Xf; g1n = A .* g1 + B .* f1; f1n = A .* f1 + B .* g1; g2n = A .* g2 + B .* f2; f2n = A .* f2 + B .* g2; leafopt.MbI = g1n; leafopt.MbII = g2n; leafopt.MfI = f1n; leafopt.MfII = f2n; end return; function tav = calctav(alfa,nr) rd = pi/180; n2 = nr.^2; np = n2+1; nm = n2-1; a = (nr+1).*(nr+1)/2; k = -(n2-1).*(n2-1)/4; sa = sin(alfa.*rd); b1 = (alfa~=90)*sqrt((sa.^2-np/2).*(sa.^2-np/2)+k); b2 = sa.^2-np/2; b = b1-b2; b3 = b.^3; a3 = a.^3; ts = (k.^2./(6*b3)+k./b-b/2)-(k.^2./(6*a3)+k./a-a/2); tp1 = -2*n2.*(b-a)./(np.^2); tp2 = -2*n2.*np.*log(b./a)./(nm.^2); tp3 = n2.*(1./b-1./a)/2; tp4 = 16*n2.^2.*(n2.^2+1).*log((2*np.*b-nm.^2)./(2*np.*a-nm.^2))./(np.^3.*nm.^2); tp5 = 16*n2.^3.*(1./(2*np.*b-nm.^2)-1./(2*np.*a-nm.^2))./(np.^3); tp = tp1+tp2+tp3+tp4+tp5; tav = (ts+tp)./(2*sa.^2); return;
github
zhangyaonju/SCOPE-master
RTMt_sb.m
.m
SCOPE-master/SCOPE_v1.xx/code/RTMt_sb.m
9,905
utf_8
0e51dfe6983199e3edb940a3be235f1f
function [rad] = RTMt_sb(spectral,rad,soil,leafopt,canopy,gap,angles,Tcu,Tch,Tsu,Tsh,obsdir) % function 'RTMt_sb' calculates total outgoing radiation in hemispherical % direction and total absorbed radiation per leaf and soil component. % Radiation is integrated over the whole thermal spectrum with % Stefan-Boltzman's equation. This function is a simplified version of % 'RTMt_planck', and is less time consuming since it does not do the % calculation for each wavelength separately. % % Authors: Wout Verhoef and Christiaan van der Tol ([email protected]) % date: 5 Nov 2007 % update: 13 Nov 2007 % 16 Nov 2007 CvdT improved calculation of net radiation % 27 Mar 2008 JT added directional calculation of radiation % 24 Apr 2008 JT Introduced dx as thickness of layer (see parameters) % 31 Oct 2008 JT introduced optional directional calculation % 31 Oct 2008 JT changed initialisation of F1 and F2 -> zeros % 07 Nov 2008 CvdT changed layout % 16 Mar 2009 CvdT removed Tbright calculation % Feb 2013 WV introduces structures for version 1.40 % % Table of contents of the function % 0 preparations % 0.0 globals % 0.1 initialisations % 0.2 parameters % 0.3 geometric factors of Observer % 0.4 geometric factors associated with extinction and scattering % 0.5 geometric factors to be used later with rho and tau % 0.6 fo for all leaf angle/azumith classes % 1 calculation of upward and downward fluxes % 2 total net fluxes % Appendix A. Stefan-Boltzmann % % usage: % [rad] = RTMt_sb(options,spectral,rad,soil,leafopt,canopy,gap,angles,Tcu,Tch,Tsu,Tsh) % % Most input and output are structures. These structures are further % specified in a readme file. The temperatures Tcu, Tch, Tsu and Tsh are % variables. % % Input: % options calculation options % spectral information about wavelengths and resolutions % rad a large number of radiative fluxes: spectrally distributed % and integrated, and canopy radiative transfer coefficients % soil soil properties % leafopt leaf optical properties % canopy canopy properties (such as LAI and height) % gap probabilities of direct light penetration and viewing % angles viewing and observation angles % Tcu Temperature of sunlit leaves (oC), [13x36x60] % Tch Temperature of shaded leaves (oC), [13x36x60] % Tsu Temperature of sunlit soil (oC), [1] % Tsh Temperature of shaded soil (oC), [1] % % Output: % rad a large number of radiative fluxes: spectrally distributed % and integrated, and canopy radiative transfer coefficients. % Here, thermal fluxes are added %% 0.0 globals global constants %% 0.1 parameters IT = find(spectral.wlS == 10000); % Take 10 microns as representative wavelength for the thermal deg2rad = constants.deg2rad; nl = canopy.nlayers; lidf = canopy.lidf; litab = canopy.litab; lazitab = canopy.lazitab; nlazi = length(lazitab); tto = angles.tto; psi = angles.psi; Ps = gap.Ps; K = gap.K; rho = leafopt.refl(IT); % [nwl] Leaf/needle reflection tau = leafopt.tran(IT); % [nwl] Leaf/needle transmission rs = soil.refl(IT); % [nwl] Soil reflectance epsc = 1-rho-tau; % [nwl] Emissivity vegetation epss = 1-rs; % [nwl] Emissivity soil crit = max(1E-2); % [1] Desired minimum accuracy LAI = canopy.LAI; dx = 1/nl; iLAI = LAI*dx; %% 0.2 initialiations Rnhc = zeros(nl,1); % [nl] Rnuc = zeros(size(Tcu)); % [13,36,nl] %% 0.3 geometric factors of observer if obsdir cos_tto = cos(tto*deg2rad); % [1] cos observation angle sin_tto = sin(tto*deg2rad); % [1] sin observation angle end %% 0.4 geometric factors associated with extinction and scattering cos_ttl = cos(litab*deg2rad); if obsdir sin_ttl = sin(litab*deg2rad); cos_ttlo= cos((lazitab-psi)*deg2rad); end bfli = cos_ttl.^2; bf = bfli'*lidf; %% 0.5 geometric factors to be used later with rho and tau, f1 f2 of pag 304: ddb = 0.5*(1+bf); % f1^2 + f2^2 ddf = 0.5*(1-bf); % 2*f1*f2 if obsdir dob = 0.5*(K+bf); % fo*f1 dof = 0.5*(K-bf); % fo*f1 end %% 0.6 fo for all leaf angle/azumith classes if obsdir Co = cos_ttl*cos_tto; % [nli] pag 305 So = sin_ttl*sin_tto; % [nli] pag 305 cos_deltao = Co*ones(1,nlazi) + So*cos_ttlo;% [nli, nlazi] projection of leaves in in direction of sun (pag 125-126) fo = cos_deltao/abs(cos_tto);% [nli, nlazi] leaf area projection factors in direction of observation end %% 1. calculation of upward and downward fluxes pag 305 sigb = ddb*rho + ddf*tau; % [nwlt] Diffuse backscatter scattering coefficient sigf = ddf*rho + ddb*tau; % [nwlt] Diffuse forward scattering coefficient if obsdir vb = dob*rho + dof*tau; % [nwlt] Directional backscatter scattering coefficient for diffuse incidence vf = dof*rho + dob*tau; % [nwlt] Directional forward scattering coefficient for diffuse incidence end a = 1-sigf; % [nwlt] Attenuation m = sqrt(a*a-sigb*sigb);% [nwlt] rinf = (a-m)/sigb; % [nwlt] Reflection coefficient for infinite thick canopy rinf2 = rinf*rinf; % [nwlt] fHs = (1-rinf2)*(1-rs)/(1-rinf*rs); fHc = iLAI*m*(1-rinf); fbottom = (rs-rinf)/(1-rs*rinf); %1.1 radiance by components Hcsu3 = Stefan_Boltzmann(Tcu);% Radiance by sunlit leaves Hcsh = Stefan_Boltzmann(Tch);% Radiance by shaded leaves Hssu = Stefan_Boltzmann(Tsu);% Radiance by sunlit soil Hssh = Stefan_Boltzmann(Tsh);% Radiance by shaded soil % 1.2 radiance by leaf layers Hv and by soil Hs (modified by JAK 2015-01) v1 = repmat( 1/size(Hcsu3, 2), 1, size(Hcsu3, 2)); % vector for computing the mean Hcsu2 = reshape(Hcsu3, size(Hcsu3, 1), []); % create a block matrix from the 3D array Hcsu = (v1 * reshape(Hcsu2'*lidf, size(Hcsu3, 2), []))'; % compute column means for each level Hc = Hcsu.*Ps(1:nl) + Hcsh.*(1-Ps(1:nl)); % hemispherical emittance by leaf layers Hs = Hssu.*Ps(nl+1) + Hssh.*(1-Ps(nl+1)); % hemispherical emittance by soil surface % 1.3 Diffuse radiation cont = 1; % continue iteration (1:yes, 0:no) counter = 0; % number of iterations F1 = zeros(nl+1,1); F2 = zeros(nl+1,1); F1top = 0; while cont F1topn = -rinf*F2(1); F1(1) = F1topn; for j = 1:nl F1(j+1) = F1(j)*(1-m*iLAI)+ fHc*Hc(j); end F2(nl+1) = fbottom*F1(nl+1) + fHs*Hs; for j = nl:-1:1 F2(j) = F2(j+1)*(1-m*iLAI) + fHc*Hc(j); end cont = abs(F1topn-F1top)>crit; F1top = F1topn; counter = counter + 1; end Emin = (F1+rinf*F2)/(1-rinf2); Eplu = (F2+rinf*F1)/(1-rinf2); % 1.4 Directional radiation if obsdir piLo1 = iLAI*epsc*K*Hcsh'*(gap.Po(1:nl)-gap.Pso(1:nl)); % directional emitted radation by shaded leaves % JAK 2015-01: replaced earlier loop by this: all-at-once with more efficient mean absfo_rep = repmat(abs(fo), 1, nl); piLo2 = iLAI*epsc*(v1 * reshape( (Hcsu2.*absfo_rep)'*lidf, size(Hcsu3, 2), []))'.*gap.Pso(1:nl); % compute column means for each level piLo3 = iLAI*((vb*Emin(1:nl) + vf*Eplu(1:nl))'*gap.Po(1:nl)); % directional scattered radiation by vegetation for diffuse incidence piLo4 = epss*Hssh*(gap.Po(nl+1)-gap.Pso(nl+1)); % directional emitted radiation by shaded soil piLo5 = epss*Hssu*gap.Pso(nl+1); % directional emitted radiation by sunlit soil piLo6 = rs*Emin(nl+1)*gap.Po(nl+1); % directional scattered radiation by soil for diffuse incidence [1] piLot = piLo1 + sum(piLo2) + piLo3 + piLo4 + piLo5 + piLo6; else piLot = NaN; end Lot = piLot/pi; %% 2. total net fluxes % net radiation per component, in W m-2 (leaf or soil surface) for j = 1:nl Rnuc(:,:,j) = (Emin(j) + Eplu(j+1) - 2*Hcsu3(:,:,j))*epsc; % sunlit leaf Rnhc(j) = (Emin(j) + Eplu(j+1) - 2*Hcsh(j))*epsc; % shaded leaf end Rnus = (Emin(nl+1) - Hssu)*epss; % sunlit soil Rnhs = (Emin(nl+1) - Hssh)*epss; % shaded soil %% 3. Write the output to the rad structure rad.Emint = Emin; rad.Eplut = Eplu; rad.Eoutte = Eplu(1)-Emin(1); % 1) rad.Lot = Lot; rad.Rnuct = Rnuc; rad.Rnhct = Rnhc; rad.Rnust = Rnus; rad.Rnhst = Rnhs; return % 1) CvdT, 11 December 2015. % We subtract Emin(1), because ALL incident (thermal) radiation from Modtran % has been taken care of in RTMo. Not ideal but otherwise radiation budget will not close! %% Appendix A. Stefan-Boltzmann function H = Stefan_Boltzmann(T_C) global constants; C2K = constants.C2K; sigmaSB = constants.sigmaSB; H = sigmaSB*(T_C + C2K).^4; return
github
kekedan/py-faster-rcnn-master
voc_eval.m
.m
py-faster-rcnn-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
1,332
utf_8
3ee1d5373b091ae4ab79d26ab657c962
function res = voc_eval(path, comp_id, test_set, output_dir) VOCopts = get_voc_opts(path); VOCopts.testset = test_set; for i = 1:length(VOCopts.classes) cls = VOCopts.classes{i}; res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir); end fprintf('\n~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Results:\n'); aps = [res(:).ap]'; fprintf('%.1f\n', aps * 100); fprintf('%.1f\n', mean(aps) * 100); fprintf('~~~~~~~~~~~~~~~~~~~~\n'); function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir) test_set = VOCopts.testset; year = VOCopts.dataset(4:end); addpath(fullfile(VOCopts.datadir, 'VOCcode')); res_fn = sprintf(VOCopts.detrespath, comp_id, cls); recall = []; prec = []; ap = 0; ap_auc = 0; do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test'); if do_eval % Bug in VOCevaldet requires that tic has been called first tic; [recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true); ap_auc = xVOCap(recall, prec); % force plot limits ylim([0 1]); xlim([0 1]); print(gcf, '-djpeg', '-r0', ... [output_dir '/' cls '_pr.jpg']); end fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc); res.recall = recall; res.prec = prec; res.ap = ap; res.ap_auc = ap_auc; save([output_dir '/' cls '_pr.mat'], ... 'res', 'recall', 'prec', 'ap', 'ap_auc'); rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
github
zhusz/ECCV16-CBN-master
CBN_ghosting.m
.m
ECCV16-CBN-master/examples/sr1/demo/CBN_ghosting.m
3,072
utf_8
f31a2af9822c312ec152101f63cb3686
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function h4 = CBN_ghosting(h,GPU_ID) if ~exist('GPU_ID','var'), GPU_ID = 7; end; m = size(h,4); % Just for the ease of the experiment for observing the ghosting effect, % Manually set the high-frequency prior landmarks locations. p = [11.7099, 11.812, 12.4488, 13.5524, 15.6061, 18.8625, 22.8716, 27.3944, 32.591, 37.7481, 42.3443, 46.4694, 49.8047, 51.9137, 52.9999, 53.5848, 53.7569, 15.4211, 18.1077, 21.7398, 25.4283, 28.8021, 35.7989, 39.4334, 43.1652, 46.8272, 49.4612, 32.4113, 32.3929, 32.3807, 32.3787, 28.1896, 30.2286, 32.3746, 34.5657, 36.5215, 19.6982, 21.948, 24.6818, 26.9798, 24.5285, 21.8254, 37.8434, 40.2426, 42.9485, 45.141, 43.1603, 40.5138, 24.1604, 27.2379, 30.2926, 32.3403, 34.6496, 37.7598, 40.8131, 37.8955, 34.8776, 32.4057, 30.1365, 27.1037, 25.4566, 30.2745, 32.3615, 34.6973, 39.4974, 34.7303, 32.3606, 30.2246, 16.2201, 17.5625, 18.9026, 20.2924, 21.7211, 23.1504, 24.562, 25.9647, 27.3898, 28.2615, 35.9095, 37.0789, 38.5015, 39.9131, 41.3352, 42.7763, 44.2302, 45.6613, 47.043, 48.3918, 28.5817, 27.8596, 27.1131, 26.641, 26.9166, 28.0125, 29.4254, 30.891, 32.3927, 33.8932, 35.3687, 36.7902, 37.9183, 38.236, 37.7933, 37.0303, 36.2445, 19.9826, 25.5522, 31.1174, 36.5607, 41.6184, 46.042, 49.8705, 53.0223, 53.9377, 53.0025, 49.8577, 46.0565, 41.6205, 36.48, 30.965, 25.432, 19.8795, 15.4859, 13.199, 12.6895, 13.33, 14.8494, 14.6765, 13.1625, 12.587, 13.2098, 15.4515, 18.9545, 22.6331, 26.2839, 30.0236, 32.2715, 33.0945, 33.7957, 33.0886, 32.3359, 19.3822, 18.025, 18.1263, 19.9469, 20.4122, 20.3884, 19.9243, 18.0718, 18.0437, 19.3926, 20.3373, 20.394, 38.9289, 37.6628, 37.0739, 37.622, 37.0966, 37.7141, 38.8737, 42.1129, 43.5173, 43.7886, 43.551, 42.176, 39.1391, 38.9409, 39.1456, 38.9256, 39.1055, 40.6596, 40.9484, 40.7003, 15.8098, 15.5638, 15.1933, 15.0084, 15.0327, 15.2109, 15.4851, 15.8025, 15.9892, 15.2132, 15.371, 15.9711, 15.7772, 15.4554, 15.1629, 14.9577, 14.8859, 15.0118, 15.3371, 15.6087, 26.158, 27.3996, 28.7326, 30.1677, 31.5994, 32.562, 33.0918, 33.4283, 33.561, 33.4342, 33.1228, 32.6239, 31.6943, 30.2748, 28.8443, 27.5203, 26.146]; p = repmat(p, [m 1]); mask1 = pt2mask(p / 2, 32, 1); input1 = reshape(imresize(h, 2), [32 32 1 m]); h1 = batchForwardPDS('../',GPU_ID,{input1,mask1},'sr1','D432','jnt_24fnc','210000'); h1 = h1{1}; input2 = cat(3,reshape(imresize(h1, 2), [64 64 1 m]),reshape(imresize(input1, 2), [64 64 1 m])); mask2 = pt2mask(p, 64, 3); h2 = batchForwardPDS('../',GPU_ID,{input2,mask2},'sr1','D464_3B','jnt_12fnc', '230000'); h2 = h2{1}; mask3 = pt2mask(p * 2, 128, 5); input3 = reshape(imresize(h2, 2), [128 128 1 m]); h3 = batchForwardPDS('../',GPU_ID,{input3,mask3},'sr1','D4128_5C','msk_12fnc','1530000'); h3 = h3{1}; mask4 = pt2mask(p * 4, 256, 7); input4 = reshape(imresize(h3, 2), [256 256 1 m]); h4 = batchForwardPDS('../',GPU_ID,{input4,mask4},'sr1','D4256_7C','msk_12fnc','70000',1,16); h4 = h4{1}; end
github
zhusz/ECCV16-CBN-master
pt2mask.m
.m
ECCV16-CBN-master/examples/sr1/demo/pt2mask.m
1,203
utf_8
02de869f693f30cf9c39271364628a26
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function mask = pt2mask(ePnow, win_size_now, sq_half_size) edge_idx = {18:22, 69:78, 23:27, 79:88, ... 37:40, [37 42 41 40], 43:46, [43 48 47 46], ... 89:105, ... 49:55, 61:65, [61 68 67 66 65], [49 60:-1:55], ... 1:17}; mask = zeros([win_size_now, win_size_now, length(edge_idx), size(ePnow,1)], 'single'); for j = 1:length(edge_idx) edge_sparse = selectPoses(ePnow, edge_idx{j}); nj = size(edge_sparse, 2) / 2; parfor i = 1:size(ePnow,1) mask_ij = false(win_size_now,win_size_now); sx = edge_sparse(i,1:nj); sy = edge_sparse(i,1+nj:2*nj); x = interp1(1:nj,sx,1:0.02:nj,'cubic'); x = round(x); y = interp1(1:nj,sy,1:0.02:nj,'cubic'); y = round(y); assert(length(x) == length(y)); for k = 1:length(x) mask_ij(max(1, y(k)-sq_half_size) : min(win_size_now, y(k)+sq_half_size), ... max(1, x(k)-sq_half_size) : min(win_size_now, x(k)+sq_half_size)) = true; end; mask(:,:,j,i) = mask_ij; end; end; end
github
zhusz/ECCV16-CBN-master
CBN.m
.m
ECCV16-CBN-master/examples/sr1/demo/CBN.m
3,283
utf_8
4cd0f555847053f948646e8fc09bdfb5
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function h4 = CBN(h,GPU_ID) if ~exist('GPU_ID','var'), GPU_ID = 7; end; win_size_top = 256; ref_simple_face = win_size_top * [([0.4 0.6 0.412 0.588]-0.15)/0.7, ... ([0.3 0.3 0.52 0.52]-0.1)/0.7]; m = size(h,4); assert(m > 1); % Have problems if m == 1, in funcction batchForward the % blob might be squeezed out and hard to identify the number of samples. % If you really want to test only one image, repeat it twice. h = reshape(imresize(h, 2), [32 32 1 m]); h = batchForwardPDS('../',GPU_ID,{h},'sr1','D432','ndc_24fnc','1000000'); h = h{1}; h = reshape(imresize(h, 2), [64 64 1 m]); h = batchForwardPDS('../',GPU_ID,{h},'sr1','D464','ndc_12fnc','1000000'); h = h{1}; p = batchForwardPDS('../',GPU_ID,{h(5:50,10:55,:,:)},'sr1','D80','pnt_222','1100000'); p = p{1}' * 46; p(:,1:5) = p(:,1:5) + 9; p(:,6:10) = p(:,6:10) + 4; p = p * 4; h = reshape(imresize(h, 4), [256 256 1 m]); T = getTransToSpecific(selectPoses(p, [1 2 4 5]), ref_simple_face); parfor i = 1:m h(:,:,:,i) = imtransform(h(:,:,:,i), T(i), 'bicubic', 'XData', [1 win_size_top], ... 'YData', [1 win_size_top], 'XYScale', 1); end; h0 = reshape(imresize(h, 16 / 256), [16 16 1 m]); h1 = reshape(imresize(h0, 2), [32 32 1 m]); h1 = batchForwardPDS('../',GPU_ID,{h1},'sr1','D432','ndc_24fnc','1000000'); h1 = h1{1}; h2 = reshape(imresize(h1, 2), [64 64 1 m]); h2 = batchForwardPDS('../',GPU_ID,{h2},'sr1','D464','ndc_12fnc','1000000'); h2 = h2{1}; p = batchForwardPDS('../',GPU_ID,{h2(5:56,7:58,1,:)},'sr1','D81','pnt_222','2860000'); p = p{1}; p = p' * 52; p(:,1:size(p,2)/2) = p(:,1:size(p,2)/2) + 6; p(:,1+size(p,2)/2:end) = p(:,1+size(p,2)/2:end) + 4; p1 = p; mask1 = pt2mask(p1 / 2, 32, 1); input1 = reshape(imresize(h0, 2), [32 32 1 m]); h1 = batchForwardPDS('../',GPU_ID,{input1,mask1},'sr1','D432','jnt_24fnc','210000'); h1 = h1{1}; input2 = cat(3,reshape(imresize(h1, 2), [64 64 1 m]),reshape(imresize(input1, 2), [64 64 1 m])); h2 = batchForwardPDS('../',GPU_ID,{input2},'sr1','D464_3B','ndc_12fnc','1000000'); h2 = h2{1}; p = batchForwardPDS('../',GPU_ID,{h2(5:56,7:58,1,:)},'sr1','D82','pnt_222','1000000'); p = p{1}; p = p' * 52; p(:,1:size(p,2)/2) = p(:,1:size(p,2)/2) + 6; p(:,1+size(p,2)/2:end) = p(:,1+size(p,2)/2:end) + 4; p2 = p; mask2 = pt2mask(p2, 64, 3); h2 = batchForwardPDS('../',GPU_ID,{input2,mask2},'sr1','D464_3B','jnt_12fnc', '230000'); h2 = h2{1}; input3 = reshape(imresize(h2, 2), [128 128 1 m]); h3 = batchForwardPDS('../',GPU_ID,{input3},'sr1','D4128_5C','ndc_12fnc','740000'); h3 = h3{1}; p = batchForwardPDS('../',GPU_ID,{h3(9:112,13:116,:,:)},'sr1','D83','pnt_222','2000000'); p = p{1}; p = p' * 104; p(:,1:size(p,2)/2) = p(:,1:size(p,2)/2) + 12; p(:,1+size(p,2)/2:end) = p(:,1+size(p,2)/2:end) + 8; p3 = p; mask3 = pt2mask(p3 * 1, 128, 5); input3 = reshape(imresize(h2, 2), [128 128 1 m]); h3 = batchForwardPDS('../',GPU_ID,{input3,mask3},'sr1','D4128_5C','msk_12fnc','1530000'); h3 = h3{1}; mask4 = pt2mask(p3 * 2, 256, 7); input4 = reshape(imresize(h3, 2), [256 256 1 m]); h4 = batchForwardPDS('../',GPU_ID,{input4,mask4},'sr1','D4256_7C','msk_12fnc','70000',1,16); h4 = h4{1}; end
github
zhusz/ECCV16-CBN-master
frameworkForward.m
.m
ECCV16-CBN-master/codes/caffe_exetension/frameworkForward.m
1,221
utf_8
d55dc0e882f297fccdfccbccd2456bfa
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function [outer] = frameworkForward(directory,P,D,S,iter,inter,input_indexing_dim,b,verbose,GPU_device) % Directory should contain the P folder % Directory should end with a / % All P/D/S/iter should be string rather than cell structure or number assert(directory(end) == '/'); if ~exist('verbose','var'), verbose = 0; end; L = length(inter); if ~exist('input_indexing_dim','var') || isempty(input_indexing_dim) input_indexing_dim = zeros(L,1); end if ~exist('b','var') || isempty(b) b = 64; % Only accept GPU mode. if net is in CPU then you must be insane to use this function. Directly use net.foward outside!! end; if ~exist('GPU_device','var') || isempty('GPU_device') GPU_device = 0; end; caffe.reset_all(); caffe.set_mode_gpu(); caffe.set_device(GPU_device); net = caffe.Net([directory P '/' D '/' S '/network-' P '-' D '-' S '-deploy.prototxt'],... [directory P '/Model/m-' P '-' D '-' S '/' P '-' D '-' S '_iter_' iter '.caffemodel'],... 'test'); outer = batchForward(net, inter, input_indexing_dim, b, verbose); end
github
zhusz/ECCV16-CBN-master
batchForward.m
.m
ECCV16-CBN-master/codes/caffe_exetension/batchForward.m
3,189
utf_8
fbe6f5b321262854e27bfbbef531f28c
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function [outer,whole_blob_firstBatch] = batchForward(net, inter, input_indexing_dim,b,verbose) % If some input object is not splitted by sample index, you should put a -1 (or any other negative value into input_indexing_dim) % When input_indexing_dim is noted with 0, it indicates it uses the default last dim as the indexing dim) % Note we only care about the output of the network here. % Typically, if you want to watch the data blobs you only need to watch the first batch and observe it via our second output or outside this function by yourself % If you really want to see the blob of one typically layer throughout all the data, you can modify the deploy prototxt and add that layer as another output blob. (Here we note you can really add additional free layer in the deploy prototxt regardless whether the origianl model has been trained) % (insert a dummy concat layer at the bottom of the deploy prototxt) if ~exist('verbose','var'), verbose = 0; end; L = length(inter); if ~exist('input_indexing_dim','var') || isempty(input_indexing_dim) input_indexing_dim = zeros(L,1); end for i = 1:L if input_indexing_dim(i) == 0 input_indexing_dim(i) = ndims(inter{i}); end; end assert(all(input_indexing_dim > 0)); first_dim = find(input_indexing_dim > 0, 1, 'first'); m = size(inter{first_dim},input_indexing_dim(first_dim)); for i = first_dim:L if input_indexing_dim(i) > 0 assert(m == size(inter{i},input_indexing_dim(i))); end; end; if ~exist('b','var') || isempty(b) b = 64; % Only accept GPU mode. if net is in CPU then you must be insane to use this function. Directly use net.foward outside!! end; s = ceil(m / b); for i = 1:s if mod(i,verbose) == 0, fprintf('Batch forward processing Batch %d / %d.\n', i, s); end; now = inter; dim_extract_index = (i-1)*b+1 : min(m, i*b); if length(dim_extract_index) == b dim_extract_index_throwin = dim_extract_index; else dim_extract_index_throwin = [dim_extract_index ones(1,b-length(dim_extract_index))]; end; for j = 1:L if input_indexing_dim(j) > 0 now{j} = getMatAccordingToDim(now{j}, input_indexing_dim(j), dim_extract_index_throwin); end; end; temp_out = net.forward(now); if i == 1 outer = cell(length(temp_out), 1); for j = length(outer):-1:1 output_indexing_dim(j) = ndims(temp_out{j}); % for now like this assert(size(temp_out{j},output_indexing_dim(j)) == b); sz = size(temp_out{j}); sz(output_indexing_dim(j)) = m; outer{j} = zeros(sz); end; if nargout == 2 whole_blob_firstBatch = getNet(net); end; end; for j = 1:length(temp_out) temp_out{j} = getMatAccordingToDim(temp_out{j},output_indexing_dim(j),1:length(dim_extract_index)); eval(['outer{j}' setMatAccordingToDim_str(ndims(outer{j}), output_indexing_dim(j),{dim_extract_index}) ... ' = temp_out{j};']); end; end; end
github
zhusz/ECCV16-CBN-master
getWeight.m
.m
ECCV16-CBN-master/codes/caffe_exetension/getWeight.m
739
utf_8
7ece356cd27c1174c902d940ab694d3f
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 % Assumes path to matcaffe has been included function m = getWeight(net) n_layer = length(net.layer_names); m.layer = cell(n_layer, 2); m.layer_names = net.layer_names; m.layer_sizes = cell(n_layer,3); for i = 1:length(net.layer_names) m.layer_sizes{i,3} = cell2mat(net.layer_names(i)); for j = 1:length(net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params) m.layer{i,j} = net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params(j).get_data(); m.layer_sizes{i,j} = size(m.layer{i,j}); end; end; end
github
zhusz/ECCV16-CBN-master
batchForwardPDS.m
.m
ECCV16-CBN-master/codes/caffe_exetension/batchForwardPDS.m
852
utf_8
8a87d7f370145e4404db482421ca060e
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function output = batchForwardPDS(Proot, GPU_ID, input, P, D, S, iter, verbose, batch_size) if ~exist('batch_size','var'), batch_size = 64; end; if ~exist('verbose', 'var'), verbose = 1; end; if verbose fprintf('BatchForwardPDS for %s, %s, %s, %s begins!\n', P, D, S, iter); end; caffe.reset_all(); caffe.set_mode_gpu(); caffe.set_device(GPU_ID); net = caffe.Net([Proot D '/' S '/network-' P '-' D '-' S '-deploy.prototxt'],... [Proot 'Model/m-' P '-' D '-' S '/' P '-' D '-' S '_iter_' iter '.caffemodel'],... 'test'); if verbose tic; output = batchForward(net, input, [], batch_size); toc; else output = batchForward(net, input, [], batch_size); end; end
github
zhusz/ECCV16-CBN-master
getNetB.m
.m
ECCV16-CBN-master/codes/caffe_exetension/getNetB.m
1,555
utf_8
cf658576946e34b255212883b2e43862
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 % Assumes path to matcaffe has been included function m = getNetB(net) n_layer = length(net.layer_names); n_blob = length(net.blob_names); m.layer = cell(n_layer, 2); m.blob = cell(n_blob, 1); m.L = cell(n_layer,1); m.F = cell(n_blob,1); m.layer_names = net.layer_names; m.blob_names = net.blob_names; m.layer_sizes = cell(n_layer,3); m.blob_sizes = cell(n_blob,2); for i = 1:length(net.layer_names) m.layer_sizes{i,3} = cell2mat(net.layer_names(i)); for j = 1:length(net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params) m.layer{i,j} = net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params(j).get_diff(); m.layer_sizes{i,j} = size(m.layer{i,j}); end; if length(net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params) == 2 n_nextLayerChannel = size(m.layer{i,2},1); assert(1 == size(m.layer{i,2},2)); m.L{i} = [reshape(m.layer{i,1},[length(m.layer{i,1}(:))/n_nextLayerChannel, n_nextLayerChannel])' m.layer{i,2}]; end; end; for i = 1:length(net.blob_names) m.blob{i} = net.blob_vec(net.name2blob_index(cell2mat(net.blob_names(i)))).get_diff(); m.blob_sizes{i,1} = size(m.blob{i}); m.blob_sizes{i,2} = cell2mat(net.blob_names(i)); n_sample = m.blob_sizes{i,1}(end); m.F{i} = reshape(m.blob{i}, [length(m.blob{i}(:)) / n_sample, n_sample]); end; end
github
zhusz/ECCV16-CBN-master
getNet.m
.m
ECCV16-CBN-master/codes/caffe_exetension/getNet.m
1,554
utf_8
95ee41bd63574285fdc9560d895e26fe
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 % Assumes path to matcaffe has been included function m = getNet(net) n_layer = length(net.layer_names); n_blob = length(net.blob_names); m.layer = cell(n_layer, 2); m.blob = cell(n_blob, 1); m.L = cell(n_layer,1); m.F = cell(n_blob,1); m.layer_names = net.layer_names; m.blob_names = net.blob_names; m.layer_sizes = cell(n_layer,3); m.blob_sizes = cell(n_blob,2); for i = 1:length(net.layer_names) m.layer_sizes{i,3} = cell2mat(net.layer_names(i)); for j = 1:length(net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params) m.layer{i,j} = net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params(j).get_data(); m.layer_sizes{i,j} = size(m.layer{i,j}); end; if length(net.layer_vec(net.name2layer_index(cell2mat(net.layer_names(i)))).params) == 2 n_nextLayerChannel = size(m.layer{i,2},1); assert(1 == size(m.layer{i,2},2)); m.L{i} = [reshape(m.layer{i,1},[length(m.layer{i,1}(:))/n_nextLayerChannel, n_nextLayerChannel])' m.layer{i,2}]; end; end; for i = 1:length(net.blob_names) m.blob{i} = net.blob_vec(net.name2blob_index(cell2mat(net.blob_names(i)))).get_data(); m.blob_sizes{i,1} = size(m.blob{i}); m.blob_sizes{i,2} = cell2mat(net.blob_names(i)); n_sample = m.blob_sizes{i,1}(end); m.F{i} = reshape(m.blob{i}, [length(m.blob{i}(:)) / n_sample, n_sample]); end; end
github
zhusz/ECCV16-CBN-master
createH5DataTrain.m
.m
ECCV16-CBN-master/codes/caffe_exetension/createH5DataTrain.m
4,585
utf_8
7c4d83febfd40735c267f7ffa4e56dd5
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function createH5DataTrain(confirm_current_project) directory = pwd; directory_split = strsplit(directory, '/'); P = directory_split{end-1}; D = directory_split{end}; % ====================================================== % assert(strcmp(P,confirm_current_project)); % in case you are operating in a wrong dir % The current directory should be in the D one % load(['Mat/' D '_info_root.mat'], 'batch_sample_tot','var_name','testing_sample_tot'); load(['Mat/' D '_info_root.mat'], 'H5Info'); var_name = H5Info.var_name; batch_sample_tot = H5Info.batch_sample_tot; training_sample_tot = H5Info.training_sample_tot; var_name = sort(var_name); datum_name = var_name; for i = 1:length(datum_name), datum_name{i} = ['/' datum_name{i}]; end; datum = cell(length(datum_name),1); for i = 1:length(var_name) eval(['load(''Mat/' D '_train1.mat'', ''' var_name{i} ''');']); eval(['datum{i} = ' var_name{i} ';']); eval(['clear ' var_name{i} ';']); end; M = training_sample_tot; chunksz = 64; verbose = 1; setName = 'train'; % ====================================================== % data_root = ['../Data/d-' D '/']; data_root_forPrint = ['examples/' P '/Data/d-' D '/']; mkdir(data_root); h5_count = 0; datum_size = cell(length(datum),1); for i = 1:length(datum), datum_size{i} = size(datum{i}); disp(datum_size{i}); end; fid = fopen([data_root P '-' D '-' setName '.txt'],'w'); for batch = 1: ceil(M / chunksz) if batch == 1 || accumulated_h5_size >= batch_sample_tot % NEEDS MODIFYING!!! h5_count = h5_count + 1; h5_fn = [P '-' D '-' setName '-' num2str(h5_count) '.h5']; fprintf(fid,'%s\n',[data_root_forPrint h5_fn]); create_new_h5file(data_root, h5_fn,datum_name,datum_size,chunksz); accumulated_h5_size = 0; datum = cell(length(datum_name),1); for i = 1:length(var_name) eval(['load(''Mat/' D '_train' num2str(h5_count) '.mat'', ''' var_name{i} ''');']); eval(['datum{i} = ' var_name{i} ';']); eval(['clear ' var_name{i} ';']); end; end; current_sample_ID = (batch-1) * chunksz; % Note current_sample_ID always refers to the input data % If we change to a new HDF5 file, the current_sample_ID does NOT go % back to 1!!! for i = 1:length(datum) % batch_datum = getMatAccordingToDim(datum{i},ndims(datum{i}),... % current_sample_ID+1:min(current_sample_ID+chunksz, M)); batch_datum = getMatAccordingToDim(datum{i},ndims(datum{i}),... current_sample_ID+1-batch_sample_tot*(h5_count-1): ... min(current_sample_ID+chunksz, M)-batch_sample_tot*(h5_count-1)); accumulated_h5_size = writeToHDF5(data_root, h5_fn, batch_datum, datum_name{i}, i); if accumulated_h5_size >= batch_sample_tot % can comment these assertion later a = batch_datum(:,:,:,end); a = a(:); b = datum{i}(:,:,:,end); b = b(:); % if i < 3, disp([a(1:10) b(1:10)]); end; assert(all(a(:) == b(:))); end; end; %FUNCTION OF CREATEH5 SHOULD BE SEPARATED!!! if verbose fprintf('Finished Batch ID = %d in the h5 file ID = %d.\n', batch, h5_count); end; end; fclose(fid); end function create_new_h5file(data_root, h5_fn,datum_name,datum_size,chunksz) if exist([data_root h5_fn], 'file') delete([data_root h5_fn]); warning(['H5 file ' h5_fn ' has existed!']); end; len = length(datum_name); assert(len == length(datum_size)); for i = 1:len h5create([data_root h5_fn],datum_name{i},[datum_size{i}(1:end-1) Inf],... 'Datatype', 'single', 'ChunkSize', [datum_size{i}(1:end-1) chunksz]); end; end function accumulated_h5_size = writeToHDF5(data_root, h5_fn, batch_datum, batch_datum_name, datum_ID) info = h5info([data_root h5_fn]); equalAssert(ndims(batch_datum),length(info.Datasets(datum_ID).Dataspace.Size)); for i = 1:ndims(batch_datum)-1 equalAssert(size(batch_datum,i),info.Datasets(datum_ID).Dataspace.Size(i)); end; startLoc = ones(1,ndims(batch_datum)); startLoc(end) = info.Datasets(datum_ID).Dataspace.Size(end) + 1; h5write([data_root h5_fn], batch_datum_name, single(batch_datum), startLoc, size(batch_datum)); info = h5info([data_root h5_fn]); accumulated_h5_size = info.Datasets(datum_ID).Dataspace.Size(end); end
github
zhusz/ECCV16-CBN-master
genXPrototype.m
.m
ECCV16-CBN-master/codes/caffe_exetension/genXPrototype.m
18,115
utf_8
1ca9a774838fbaaa97cb2382950ff37d
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function genXPrototype(GPU_ID) % By-product: calculated network feature map size % Printed onto the screen % Important variable: % p: project name % s: structure name of one perticular design (aka name of the folder) % a: training data set % b: test data set % o: learning rate % Solver characters: % Oa: Standard training of full training set with base lr = 0.0001 % Na/Pa: 10 times larger/smaller base lr solver % Ob: Training on small training set b. (Force error reduction) % Nb/Pb: Similar % Oc: Training exluding val set or other special training set. % Nc/Pc: Similar assert(logical(exist('GPU_ID','var'))); delete('./*.prototxt'); % 1. Basic info getting and model storing folder setting up directory = pwd; directory(directory=='\') = '/'; d_split = strsplit(directory,'/'); S = d_split{end}; D = d_split{end-1}; P = d_split{end-2}; % 2. Get traintest and deploy prototxt (network structure) % Print layer map size info fid = fopen('xset.txt','r'); fn_traintest = ['network-' P '-' D '-' S '.prototxt']; fn_deploy = ['network-' P '-' D '-' S '-deploy.prototxt']; fid_traintest = fopen(fn_traintest,'w'); fid_deploy = fopen(fn_deploy,'w'); test_blob_tot = str2double(fgetl(fid)); test_blob = cell(test_blob_tot, 1); for i = 1:test_blob_tot, test_blob{i} = str2num(fgetl(fid)); end; fprintf(fid_traintest, ['name: "' P '-' D '-' S '"\n']); fprintf(fid_deploy, ['name: "' P '-' D '-' S '"\n']); line = fgetl(fid); while (length(line) ~= 1 || line(1) ~= '.') writeLayer(fid_traintest,line,0,P,D,S,GPU_ID); writeLayer(fid_deploy,line,1,P,D,S,GPU_ID,test_blob); line = fgetl(fid); end; fclose(fid_traintest); fclose(fid_deploy); % 3. Gen solver prototxt series = GF(fid); lrO = GF(fid); test_iter = GF(fid); test_interval = GF(fid); momentum = GF(fid); weight_decay = GF(fid); display = GF(fid); max_iter = GF(fid); snapshot = GF(fid); iter_size = GF(fid); for ch = series fid_solver = fopen(['solver-' P '-' D '-' S '-' ch '.prototxt'],'w'); PI(fid_solver, ['net: "examples/' P '/' D '/' S '/network-' P '-' D '-' S '.prototxt"']); PI(fid_solver, ['test_iter: ' num2str(test_iter)]); PI(fid_solver, ['test_interval: ' num2str(test_interval)]); PI(fid_solver, ['base_lr: ' num2str((10 ^ ('O' - ch)) * lrO)]); PI(fid_solver, ['momentum: ' num2str(momentum)]); PI(fid_solver, ['weight_decay: ' num2str(weight_decay)]); PI(fid_solver, ['lr_policy: "fixed"']); %#ok<NBRAK> PI(fid_solver, ['display: ' num2str(display)]); PI(fid_solver, ['max_iter: ' num2str(max_iter)]); PI(fid_solver, ['snapshot: ' num2str(snapshot)]); PI(fid_solver, ['snapshot_prefix: "examples/' P '/Model/m-' P '-' D '-' S '/' P '-' D '-' S '"']); PI(fid_solver, ['iter_size: 1']); fprintf(fid_solver, 'device_id : [%d', GPU_ID(1)); for j = 2:length(GPU_ID), fprintf(fid_solver, ',%d', GPU_ID(j));end; fprintf(fid_solver, ']\n'); fclose(fid_solver); end; % 4. Generate sample shell fid_sh = fopen(['new_xtrain.sh'],'w'); PI(fid_sh, '#!/usr/bin/env sh'); PI(fid_sh, ''); PI(fid_sh, ['GOOGLE_LOG_DIR=examples/' P '/' D '/' S '/log \']); PI(fid_sh, ['mpirun -np ' num2str(length(GPU_ID)) ' \'], 4); fprintf(fid_sh, [' ./build/install/bin/caffe train --solver=examples/' P '/' D '/' S '/solver-' P '-' D '-' S '-' series(1) '.prototxt']); %PI(fid_sh, ['#-snapshot=examples/' P '/Model/m-' P '-' D '-' S '/' P '-' D '-' S '_iter_110000.solverstate'], 4); % resuming or finetuning st = fgetl(fid); while (st(1) == '#'), st = fgetl(fid); end; id = find(st=='#',1,'first'); if ~isempty(id), st = st(1:id-1);end; st = strsplit(st, ' '); rf_flag = st{1}; disp({P,D,S}); disp(st); if ~(length(rf_flag) == 1 || rf_flag(1) == '.' || strcmp(rf_flag, 'NONE')) switch rf_flag case 'RESUME' assert(length(st) == 2); resume_iter = str2double(st{2}); assert(~isnan(resume_iter)); fprintf(fid_sh, [' \\\n -snapshot=examples/' P '/Model/m-' P '-' D '-' S '/' P '-' D '-' S '_iter_' num2str(resume_iter) '.solverstate']); case 'FINETUNE' finetune_tot = GF(fid); finetune = cell(finetune_tot, 4); for i = 1:finetune_tot st = fgetl(fid); id = find(st == '#', 1, 'first'); if ~isempty(id), st = st(1:id-1); end; st = strsplit(st, ' '); assert(length(st) == 4); assert(~isnan(str2double(st{4}))); for j = 1:4, finetune{i,j} = st{j}; end; end; disp(finetune); fprintf(fid_sh, [' \\\n -weights=']); for i = 1:finetune_tot if i > 1, fprintf(fid_sh, ','); end; fprintf(fid_sh, ['examples/' finetune{i,1} '/Model/m-' finetune{i,1} '-' finetune{i,2} '-' finetune{i,3} '/' finetune{i,1} '-' finetune{i,2} '-' finetune{i,3} '_iter_' finetune{i,4} '.caffemodel']); end; otherwise error('The rf_flag can only be one of: 1) NONE; 2) RESUME; 3) FINETUNE'); end; end; fclose(fid_sh); fclose(fid); warning off all; mkdir('log'); mkdir('../../Model/',['m-' P '-' D '-' S]); warning on all; end % ========================= Layer Writing =========================== % function writeLayer(fid, line, flag, P, D, S, GPU_ID, test_blob) % fid refers to fid_traintest or fid_deploy globally. % layer_name CONVOLUTION | bottom top xxx % flag == 0: writes on traintest, flag == 1: writes on deploy if line(1) == '#', return; end; e = strsplit(line); tot = length(e); while isempty(e{tot}), tot = tot - 1; end; e = e(1:tot); if strcmp(e{1},'`') && flag == 1, return; end; if strcmp(e{1},'`') && flag == 0, e = e(2:end); end; switch e{2} case 'HDF5DATA' % name TYPE | PHASE setName batchSize inputTot top1 top2 ... if flag == 0 % only effective for traintest prototxt PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'],2); PI(fid, ['type: "HDF5Data"'],2); for i = 7:tot, PI(fid, ['top: "' e{i} '"'],2);end; PI(fid, ['include: { phase: ' e{3} ' }'],2); PI(fid, 'hdf5_data_param {',2); PI(fid, ['source: "examples/' P '/Data/d-' D '/' P '-' D '-' e{4} '.txt"'],4); bs = 2^(ceil(log2(str2double(e{5}) / length(GPU_ID)))); % Cauculate the batchsize if bs < 1, bs = 1; end; PI(fid, ['batch_size: ' num2str(bs)],4); PI(fid, '}', 2); PI(fid, '}'); elseif flag == 1 && strcmp(e{3},'TEST') % only effective for deploy prototxt inputTot = str2double(e{6}); assert(inputTot == length(test_blob)); for i = 7:6+inputTot PI(fid, ['input: "' e{i} '"']); PI(fid, ['input_dim: ' num2str(test_blob{i-6}(1))]); PI(fid, ['input_dim: ' num2str(test_blob{i-6}(2))]); PI(fid, ['input_dim: ' num2str(test_blob{i-6}(3))]); PI(fid, ['input_dim: ' num2str(test_blob{i-6}(4))]); end; PI(fid, 'force_backward: true'); end; case 'CONVRELUS' % name TYPE | bot top kernel_size stride pad output w_lr b_lr num_of_conv assert(length(e) == 11); assert(str2double(e{11}) <= 1e6); for i = 1:str2double(e{11}) layer_append = sprintf('_%06d', i); layer_append_prev = sprintf('_%06d', i-1); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '_conv' layer_append '"'], 2); PI(fid, 'type: "Convolution"', 2); if i == 1 PI(fid, ['bottom: "' e{3} '"'], 2); else PI(fid, ['bottom: "' e{1} '_conv' layer_append_prev '"'], 2); end; if i == str2double(e{11}) PI(fid, ['top: "' e{4} '"'], 2); else PI(fid, ['top: "' e{1} '_conv' layer_append '"'], 2); end; PI(fid, 'param {',2); PI(fid, ['lr_mult: ' num2str(e{9})], 4); PI(fid, 'decay_mult: 1', 4); PI(fid, '}', 2); PI(fid, 'param {',2); PI(fid, ['lr_mult: ' num2str(e{10})], 4); PI(fid, 'decay_mult: 0', 4); PI(fid, '}', 2); PI(fid, 'convolution_param {', 2); PI(fid, ['num_output: ' num2str(e{8})], 4); PI(fid, ['pad: ' num2str(e{7})], 4); PI(fid, ['kernel_size: ' num2str(e{5})], 4); PI(fid, ['stride: ' num2str(e{6})], 4); PI(fid, 'weight_filler {', 4); PI(fid, 'type: "xavier"', 6); PI(fid, '}', 4); PI(fid, 'bias_filler {', 4); PI(fid, 'type: "constant"', 6); PI(fid, 'value: 0', 6); PI(fid, '}', 4); PI(fid, '}', 2); PI(fid, '}'); if i == str2double(e{11}), break; end; PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '_relu' layer_append '"'], 2); PI(fid, ['type: "ReLU"'], 2); PI(fid, ['bottom: "' e{1} '_conv' layer_append '"'], 2); PI(fid, ['top: "' e{1} '_conv' layer_append '"'], 2); PI(fid, '}'); end; case 'CONVOLUTION' % name TYPE | bot top kernel_size stride pad output w_lr b_lr assert(length(e) == 10); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, 'type: "Convolution"', 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, 'param {',2); PI(fid, ['lr_mult: ' num2str(e{9})], 4); PI(fid, 'decay_mult: 1', 4); PI(fid, '}', 2); PI(fid, 'param {',2); PI(fid, ['lr_mult: ' num2str(e{10})], 4); PI(fid, 'decay_mult: 0', 4); PI(fid, '}', 2); PI(fid, 'convolution_param {', 2); PI(fid, ['num_output: ' num2str(e{8})], 4); PI(fid, ['pad: ' num2str(e{7})], 4); PI(fid, ['kernel_size: ' num2str(e{5})], 4); PI(fid, ['stride: ' num2str(e{6})], 4); PI(fid, 'weight_filler {', 4); PI(fid, 'type: "xavier"', 6); PI(fid, '}', 4); PI(fid, 'bias_filler {', 4); PI(fid, 'type: "constant"', 6); PI(fid, 'value: 0', 6); PI(fid, '}', 4); PI(fid, '}', 2); PI(fid, '}'); case 'POOLING' % name TYPE | bot top POOLING_METHOD kernel_size stride % No learning params assert(length(e) == 7); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, 'type: "Pooling"', 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, 'pooling_param {', 2); PI(fid, ['pool: ' e{5}], 4); PI(fid, ['kernel_size: ' num2str(e{6})], 4); PI(fid, ['stride: ' num2str(e{7})], 4); PI(fid, '}', 2); PI(fid, '}'); case 'INNER_PRODUCT' % name TYPE | bot top output w_lr b_lr assert(length(e) == 7); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, 'type: "InnerProduct"', 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, 'param {', 2); PI(fid, ['lr_mult: ' num2str(e{6})], 4); PI(fid, 'decay_mult: 1', 4); PI(fid, '}', 2); PI(fid, 'param {', 2); PI(fid, ['lr_mult: ' num2str(e{7})], 4); PI(fid, 'decay_mult: 0', 4); PI(fid, '}', 2); PI(fid, 'inner_product_param {', 2); PI(fid, ['num_output: ' num2str(e{5})], 4); PI(fid, 'weight_filler {', 4); PI(fid, 'type: "xavier"', 6); PI(fid, '}', 4); PI(fid, '}', 2); PI(fid, '}'); case 'BN' % ONLY VALID FOR XIONGSHEN AND TONGSHEN'S CAFFE % name TYPE | bot top lr_w lr_b assert(length(e) == 6); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, ['type: "BN"'], 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); for j = 1:2 PI(fid, 'param {', 2); PI(fid, ['lr_mult: ' e{4+j}], 4); PI(fid, 'decay_mult: 0', 4); PI(fid, '}', 2); end; PI(fid, 'bn_param {', 2); PI(fid, 'slope_filler {', 4); PI(fid, 'type: "constant"', 6); PI(fid, 'value: 1', 6); PI(fid, '}', 4); PI(fid, 'bias_filler {', 4); PI(fid, 'type: "constant"', 6); PI(fid, 'value: 0', 6); PI(fid, '}', 4); PI(fid, '}', 2); PI(fid, '}'); case 'CONCAT' % name TYPE | bot1 bot2 ... top 0/1 assert(length(e) >= 6); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, ['type: "Concat"'], 2); for i = 3:length(e)-2 PI(fid, ['bottom: "' e{i} '"'], 2); end; PI(fid, ['top: "' e{end-1} '"'], 2); PI(fid, ['concat_param {'], 2); assert(~isnan(str2double(e{end}))); PI(fid, ['axis: ' e{end}], 4); PI(fid, '}', 2); PI(fid, '}'); case 'ELTWISE' % name TYPE | bot1 bot2 top SUM/PROD/MAX assert(length(e) == 6); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, ['type: "Eltwise"'], 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['bottom: "' e{4} '"'], 2); PI(fid, ['top: "' e{5} '"'], 2); PI(fid, ['eltwise_param {'], 2); PI(fid, ['operation: ' e{6}], 4); PI(fid, '}', 2); PI(fid, '}'); case 'TILE' % name TYPE | bot top axis tiles assert(length(e) == 6); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, ['type: "Tile"'], 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, ['tile_param {'], 2); for i = 5:6, assert(~isnan(str2double(e{i}))); end; PI(fid, ['axis: ' e{5}], 4); PI(fid, ['tiles: ' e{6}], 4); PI(fid, '}', 2); PI(fid, '}'); case 'POWER' % name TYPE | bot top power scaling shift assert(length(e) == 7); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, ['type: "Power"'], 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, ['power_param {'], 2); for i = 5:7, assert(~isnan(str2double(e{i}))); end; PI(fid, ['power: ' e{5}], 4); PI(fid, ['scale: ' e{6}], 4); PI(fid, ['shift: ' e{7}], 4); PI(fid, '}', 2); PI(fid, '}'); case 'RELU' % name TYPE | bot top assert(length(e) == 4); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, ['type: "ReLU"'], 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, '}'); case 'TANH' % name TYPE | bot top assert(length(e) == 4); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, ['type: "TanH"'], 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, '}'); case 'DROPOUT' assert(length(e) == 5); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, 'type: "Dropout"', 2); PI(fid, ['bottom: "' e{3} '"'], 2); PI(fid, ['top: "' e{4} '"'], 2); PI(fid, 'dropout_param {', 2); PI(fid, ['dropout_ratio: ' num2str(e{5})], 4); PI(fid, '}', 2); PI(fid, '}'); case 'EUCLIDEAN_LOSS' % name TYPE | bot1 bot2 top loss_weight % if flag == 0 % only when writing on training prototxt can do this assert(length(e) == 6); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, 'type: "EuclideanLoss"', 2); for i = 3:4, PI(fid, ['bottom: "' e{i} '"'], 2);end; PI(fid, ['top: "' e{5} '"'], 2); PI(fid, ['loss_weight: ' num2str(e{6})], 2); PI(fid, '}'); % end; case 'SMOOTHL1_LOSS' % PROVIDED BY JINWEI % name TYPE | bot1 bot2 top loss_weight threshold margin % if flag == 0 % only when writing on training prototxt can do this assert(legnth(e) == 8); PI(fid, 'layer {'); PI(fid, ['name: "' e{1} '"'], 2); PI(fid, 'type: "SmoothL1Loss"', 2); for i = 3:4, PI(fid, ['bottom: "' e{i} '"'], 2);end; PI(fid, ['top: "' e{5} '"'], 2); PI(fid, ['loss_weight: ' num2str(e{6})], 2); PI(fid, 'smooth_l1_loss_param {', 2); PI(fid, ['threshold: ' num2str(e{7})], 4); PI(fid, ['margin: ' num2str(e{8})], 4); PI(fid, '}', 2); PI(fid, '}'); % end; otherwise error('Haven'' t implementation such type of layer!'); end; end % =================================================================== % % ============================== Utility ============================ % % Print Indentation and return function PI(fid, str, indent) if nargin >= 3 for i = 1:indent, fprintf(fid, ' '); end; end; fprintf(fid, '%s\n', str); end % Get first element from the line of reading file function ele = GF(fid) str = fgetl(fid); e = strsplit(str, ' '); if ~isnan(str2double(e{1})) ele = str2double(e{1}); else ele = e{1}; end; end % =================================================================== %
github
zhusz/ECCV16-CBN-master
createH5DataTest.m
.m
ECCV16-CBN-master/codes/caffe_exetension/createH5DataTest.m
3,805
utf_8
9e43ef196726df7b3d4f5a2689a721e5
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function createH5DataTest(confirm_current_project) directory = pwd; directory_split = strsplit(directory, '/'); P = directory_split{end-1}; D = directory_split{end}; % ====================================================== % assert(strcmp(P,confirm_current_project)); % in case you are operating in a wrong dir % The current directory should be in the D one % load(['Mat/' D '_info_root.mat'], 'batch_sample_tot','var_name','testing_sample_tot'); load(['Mat/' D '_info_root.mat'], 'H5Info'); var_name = H5Info.var_name; batch_sample_tot = H5Info.batch_sample_tot; testing_sample_tot = H5Info.testing_sample_tot; var_name = sort(var_name); datum_name = var_name; for i = 1:length(datum_name), datum_name{i} = ['/' datum_name{i}]; end; datum = cell(length(datum_name),1); for i = 1:length(var_name) eval(['load(''Mat/' D '_test.mat'', ''' var_name{i} ''');']); eval(['datum{i} = ' var_name{i} ';']); eval(['clear ' var_name{i} ';']); end; M = testing_sample_tot; chunksz = 64; verbose = 1; setName = 'test'; clear var_name testing_sample_tot; % ====================================================== % data_root = ['../Data/d-' D '/']; data_root_forPrint = ['examples/' P '/Data/d-' D '/']; mkdir(data_root); h5_count = 0; datum_size = cell(length(datum),1); for i = 1:length(datum), datum_size{i} = size(datum{i}); disp(datum_size{i}); end; fid = fopen([data_root P '-' D '-' setName '.txt'],'w'); for batch = 1: ceil(M / chunksz) if batch == 1 || accumulated_h5_size >= batch_sample_tot % NEEDS MODIFYING!!! h5_count = h5_count + 1; h5_fn = [P '-' D '-' setName '-' num2str(h5_count) '.h5']; fprintf(fid,'%s\n',[data_root_forPrint h5_fn]); create_new_h5file(data_root, h5_fn,datum_name,datum_size,chunksz); accumulated_h5_size = 0; end; current_sample_ID = (batch-1) * chunksz; % Note current_sample_ID always refers to the input data % If we change to a new HDF5 file, the current_sample_ID does NOT go % back to 1!!! for i = 1:length(datum) batch_datum = getMatAccordingToDim(datum{i},ndims(datum{i}),... current_sample_ID+1:min(current_sample_ID+chunksz, M)); accumulated_h5_size = writeToHDF5(data_root, h5_fn, batch_datum, datum_name{i}, i); end; %FUNCTION OF CREATEH5 SHOULD BE SEPARATED!!! if verbose fprintf('Finished Batch ID = %d in the h5 file ID = %d.\n', batch, h5_count); end; end; fclose(fid); end function create_new_h5file(data_root, h5_fn,datum_name,datum_size,chunksz) if exist([data_root h5_fn], 'file') delete([data_root h5_fn]); warning(['H5 file ' h5_fn ' has existed!']); end; len = length(datum_name); assert(len == length(datum_size)); for i = 1:len h5create([data_root h5_fn],datum_name{i},[datum_size{i}(1:end-1) Inf],... 'Datatype', 'single', 'ChunkSize', [datum_size{i}(1:end-1) chunksz]); end; end function accumulated_h5_size = writeToHDF5(data_root, h5_fn, batch_datum, batch_datum_name, datum_ID) info = h5info([data_root h5_fn]); equalAssert(ndims(batch_datum),length(info.Datasets(datum_ID).Dataspace.Size)); for i = 1:ndims(batch_datum)-1 equalAssert(size(batch_datum,i),info.Datasets(datum_ID).Dataspace.Size(i)); end; startLoc = ones(1,ndims(batch_datum)); startLoc(end) = info.Datasets(datum_ID).Dataspace.Size(end) + 1; h5write([data_root h5_fn], batch_datum_name, single(batch_datum), startLoc, size(batch_datum)); info = h5info([data_root h5_fn]); accumulated_h5_size = info.Datasets(datum_ID).Dataspace.Size(end); end
github
zhusz/ECCV16-CBN-master
transImagesFwd.m
.m
ECCV16-CBN-master/codes/trans/transImagesFwd.m
1,270
utf_8
403aab76fe2a698286babee06323f9e3
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function newImages = transImagesFwd(oldImages,T,rows,cols) %newImages = transImagesFwd(oldImages) % images are all cell array. m = length(oldImages); if m~=length(T),error('size(oldImages,1) must equal to length(T)!');end; if 0 % (m<100) || (matlabpool('size')==0) newImages = arrayfun(@(i)imtransform(oldImages{i},T(i),'XData',... [1 cols],'YData',[1 rows],'XYScale',1),1:m,'UniformOutput',false); if (m>=100) warning('Please launch matlabpool to speed up your program!'); end else newImages = cell(m,1); parfor i = 1:m img = imtransform(oldImages{i},T(i),'XData',... [1 cols],'YData',[1 rows], 'XYScale', 1); if size(img,1) ~= rows || size(img,2) ~= cols error('Now it is not allowed to imresize after imtransform!'); newImages{i} = imresize(img, [rows, cols]); else newImages{i} = img; end; end end for i = 1:m, if size(newImages{i},1)~=rows || size(newImages{i},2)~=cols, newImages{i} = imresize(newImages{i},[rows,cols]);end;end; end
github
zhusz/ECCV16-CBN-master
getTransToSpecific.m
.m
ECCV16-CBN-master/codes/trans/getTransToSpecific.m
930
utf_8
03340d5afae78b851f1934b4f6763ec7
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransToSpecific(pose,specific) %T = getTransToSpecific(pose,specific) % T: m*1 t_concord % pose: m*2n % specific: 1*2n n = size(pose,2); if mod(n,2),error('size(pose,2) is odd!');end n = n / 2; m = size(pose,1); assert(size(specific,1)==1); assert(size(specific,2)==2*n); specific = reshape(specific,n,2); if (m<100) || (matlabpool('size')==0) T = arrayfun(@(i)cp2tform(reshape(pose(i,:),n,2),specific,'nonreflective similarity'),1:m); if m>=100 warning('Please launch matlabpool to speed up your program!'); end else T = cell(m,1); parfor i = 1:m T{i} = cp2tform(reshape(pose(i,:),n,2),specific,'nonreflective similarity'); end T = cell2mat(T); end end
github
zhusz/ECCV16-CBN-master
getTransToMean.m
.m
ECCV16-CBN-master/codes/trans/getTransToMean.m
988
utf_8
2cb374e914c957d9f6d787a10e36d217
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransToMean(pose) % T = getTransToMean(pose) % produce trans to project poese onto mean pose % size(pose) = [m,2n], each row must in the format of X1...Xn,Y1...Yn. % T is a array containing n structures. Each one is the trans for one % sample. n = size(pose,2); if mod(n,2),error('size(pose,2) is odd!');end n = n / 2; m = size(pose,1); meanPose = reshape(mean(pose,1),n,2); if (m<100) || (matlabpool('size')==0) T = arrayfun(@(i)cp2tform(reshape(pose(i,:),n,2),meanPose,'nonreflective similarity'),1:m); if m>=100 warning('Please launch matlabpool to speed up your program!'); end else T = cell(m,1); parfor i = 1:m T{i} = cp2tform(reshape(pose(i,:),n,2),meanPose,'nonreflective similarity'); end T = cell2mat(T); end end
github
zhusz/ECCV16-CBN-master
getTransPair.m
.m
ECCV16-CBN-master/codes/trans/getTransPair.m
905
utf_8
074d64eb279affb07157a1f702c5464e
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransPair(pose1,pose2) %T = getTransPair(pose1,pose2) % T: m*1 t_concord % pose1: m*2n % pose2: m*2n n = size(pose1,2); if mod(n,2),error('size(pose,2) is odd!');end n = n / 2; m = size(pose1,1); assert(size(pose2,1)==m); assert(size(pose2,2)==2*n); if (m<100) || (matlabpool('size')==0) T = arrayfun(@(i)cp2tform(reshape(pose1(i,:),n,2),reshape(pose2(i,:),n,2),'nonreflective similarity'),1:m); if m>=100 warning('Please launch matlabpool to speed up your program!'); end else T = cell(m,1); parfor i = 1:m T{i} = cp2tform(reshape(pose1(i,:),n,2),reshape(pose2(i,:),n,2),'nonreflective similarity'); end T = cell2mat(T); end end
github
zhusz/ECCV16-CBN-master
getTransViaXY.m
.m
ECCV16-CBN-master/codes/trans/getTransViaXY.m
550
utf_8
f41ee5ea1902c2edd08473f8a9d72730
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransViaXY(XY,win_size) %T = getTransViaXY(scaling_vector,win_size) % T: m*1 t_concord % XY: m*2 m = size(XY,1); assert(size(XY,2) == 2); pose_src = zeros(m,4); parfor i = 1:m pose_src(i,4) = norm(XY(i,:)); end; pose_src = pose_src + win_size / 2; pose_dst = pose_src + XY(:,[1 1 2 2]); T = getTransPair(pose_src,pose_dst); end
github
zhusz/ECCV16-CBN-master
getTransViaRotateGivenCenter.m
.m
ECCV16-CBN-master/codes/trans/getTransViaRotateGivenCenter.m
1,235
utf_8
be1f610a94138e6c0c932fb87f257fd0
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransViaRotateGivenCenter(theta_vector,center,rotatorLength) %T = getTransViaRotateGivenCenter(theta_vector,win_size) % T: m*1 t_concord % theta_vector: m*1 in degree! Make sure abs(theta)<180 % center: 1*2 indicates the x-y coordinates of rotation center % rotatorLength: scalar, length of the ratator. Set this variable to % avoid numerical problems. warning('This function might get non-affine tform'); assert(size(theta_vector,1)==1 || size(theta_vector,2)==1); assert(size(center,1)==1 || size(theta_vector,2)==1); assert(length(center)==2); assert(length(rotatorLength)==1); theta_vector = theta_vector(:); assert(all(abs(theta_vector) < 180)); pose_src = zeros(length(theta_vector),4); pose_src(:,[1 3]) = repmat(center(:)',length(theta_vector),1); pose_src(:,2) = center(1) + rotatorLength * cosd(theta_vector); pose_src(:,4) = center(2) + rotatorLength * sind(theta_vector); pose_dst = [center(1) center(1)+rotatorLength center(2) center(2)]; T = getTransToSpecific(pose_src,pose_dst); end
github
zhusz/ECCV16-CBN-master
getTransViaMerge.m
.m
ECCV16-CBN-master/codes/trans/getTransViaMerge.m
906
utf_8
d3cd898a298d90a1dc849d8511bd6e00
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransViaMerge(win_size,varargin) % T = getTransViaMerge(win_size,T1,T2,...) % y = T(x) = T_nargin(...(T2(T1(x)))) % T-s can only be similarity transform: rotate, scale, translate x/y % Note T-s must have strict order: rotate > scale > translate % rotate and scale only support: based on the center of patch (same win_size). % otherwise, don't feel suprised to see this function fuck you. m = length(varargin{1}); n = length(varargin); for i = 2:n assert(m == length(varargin{i})); end; x_old = repmat([win_size/2,win_size/2,win_size/2,win_size/2-win_size/3],m,1); x = transPoseFwd(x_old,varargin{1}); for i = 2:n x = transPoseFwd(x,varargin{i}); end; T = getTransPair(x_old,x); end
github
zhusz/ECCV16-CBN-master
transPoseRigidTurbulent.m
.m
ECCV16-CBN-master/codes/trans/transPoseRigidTurbulent.m
1,691
utf_8
3ad20b33786a8f3a7cf35cf319902823
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function [newCurrentPose,testShift] = transPoseRigidTurbulent(themeA,win_size,turb_coeff,currentPose,targetPose,errorL,errorS,maxIter) % Please note 'turb_coeff' is defined as follows: % (errorL - errorS) * turb_coeff = (errorNew - errorS) % All error means L2 error. errorNewTarget = errorS + (errorL-errorS)*turb_coeff; testShift = 1; upper = inf; inffer = -inf; step = 0.2; m_sample = size(currentPose,1); % min(size(currentPose,1),1000); for i = 1:maxIter ra = randperm(size(currentPose,1)); ra = ra(1:m_sample); expOldCurrentPose = currentPose(ra,:); Tshift = getTransShift(win_size,testShift,m_sample); expNewCurrentPose = transPoseFwd(expOldCurrentPose,Tshift); errorNew = mean(calcErrors(expNewCurrentPose,targetPose(ra,:)) ./ calcEyesDist(themeA,targetPose(ra,:))); if errorNew < errorNewTarget if testShift > inffer inffer = testShift; end; if upper == inf testShift = testShift + step; else testShift = (upper+inffer)/2; end; else if testShift < upper upper = testShift; end; if inffer == -inf testShift = testShift - step; else testShift = (upper+inffer)/2; end; end; % testShift end; fprintf('The best testShift is %f.\n',testShift); Tshift = getTransShift(win_size,testShift,size(currentPose,1)); newCurrentPose = transPoseFwd(currentPose,Tshift); end
github
zhusz/ECCV16-CBN-master
getTransViaScaling.m
.m
ECCV16-CBN-master/codes/trans/getTransViaScaling.m
863
utf_8
544591f1eb14509860b0fc393ca2c16b
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransViaScaling(scaling_vector,win_size) %T = getTransViaScaling(scaling_vector,win_size) % T: m*1 t_concord % scaling_vector: m*1 around 1 (Don't arbitrarily large or small!) % win_size: scalar. Note the image must be square! assert(size(scaling_vector,1)==1 || size(scaling_vector,2)==1); scaling_vector = scaling_vector(:); win_cent = win_size / 2; win_del = win_cent * 2 / 3; pose_dst = zeros(length(scaling_vector),4); pose_dst(:,[1 3 4]) = win_cent; pose_dst(:,2) = win_cent + win_del * scaling_vector; pose_src = repmat([win_cent win_cent+win_del win_cent win_cent],size(scaling_vector,1),1); T = getTransPair(pose_src,pose_dst); end
github
zhusz/ECCV16-CBN-master
transPoseFwd.m
.m
ECCV16-CBN-master/codes/trans/transPoseFwd.m
1,218
utf_8
eb1853ef17684bba523cf027a8285335
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function newPose = transPoseFwd(oldPose,T) % newPose = transPoseFwd(oldPose,T) % produce new pose according to oldPose and T % size(oldPose) = [m,2n], each row must in the format of X1...Xn,Y1...Yn. % T is a array containing n structures. Each one is the trans for one % sample. % newPose has the same size as oldPose. m = size(oldPose,1); if length(T)~=m,error('length(T) must be the same as size(oldPose,1)!');end; n = size(oldPose,2); if mod(n,2),error('size(pose,2) is odd!');end n = n / 2; ind_nan = find(isnan(oldPose)); oldPose(ind_nan) = 0; if (m<100) || (matlabpool('size')==0) newPose = arrayfun(@(i)reshape(tformfwd(T(i),reshape(oldPose(i,:),n,2)),1,2*n),1:m,'UniformOutput',false); newPose = cell2mat(newPose(:)); if m>=100 warning('Please launch matlabpool to speed up your program!'); end else newPose = zeros(size(oldPose)); parfor i = 1:m newPose(i,:) = reshape(tformfwd(T(i),reshape(oldPose(i,:),n,2)),1,2*n); end end newPose(ind_nan) = NaN; end
github
zhusz/ECCV16-CBN-master
getTransViaRotate.m
.m
ECCV16-CBN-master/codes/trans/getTransViaRotate.m
923
utf_8
9d8a11b78871350dc1b808e37c61d728
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransViaRotate(theta_vector,win_size) %T = getTransViaRotate(theta_vector,win_size) % T: m*1 t_concord % theta_vector: m*1 in degree! Make sure abs(theta)<180 % win_size: scalar. Note the image must be square! warning('This function might get non-affine tform'); assert(size(theta_vector,1)==1 || size(theta_vector,2)==1); theta_vector = theta_vector(:); win_cent = win_size / 2; win_del = win_cent * 2 / 3; pose_src = zeros(length(theta_vector),4); pose_src(:,[1 3]) = win_cent; pose_src(:,2) = win_cent + win_del * cosd(theta_vector); pose_src(:,4) = win_cent + win_del * sind(theta_vector); pose_dst = [win_cent win_cent+win_del win_cent win_cent]; T = getTransToSpecific(pose_src,pose_dst); end
github
zhusz/ECCV16-CBN-master
getTransRandomCross.m
.m
ECCV16-CBN-master/codes/trans/getTransRandomCross.m
1,175
utf_8
7fb2c466057c830574d5c8df1cd841cd
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransRandomCross(pose) % T = getTransRandomCross(pose) % produce trans to project poese onto randomly selected another pose % size(pose) = [m,2n], each row must in the format of X1...Xn,Y1...Yn. % T is a array containing n structures. Each one is the trans for one % sample. n = size(pose,2); if mod(n,2),error('size(pose,2) is odd!');end n = n / 2; m = size(pose,1); pr = randi(m,m,1); I = find(pr-[1:m]'==0); while ~isempty(I) pr(I) = randi(m,length(I),1); I = find(pr-[1:m]'==0); end if (m<100) || (matlabpool('size')==0) T = arrayfun(@(i)cp2tform(reshape(pose(i,:),n,2),reshape(pose(pr(i),:),n,2),'nonreflective similarity'),1:m); if m>=100 warning('Please launch matlabpool to speed up your program!'); end else T = cell(m,1); newPose = pose(pr,:); parfor i = 1:m T{i} = cp2tform(reshape(pose(i,:),n,2),reshape(newPose(i,:),n,2),'nonreflective similarity'); end T = cell2mat(T); end end
github
zhusz/ECCV16-CBN-master
getTransPairRegardingNaN.m
.m
ECCV16-CBN-master/codes/trans/getTransPairRegardingNaN.m
827
utf_8
6c4302099433bd3b5a70427bedb91c8d
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransPairRegardingNaN(pose1,pose2) %T = getTransPair(pose1,pose2) % T: m*1 t_concord % pose1: m*2n % pose2: m*2n n = size(pose1,2); if mod(n,2),error('size(pose,2) is odd!');end n = n / 2; m = size(pose1,1); assert(size(pose2,1)==m); assert(size(pose2,2)==2*n); T = cell(m,1); parfor i = 1:m pose1I = pose1(i,:); pose2I = pose2(i,:); idx = intersect(find(~isnan(pose1I(1:n))),find(~isnan(pose2I(1:n)))); T{i} = cp2tform(reshape(pose1I([idx idx+n]),length(idx),2),... reshape(pose2I([idx idx+n]),length(idx),2),... 'nonreflective similarity'); end T = cell2mat(T); end
github
zhusz/ECCV16-CBN-master
transPoseInv.m
.m
ECCV16-CBN-master/codes/trans/transPoseInv.m
1,218
utf_8
1455a7d757d552480df16bb04986cec3
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function newPose = transPoseInv(oldPose,T) % newPose = transPoseInv(oldPose,T) % produce new pose according to oldPose and T % size(oldPose) = [m,2n], each row must in the format of X1...Xn,Y1...Yn. % T is a array containing n structures. Each one is the trans for one % sample. % newPose has the same size as oldPose. m = size(oldPose,1); if length(T)~=m,error('length(T) must be the same as size(oldPose,1)!');end; n = size(oldPose,2); if mod(n,2),error('size(pose,2) is odd!');end n = n / 2; ind_nan = find(isnan(oldPose)); oldPose(ind_nan) = 0; if (m<100) || (matlabpool('size')==0) newPose = arrayfun(@(i)reshape(tforminv(T(i),reshape(oldPose(i,:),n,2)),1,2*n),1:m,'UniformOutput',false); newPose = cell2mat(newPose(:)); if m>=100 warning('Please launch matlabpool to speed up your program!'); end else newPose = zeros(size(oldPose)); parfor i = 1:m newPose(i,:) = reshape(tforminv(T(i),reshape(oldPose(i,:),n,2)),1,2*n); end end newPose(ind_nan) = NaN; end
github
zhusz/ECCV16-CBN-master
getTransShift.m
.m
ECCV16-CBN-master/codes/trans/getTransShift.m
1,224
utf_8
93cb76a68896c019a072c3e5ff4db56e
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function T = getTransShift(win_size,shift,m) %T = getTransShift(win_size,shift,m) % return Ta with size m*1 centric = floor([win_size / 2, win_size / 2]); side = centric + [100,0]; assert(max(side)<win_size); centric = repmat(centric,m,1); side = repmat(side,m,1); move1_theta = rand(m,1)*360; move1_r = shift * randn(m,1); move1_shift = [move1_r.*cosd(move1_theta) move1_r.*sind(move1_theta)]; m_centric = centric + move1_shift; move2_tao = shift * randn(m,1); m_side = side + move1_shift; m_side(:,2) = m_side(:,2) + move2_tao; if (m<100) || (matlabpool('size')==0) T = arrayfun(@(i)cp2tform(... [centric(i,:);side(i,:)],... [m_centric(i,:);m_side(i,:)],... 'nonreflective similarity'),1:m); if m>=100 warning('Please launch matlabpool to speed up your program!'); end else T = cell(m,1); parfor i = 1:m T{i} = cp2tform([centric(i,:);side(i,:)],[m_centric(i,:);m_side(i,:)],'nonreflective similarity'); end T = cell2mat(T); end end
github
zhusz/ECCV16-CBN-master
selectPoses.m
.m
ECCV16-CBN-master/codes/toolbox_face_alignment/selectPoses.m
344
utf_8
2f35b1cf3e822201de1c0458e6c27780
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function [selectedPose,ind] = selectPoses(pose,sub,d) if nargin<3 d = 2; end; ind = selectPosesIdx(size(pose,2),sub,d); selectedPose = pose(:,ind); end
github
zhusz/ECCV16-CBN-master
selectPosesIdx.m
.m
ECCV16-CBN-master/codes/toolbox_face_alignment/selectPosesIdx.m
375
utf_8
63aca49a8acf67eb352992faa67d8d96
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function ind = selectPosesIdx(len,sub,d) if nargin<3 d = 2; end assert(mod(len,d)==0); gap = len/d; ind = []; sub = sub(:)'; for i = 1:d ind = [ind sub + (i-1)*gap]; end end
github
zhusz/ECCV16-CBN-master
raRandPerm.m
.m
ECCV16-CBN-master/codes/extension/raRandPerm.m
357
utf_8
945e4384372d2aa3727c2c9d9c823e4d
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function ra = raRandPerm(n,k) % K can be larger than N times = ceil(k/n); ra = zeros(n,times); for i = 1:times,ra(:,i) = randperm(n)';end; ra = ra(:)'; ra = ra(1:k); end
github
zhusz/ECCV16-CBN-master
setMatAccordingToDim_str.m
.m
ECCV16-CBN-master/codes/extension/setMatAccordingToDim_str.m
829
utf_8
5e8a9e050f9b8d5e24395ef931ec107d
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function s = setMatAccordingToDim_str(dim_tot, dim_ID, dim_index) % output example: (:,:,[1 2 3 4], [2 3 5],:,[3]) % Outside you need to use eval to do this. % Here dim_ID can be multiple as long as length(dim_ID) == length(dim_index), the former is array and latter is cell strcture % Remember dim_index must be a cell strcture whose length is identical to % the array dimID!!! assert(length(dim_ID) == length(dim_index)); s = '('; for i = 1:dim_tot h = find(dim_ID == i); assert(length(h) <= 1); if isempty(h) s = [s ':,']; else k = dim_index{h}(:)'; s = [s '[' num2str(k) '],']; end; end; s(end) = ')'; end
github
zhusz/ECCV16-CBN-master
equalAssert.m
.m
ECCV16-CBN-master/codes/extension/equalAssert.m
1,123
utf_8
6ebec5bf05aad6b71d95f9d5c5eaaae3
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function equalAssert(A,B,mode,epsilon) if ~exist('mode','var') mode = 0; end; switch mode case 0 % double accurate scalar input assert(length(A) == 1 && length(B) == 1, 'Not numerical scalar real number input!'); assert(A==B, ['EqualAssert (mode two accurate scalars) failed!, [' num2str(A) ' | ' num2str(B) '].']); case 1 % double numerical scalar input assert(length(A) == 1 && length(B) == 1, 'Not numerical scalar real number input!'); if ~exist('epsilon','var'), epsilon = 0.0001; end; assert(abs(A-B) < epsilon, ... ['EqualAssert (mode two numerical scalars) failed!, [' num2str(A) ' | ' num2str(B) '].']); case 2 % double strings input assert(ischar(A) && ischar(B), 'Not char input!'); assert(strcmp(A,B), ['EqualAssert (mode two strings) failed! [' A ' | ' B '].']); otherwise error('What mode is this?'); end; end
github
zhusz/ECCV16-CBN-master
swap.m
.m
ECCV16-CBN-master/codes/extension/swap.m
226
utf_8
9d889f79e9f350cee4a4c2bf3a688bc6
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function [A,B] = swap(A,B) T = A; A = B; B = T; end
github
zhusz/ECCV16-CBN-master
minInMat.m
.m
ECCV16-CBN-master/codes/extension/minInMat.m
283
utf_8
fc9b0b8ad44696ebced17418e2b645d3
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function [v,i,j] = minInMat(A) assert(ndims(A) <= 2); [v,id] = min(A, [], 1); [v,j] = min(v); i = id(j); end
github
zhusz/ECCV16-CBN-master
indexingData.m
.m
ECCV16-CBN-master/codes/extension/indexingData.m
640
utf_8
16ac4a91a8d1d0e87761c25c1e7c3408
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function varargout = indexingData(varargin) %varargout = indexingData(ind,varargin) % every element in varargin will be extracted according to ind(index), % and the relative output will be sent to varargout. % PLEASE NOTE indexing only refer to the 1st dimension! varargout = cell(1,nargin-1); ind = varargin{1}; for i = 2:nargin k = varargin{i}; if size(k,1) == 1 k = k'; end varargout{i-1} = k(ind,:); end end
github
zhusz/ECCV16-CBN-master
getMatAccordingToDim.m
.m
ECCV16-CBN-master/codes/extension/getMatAccordingToDim.m
648
utf_8
242e8bc2c6a05c1f8d48ab4bb373713a
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function data_out = getMatAccordingToDim(data_in, dim_ID, dim_index) %#ok<STOUT> nd = ndims(data_in); assert(length(dim_ID) == 1 && dim_ID <= nd); dim_index = dim_index(:)'; assert(max(dim_index) <= size(data_in, dim_ID)); st = []; for i = 1:dim_ID-1 st = [st ':, ']; %#ok<AGROW> end; st = [st '[' num2str(dim_index) '], ']; for i = dim_ID+1: nd st = [st ':, ']; %#ok<AGROW> end; st = st(1:end-2); eval(['data_out = data_in(' st ');']); end
github
zhusz/ECCV16-CBN-master
isIn_str.m
.m
ECCV16-CBN-master/codes/extension/isIn_str.m
741
utf_8
e60520abf0c9da63c397e7850c9019c0
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function [TF,TF_idx] = isIn_str(ele,s) %TF = isIn_str(ele,s) % judge if ele is in the set s. return 0 or 1. % if ele is an array TF will also be an array. % all input are in cell form of strings % TF = arrayfun(@(x)isempty(find(x==s,1)),ele); % TF = 1-TF; ele = ele(:); s = s(:); TF = NaN * zeros(length(ele),1); TF_idx = TF; for i = 1:length(ele) id = find(cellfun(@(x)strcmp(x,ele{i}),s)); if isempty(id) TF(i) = 0; TF_idx(i) = 0; else assert(length(id) == 1); TF(i) = 1; TF_idx(i) = id; end; end; end
github
zhusz/ECCV16-CBN-master
isIn.m
.m
ECCV16-CBN-master/codes/extension/isIn.m
391
utf_8
02eec0695dfd9451cef67290ae729315
% Codes for ECCV-16 work `Deep Cascaded Bi-Network for Face Hallucination' % Any question please contact Shizhan Zhu: [email protected] % Released on August 19, 2016 function TF = isIn(ele,s) %TF = isIn(ele,s) % judge if ele is in the set s. return 0 or 1. % if ele is an array TF will also be an array. TF = arrayfun(@(x)isempty(find(x==s,1)),ele); TF = 1-TF; end
github
KevinLoudi/SpectrumLearning-master
MultiDayAnalysisProcess.m
.m
SpectrumLearning-master/MultiDayAnalysisProcess.m
1,325
utf_8
7881ab86c43542c5be879bca35f5415b
%Analsis Multi-day data %Author: Zhu Gengyu %Date: 2016/7/18 function MultiDayAnalysisProcess() %Analyz channel state Parameters.MaxSlotNum = 2000; Parameters.MaxChannelNum = 6000; Parameters.ExtremSize = 0.05; Parameters.SingalThershold = 30; %dB %load original several-day-all-timeslot data data StartF = 1710; StopF = 1740; %StartF = 60; StopF = 137; filename = sprintf('MultiLevel_%s_%s.mat', num2str(StartF),num2str(StopF)); if exist(filename,'file') ~= 2 error('*.mat file do not exist!'); end load(filename); %vari- AllTimeSlots % StartItem=(80-60)/0.025; StopItem=(110-60)/0.025; % TmpLevel=MultiLevel.ByDay{1,1}.level(:,StartItem:StopItem); TmpLevel=MultiLevel.ByDay{1,1}.level(:,1:800); %1710 csvwrite('DayLevel.csv',TmpLevel); Res = CalcChannelState(TmpLevel,Parameters); figure(1); %Demostrate channel state %contoutf(Res); %show the channel state StartF = MultiLevel.Info.StartFreq; StopF = MultiLevel.Info.StopFreq; StepF = MultiLevel.Info.StepFreq; figure(1); [slotnum,freqnum] = size(TmpLevel); Freq = StartF:StepF:(StopF-StepF); Freq=Freq(1:800); %Freq=Freq(StartItem:StopItem); Time = 1:slotnum; WaterFallPlot(Freq,Time,Res.Occupancy); csvwrite('DayChannelState.csv',Res.Occupancy); %culster according to channel %BandCluster(AllTimeSlots,StartF,StopF); end
github
KevinLoudi/SpectrumLearning-master
BandCluster.m
.m
SpectrumLearning-master/BandCluster.m
858
utf_8
4c5e780ac7e69c64aff71d9ffe8bc463
%Culster data according to divided channel %Author: Zhu Gengyu %Date: 2016/8/17 function BandLevel = BandCluster(Level, StartF, StopF) % 1710+0.2*(n-511) downlink [slots,freqs] = size(Level); %ratio = 0.2/0.025; %banditem = 1:ratio:freqs; bandindex = 1; count = 0; BandLevel = zeros(slots,floor(freqs/8)); %for i = 1:slots %for j= 1:freqs i=1; j=1; while(i<slots) while (j < freqs) if(mod(j,8)==1)||j~=1 BandLevel(i,bandindex) = BandLevel(i,bandindex) +Level(i,j); count = count + 1; else BandLevel(i,bandindex) = BandLevel(i,bandindex)/count; count = 0; bandindex = bandindex + 1; end i = i+1; j = j+1; end end figure(1); [t,f] = size(BandLevel); WaterFallPlot(f,t,BandLevel); end
github
KevinLoudi/SpectrumLearning-master
MultiDayDataSave.m
.m
SpectrumLearning-master/MultiDayDataSave.m
1,315
utf_8
b8d635bf1beca44e07b05881a68bd4cd
%Save multi-day data into .mat file %Author: Zhu Gengyu %Date: 2016/7/19 function MultiDayDataSave() clear; clc; %Path = 'E:\\tmpData\\825-960\\%s\\02'; %Path ='D:\\Code\\Matlab\\SpectrumLearning\\Data\\OriginData\\1710-1960\\%s\\02'; % StartF = 1710; % StopF = 1740; Path ='D:\\Code\\Matlab\\SpectrumLearning\\Data\\OriginData\\60-137\\%s\\02'; StartF=60; StopF=137; StepF = 0.025; %DayArray = {'20151216','20151217','20151218','20151219','20151220','20151221','20151222'}; DayArray = {'20151217'}; %Read data day by day if the "Path" exist locally [MultiLevel] = MultiDaySpectrumReader(Path,DayArray,StartF,StopF) %Save Data % tmpname = '%s_%s.mat'; % filename = sprintf(tmpname,num2str(StartF),num2str(StopF)); % if exist(filename,'file') ~= 2 % error('*.mat file do not exist!'); % end % load(filename); %save all level data in allLevel and clear reducant variable MultiLevel.Info.StartFreq = StartF; MultiLevel.Info.StopFreq = StopF; MultiLevel.Info.StepFreq = StepF; cur_time = fix(clock); time_str = sprintf('%.4d-%.2d-%.2d:%.2d:%.2d:%.2d:%.2d',cur_time(1),cur_time(2),cur_time(3),cur_time(4),cur_time(5),cur_time(6)); MultiLevel.Info.BuildTime = time_str; filename = sprintf('MultiLevel_%s_%s.mat', num2str(StartF),num2str(StopF)); save(filename,'MultiLevel'); end
github
KevinLoudi/SpectrumLearning-master
HMMAnalyz.m
.m
SpectrumLearning-master/HMMAnalyz.m
264
utf_8
e4373db7276009a068ce13995df9d68c
%Author: Zhu Gengyu %Date: 2016/8/17 %Propose: Analyz Time State Evolution function [Res] = HMMAnalyz() TRANS = [.9 .1; .05 .95;]; EMIS = [1/6, 1/6, 1/6, 1/6, 1/6, 1/6;... 7/12, 1/12, 1/12, 1/12, 1/12, 1/12]; [seq,states] = hmmgenerate(1000,TRANS,EMIS); end
github
KevinLoudi/SpectrumLearning-master
WaterFallPlot.m
.m
SpectrumLearning-master/WaterFallPlot.m
341
utf_8
8d8ddfdc834d4a973e9e9199f50ff547
%Plot a Freq-Time waterfall with color %Author: Zhu Gengyu %Date: 2016/7/12 function WaterFallPlot(FreqRange,TimeRange,TimeLevel) [Time,Freq] = size(TimeLevel); if Time ~= length(TimeRange) || Freq ~= length(FreqRange) error('The input data set did not match!!'); return; end imagesc(FreqRange,TimeRange,TimeLevel); colorbar; end
github
KevinLoudi/SpectrumLearning-master
SpectrumReader.m
.m
SpectrumLearning-master/SpectrumReader.m
1,007
utf_8
05360833f1b6887d13bda1cb67ab0b49
%Read Spectrum Data from a signal day %Author: Zhu Gengyu %Data: 2016/7/11 function [Level]=SpectrumReader(Path, StartF, StopF, StepF) SelItem1 = (StartF-2010)/StepF+1; SelItem2 = (StopF-2010)/StepF+1; %Get all Filenames belongs to a specific station dirinfo = dir(Path); %AbsoPath = [Path,'\\%s']; %strcat %Loop for all File index = 1; for k = 1:length(dirinfo) thisdir = dirinfo(k).name; %Concate the two path %Filename = Path + '\'+ thisdir; %sprintf(AbsoPath,thisdir); Filename = [Path,'\',thisdir]; if exist(Filename,'file') == 2 %Test: if the filepath is accessible tmpLevel = ArgusReader(Filename,2010,2150); Level{index} = tmpLevel; index = index + 1; end end end %Read all data sets from an argus file function [LevelData]= ArgusReader(Path,StartF,StopF) jump_distance = 36+0; len = (StopF-StartF)/0.025; fid = fopen(Path); fseek(fid,jump_distance,'bof'); LevelData = fread(fid,len,'integer*2=>int16',6); fclose(fid); end
github
KevinLoudi/SpectrumLearning-master
Readme.m
.m
SpectrumLearning-master/Readme.m
1,147
utf_8
ede3f0e31d2dc01fe8299705064c4320
% function Readme() disp('This research aim at applying mechine learning principle to tackle massive radio-frequency data'); disp('Author: Zhu Gengyu'); disp('Data 2016/7/11'); disp('And this is the bynow plans'); disp('Step 1: Read Spectrum Data; (1)Should be time-saving and well-structed') disp('Step 2: Save Specific Part of Spectrum by Time Slots; (1)Save the Data in .mat. (2)Corr ratio aalysis'); disp('Step 3: Invese-FFT on Spectrum to obtain I/Q; (1)Seems impossible'); disp('Step 4: Frequenct Pattern mining; (1)A Example(unfinished)'); disp('Step 5: Calculate the channel state;(1) According to the real signal channel assignment of GSM900 DL'); disp('Step 6: Seperate the file-read process and anlysis process'); disp('Step 7: Calculate the Service Congestion Rate(SCR)'); disp('Step 8: Calculate the Channel vacancy duration(CVD)'); disp('Step 9: Analyze the CVD distribution, calculate the fit significance(R^2) (1)Find a well fit model(exponential-like)'); disp('Step 10: Applying the first-order Markov chain in one-timeslot CVD prediction.'); disp('Step 11: Dickey-Fuller(ACF) test'); disp('Step 12: Hang on'); end
github
KevinLoudi/SpectrumLearning-master
CDFplot.m
.m
SpectrumLearning-master/CDFplot.m
387
utf_8
6eac4766b77ceb46fb46fc87639afe82
%Calculate cdf of different distributions %Author: Shirley %Date: 2016/9/8 function []=CDFplot() pd = makedist('Normal'); r = random(pd,[80,1]); p = cdf('Normal',r,1,4); cdfplot(p); % pd = makedist('Poisson',lambda); % p = cdf('Poisson',0:4,1:5); % X = 1:200; % Y = logncdf(X,4.5,0.1); % func = @(fit,xdata)logncdf(xdata,fit(1),fit(2)); % fit = lsqcurvefit(func,[4 0.3],X,Y) end
github
KevinLoudi/SpectrumLearning-master
ChannelStateClassify.m
.m
SpectrumLearning-master/ChannelStateClassify.m
126
utf_8
3c2643a553173cfeaf79b02992e2e80a
%Classify Channel %Author: Zhu Gengyu %Date: 2016/7/20 function ClassifyRes = ChannelStateClassify(ChannelStatecell) end
github
KevinLoudi/SpectrumLearning-master
RealChannelState.m
.m
SpectrumLearning-master/RealChannelState.m
405
utf_8
15c7df02a3a78154a2830006d578fefe
%Analysis real channel according to start, stop and increment of %specific service %Author: Zhu Gengyu %Date: 2016/7/21 %Data Format: %InputPara.StartF; %InputPara.StopF; %InputPara.FirstCenterBand %InputPara.ChannelNum %InputPara.BandWidth function [Result] = RealChannelState(RawData,InputPara) if(nargin < 2)||(isempty(RawChannelState)) error('Not Enough Input Data!!!'); return; end end
github
KevinLoudi/SpectrumLearning-master
ShepardIterpolation.m
.m
SpectrumLearning-master/ShepardIterpolation.m
874
utf_8
6b8a5755c36551eb97b50e60118ab3ed
%Construct Spectrum map using grid interpolation in 2D %Author: Shirley %Date: 2016/9/8 function ShepardIterpolation() %[Xq, Yq, Vq] = griddata(X,Y,V, xq, yq,v4); % Interpolate a 2D scattered data set over a uniform grid xy = -2.5 + 5*gallery('uniformdata',[200 2],0); x = xy(:,1); y = xy(:,2); v = x.*exp(-x.^2-y.^2); [xq,yq] = meshgrid(-2:.2:2, -2:.2:2); vq = griddata(x,y,v,xq,yq,'v4'); mesh(xq,yq,vq), hold on, plot3(x,y,v,'o'), hold off % % Example 2: % Interpolate a 3D data set over a grid in the x-y (z=0) plane % xyz = -1 + 2*gallery('uniformdata',[5000 3],0); % x = xyz(:,1); y = xyz(:,2); z = xyz(:,3); % v = x.^2 + y.^2 + z.^2; % d = -0.8:0.05:0.8; % [xq,yq,zq] = meshgrid(d,d,0); % vq = griddata(x,y,z,v,xq,yq,zq); % surf(xq,yq,vq); end
github
KevinLoudi/SpectrumLearning-master
CvdAnalysis.m
.m
SpectrumLearning-master/CvdAnalysis.m
334
utf_8
9c6e232eb2d7fcef98875a8634ae483a
%Abstract partial CVD for analysis %Author: Zhu Gengyu %Date: 2016/8/13 function CvdAnalysis(StartF,StopF) if exist('CVD.mat','file') ~= 2 || exist('AllTimeSlotinOne.mat','file') ~= 2 return error('*.mat file do not exist!'); end load('CVD.mat'); load('AllTimeSlotinOne.mat','file') ; StartItem = (StartF-) end
github
KevinLoudi/SpectrumLearning-master
CalculateCVD.m
.m
SpectrumLearning-master/CalculateCVD.m
1,518
utf_8
9be38f10d76902fd941bd710d6fd6fd2
%Calculate Channel Vacancy Duration through Channel State %Author: Zhu Gengyu %Date: 2016/7/20 function [Result]=CalculateCVD(ChannelState) CS = ChannelState; [Time,Channel] = size(CS); if (Time < 20)||(Channel < 2) error('Insufficient Input Data !!!'); return; end %set a variable to preserve CVD data CVD = cell(1,Channel); %for each channel, recongize the continuous '0' items %This is an excellent method in solve the problem for i = 1:Channel %select specific line according to channels a = CS(:,i); temp = []; result = {}; %obtain a bool-state of a (equal to '1' or not) %tmpCVD = zeros(Time); %if all items in the series equal '0', skip the calculation if(Time ~= find(a)) while(~isempty(a)) if a(1)~=0 if(~isempty(temp)) %if temp is empty, then it have no value last time result = [result,{temp}]; end %if temp have value, means it is a 0 this time temp = []; flag = 0; else %a(1) equals 0 temp = [temp,a(1)]; %a vacancy means at least 5 mins duration flag = 1; end a(1) = []; end else result{1} = length(a); end %calculate the number of results or "vacancy period" for k = 1:length(result) %how many vacancy periods a channel have tmpCVD(k) = length(result{k}); end %all "vacancy period" belongs to a specific channel CVD{1,i} = tmpCVD; end Result.ChannelNum = Channel; Result.TimeSlot = Time; Result.CVDcell = CVD; end
github
KevinLoudi/SpectrumLearning-master
MultiDaySpectrumReader.m
.m
SpectrumLearning-master/MultiDaySpectrumReader.m
2,597
utf_8
9447f6563c48f1c4d17cdfb5b05bbc7b
%Read Out Spectrum Data from several days (one station) %Author: Zhu Gengyu %Date: 2016/7/18 %Path format: 'Y:\\20-3000\\%s\\03' DayArray should be string %Level.Info: Device, Lon, Lat, Status, FileNum Level.Data: Time[time,stringlen], level[time,freq] function [MultiLevel] = MultiDaySpectrumReader(Path,DayArray,StartFreq,StopFreq) Maxsize = 1000; %index for the time slot num datasize = 1; %declear Level container %Level.Info=0; %Device, Lon, Lat Data.time=''; Data.level=0; Info.DeviceId=0; Info.Longitude=0; Info.Latitude=0; Info.Status=0; Info.FileNum=0; for i = 1:length(DayArray) Day = DayArray{i}; %get the file path for a specific day DayPath = sprintf(Path,Day); %find all files in the path dirinfo = dir(DayPath); index = 1; %Loop for all files within the path for k = 1:length(dirinfo) %point to this-file thisdir = dirinfo(k).name; %get the path for this-file filename = [DayPath,'\',thisdir]; %check if this-file really exist if exist(filename,'file') == 2 %Read out data from a *.argus file [Info,Data]=ArgusReader(filename,StartFreq,StopFreq,Info,Data); %tmpLevel.SampleTime=floor(str2num(thisdir(1:12))); Data.time(Info.FileNum,1:12)=thisdir(1:12); %Count the accessed data datasize = datasize + 1; index = index + 1; if(index > Maxsize) %abortion if the data set is too large delete Info, Data ; break; end end end %Combine the newly read data and existed data in Level MultiLevel.ByDay{i}=Data; end %presever other information MultiLevel.Info=Info; end %Read all data sets from an argus file function [Info,Data]=ArgusReader(Path,StartF,StopF,Info,Data) len = (StopF-StartF)/0.025; fid = fopen(Path); jump_distance = 0; fseek(fid,jump_distance,'bof'); Info.FileNum=Info.FileNum+1; if Info.Status==0 Info.DeviceId=fread(fid,1,'integer*4=>int32'); Info.Longitude= fread(fid,1,'float=>float'); Info.Latitude=fread(fid,1,'float=>float'); Info.Status=1; %aleard assign device information end % jump_distance = 36+0; %+0: min level; +2: mean level; +4: max level % fseek(fid,jump_distance,'bof'); % LevelData.MinLevel = fread(fid,len,'integer*2=>int16',6); % jump_distance = 36+2; % fseek(fid,jump_distance,'bof'); % LevelData.MeanLevel= fread(fid,len,'integer*2=>int16',6); jump_distance = 36+4; fseek(fid,jump_distance,'bof'); %LevelData.MaxLevel= fread(fid,len,'integer*2=>int16',6); Data.level(Info.FileNum, 1:len)= fread(fid,len,'integer*2=>int16',6); fclose(fid); end
github
KevinLoudi/SpectrumLearning-master
DistriAnalysis.m
.m
SpectrumLearning-master/DistriAnalysis.m
588
utf_8
53526d47c2a44a36dd422a27e972de09
%Distribution analysis %Author: Zhu Gengyu %Date: 2016/7/14 function [DistriModel] = DistriAnalysis(Level) if length(Level)== 0 error('No Input Data!!!'); return; end %calculate the stage num in hist, no more than 100 Stage = length(Level)/10; if Stage > 100 Stage = 100; end %hist display H = hist(Level,Stage); %calcule the sample distribution cdf = zeros(1,length(H)); for k = 1:length(H) cdf(k) = sum(H(1:k)); end %save calculate results DistriModel.Cdf = cdf; DistriModel.Hist = H; DistriModel.Len = length(Level); DistriModel.StageNum = Stage; end
github
KevinLoudi/SpectrumLearning-master
BP_ANN_Forecast.m
.m
SpectrumLearning-master/Examine/Neural Network Implementation/BP_ANN_Forecast.m
729
utf_8
d700d638e039742a1db848f5847b3924
%Implementation of BP-ANN in analysis %Author: Zhu Gengyu %Date: 2016/9/17 function BP_ANN_Forecast() load DayChannelState.csv; OrigData=DayChannelState; clear DayChannelState; %randomly select a channel SelData=OrigData(135, :); T=length(SelData); tao=4; rowsz=tao; colsz=T-tao; %input data-set matrix data=zeros(rowsz,colsz); for i=1:colsz for j=1:rowsz data(i,j)=SelData(tao-j+i); end end %output data-set matrix oudata=zeros(T-tao-1,1); oudata=SelData(tao+1:T); %BP-ANN net=newff(data,oudata,20); net=train(net,data,oudata); outputs=net(data); errors=outputs-oudata; perf=perform(net,outputs,oudata); end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_upw_MOD2_f2_2.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_upw_MOD2_f2_2.m
7,593
utf_8
744afc3d3405319ddc02f81b6b57ba8b
% write_lpf_MOD % 11/17/16 function write_upw_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY) % % =========== TO RUN AS SCRIPT =========================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % % for sfr % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; buffer_fil = '/home/leila/GSFLOW_Jan_2016/GSFLOW_test2_24thJan/simdir/30yrmelt/Data/GIS/segments_buffer2.asc'; % % ==================================================================== % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % lpf_file = 'test.lpf'; lpf_file = [infile_pre, '.upw']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 2; % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); % - space discretization DELR = (NSEW(3)-NSEW(4))/NCOL; % width of column [m] DELC = (NSEW(1)-NSEW(2))/NROW; % height of row [m] % - set TOP to surface elevation [m] D = textscan(fid, '%f'); fclose(fid); fprintf('Done reading...\n'); TOP = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL % get buffer info fid = fopen(buffer_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); D = textscan(fid, '%f'); buffer = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL fclose(fid); % -- Base hydcond, Ss (all layers), and Sy (top layer only) on data from files % (temp place-holder) hydcond = ones(NROW,NCOL,NLAY)*2; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.5; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,2) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,1) = 0.1; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) % hydcond(:,:,1) = 0.01; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) hydcond(:,:,2) = 0.01; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) Ss = ones(NROW,NCOL,NLAY)* 2e-6; % constant 2e-6 /m for Sagehen Sy = ones(NROW,NCOL,NLAY)*0.15; % 0.08-0.15 in Sagehen (lower Sy under ridges for volcanic rocks) WETDRY = Sy; % = Sy in Sagehen (lower Sy under ridges for volcanic rocks) % % use buffer (and elev?) % K = buffer; % 0: very far from stream, 5: farthest from stream in buffer, 1: closest to stream % K(buffer==0) = 0.04; % very far from streams % K(buffer==0 & TOP>5000) = 0.03; % very far from streams % K(buffer>=1) = 0.5; % close to streams % K(buffer>=2) = 0.4; % K(buffer>=3) = 0.3; % K(buffer>=4) = 0.15; % K(buffer==5) = 0.08; % farthest from stream and high % hydcond(:,:,1) = K; % hydcond(:,:,2) = 0.01; % use buffer (and elev?) K = buffer; % 0: very far from stream, 5: farthest from stream in buffer, 1: closest to stream K(buffer==0) = 0.04; % very far from streams K(buffer==0 & TOP>5000) = 0.03; % very far from streams % K(buffer>=1) = 0.5; % close to streams K(buffer>=1) = 0.25; % close to streams K(buffer>=2) = 0.15; K(buffer>=3) = 0.08; K(buffer>=4) = 0.08; K(buffer==5) = 0.08; % farthest from stream and high hydcond(:,:,1) = K; hydcond(:,:,2) = 0.01; % -- assumed input values flow_filunit = 34; % make sure this matches namefile!! hdry = 1e30; % head assigned to dry cells nplpf = 0; % number of LPF parameters (if >0, key words would follow) laytyp = zeros(NLAY,1); laytyp(1) = 1; % flag, top>0: "covertible", rest=0: "confined" layave = zeros(NLAY,1); % flag, layave=1: harmonic mean for interblock transmissivity chani = ones(NLAY,1); % flag, chani=1: constant horiz anisotropy mult factor (for each layer) layvka = zeros(NLAY,1); % flag, layvka=0: vka is vert K; >0 is vertK/horK ratio VKA = hydcond; laywet = zeros(NLAY,1); laywet(1)=1; % flag, 1: wetting on for top convertible cells, 0: off for confined fl_Tr = 1; % flag, 1 for at least 1 transient stress period (for Ss and Sy) %Comment these three out to turn .lpf to .upw % WETFCT = 1.001; % 1.001 for Sagehen, wetting (convert dry cells to wet) % IWETIT = 4; % number itermations for wetting % IHDWET = 0; % wetting scheme, 0: equation 5-32A is used: h = BOT + WETFCT (hn - BOT) %% ------------------------------------------------------------------------ fmt1 = repmat('%2d ', 1, NLAY); fil_lpf_0 = [GSFLOW_indir, slashstr, lpf_file]; fid = fopen(fil_lpf_0, 'wt'); fprintf(fid, '# LPF package inputs\n'); fprintf(fid, '%d %g %d ILPFCB,HDRY,NPLPF\n', flow_filunit, hdry, nplpf); fprintf(fid, [fmt1, ' LAYTYP\n'], laytyp); fprintf(fid, [fmt1, ' LAYAVE\n'], layave); fprintf(fid, [fmt1, ' CHANI \n'], chani); fprintf(fid, [fmt1, ' LAYVKA\n'], layvka); fprintf(fid, [fmt1, ' LAYWET\n'], laywet); % if ~isempty(find(laywet,1)) % fprintf(fid, '%g %d %d WETFCT, IWETIT, IHDWET\n', WETFCT, IWETIT, IHDWET); % end % -- Write HKSAT and Ss, Sy (if Tr) in .lpf file format0 = [repmat(' %4.2f ', 1, NCOL), '\n']; format1 = [repmat(' %4.2e ', 1, NCOL), '\n']; % loop thru layers (different entry for each layer) for lay = 1: NLAY fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 HY layer %d\n', lay); % horizontal hyd cond fprintf(fid, format1, hydcond(:,:,lay)'); fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 VKA layer %d\n', lay); % vertical hyd cond fprintf(fid, format1, VKA(:,:,lay)'); if fl_Tr fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Ss layer %d\n', lay); fprintf(fid, format1, Ss(:,:,lay)'); if laytyp(lay) > 0 % convertible, i.e. unconfined fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Sy layer %d\n', lay); fprintf(fid, format1, Sy(:,:,lay)'); if laywet(lay) > 0 % fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 WETDRY layer %d\n', lay); % fprintf(fid, format0, WETDRY(:,:,lay)'); fprintf(fid, 'CONSTANT 2.000E-6 (FREE) 0 SPECIFIC STORAGE FOR LAYER %d\n', lay); fprintf(fid, format0, WETDRY(:,:,lay)'); end end end end fprintf(fid, '\n'); fclose(fid); figure for ilay = 1:NLAY subplot(2,2,double(ilay)) X = hydcond(:,:,ilay); m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; % cm(1,:) = [1 1 1]; caxis([0 max(X(:))]) colormap(cm); colorbar title(['hydcond', num2str(ilay)]); end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_nam_MOD_f.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_nam_MOD_f.m
2,050
utf_8
786f4b54902ff3101173f4faa44a238f
% write_nam_MOD % 11/20/16 function write_nam_MOD_f(GSFLOW_indir, GSFLOW_outdir, infile_pre) % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % - write to this file (within indir) fil_nam = [infile_pre, '.nam']; slashstr = '/'; % all assumed to be in GSFLOW_dir fil_ba6 = [infile_pre, '.ba6']; fil_lpf = [infile_pre, '.lpf']; fil_pcg = [infile_pre, '.pcg']; fil_oc = [infile_pre, '.oc']; fil_dis = [infile_pre, '.dis']; fil_uzf = [infile_pre, '.uzf']; fil_sfr = [infile_pre, '.sfr']; %% ------------------------------------------------------------------------ % -- .nam file with full paths % fil_nam_0 = fullfile(MODtest_dir0, fil_nam); fil_nam_0 = [GSFLOW_indir, slashstr, fil_nam]; fid = fopen(fil_nam_0, 'wt'); fprintf(fid, 'LIST 7 %s \n', [GSFLOW_outdir, slashstr, 'test.lst']); % MODFLOW output file fprintf(fid, 'BAS6 8 %s \n', [GSFLOW_indir, slashstr, fil_ba6]); fprintf(fid, 'LPF 11 %s \n', [GSFLOW_indir, slashstr, fil_lpf]); fprintf(fid, 'PCG 19 %s \n', [GSFLOW_indir, slashstr, fil_pcg]); fprintf(fid, 'OC 22 %s \n', [GSFLOW_indir, slashstr, fil_oc]); fprintf(fid, 'DIS 10 %s \n', [GSFLOW_indir, slashstr, fil_dis]); fprintf(fid, 'UZF 12 %s \n', [GSFLOW_indir, slashstr, fil_uzf]); fprintf(fid, 'SFR 13 %s \n', [GSFLOW_indir, slashstr, fil_sfr]); fprintf(fid, 'DATA(BINARY) 34 %s \n', fullfile(GSFLOW_outdir, 'test.bud')); % MODFLOW LPF output file, make sure 34 is unit listed in lpf file!! fprintf(fid, 'DATA(BINARY) 51 %s \n', [GSFLOW_outdir, slashstr, 'testhead.dat']); % MODFLOW output file fprintf(fid, 'DATA(BINARY) 61 %s \n', [GSFLOW_outdir, slashstr, 'uzf.dat']); % MODFLOW output file fprintf(fid, 'DATA 52 %s \n', [GSFLOW_outdir, slashstr, 'ibound.dat']); % MODFLOW output file fclose(fid);
github
UMN-Hydro/GSFLOW_pre-processor-master
make_sfr2_f_bu.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/make_sfr2_f_bu.m
16,998
utf_8
0ad0153cb953fb0dc4dfac073cf5d6b4
% make_sfr.m % 1/8/16 % Leila Saberi % % 2 - gcng function make_sfr2_f(GSFLOW_indir, infile_pre, reach_fil, segment_fil_all) % Note: assume .dis file already created!! (reads in TOP for setting STRTOP) % % ======== TO RUN AS SCRIPT =============================================== % clear all, close all, fclose all; % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % infile_pre = 'test2lay'; % % % for sfr % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; % % ========================================================================= %% sfr_file = [infile_pre, '.sfr']; % -- Refer to GSFLOW manual p.202, SFR1 manual, and SFR2 manual % - Refer to Fig. 1 of SFR1 documentation for segment vs. reach numbering % You need the following inputs (with corresponding structures) % the followings are used to write item 1 fl_nstrm = -1; % flag for stream reaches, <0: include unsaturated zone below (sagehen: >0) nsfrpar = 0; %Always Zero nparseg = 0; %Always Zero const = 86400.; %Conversion factor used in calculating depth for a stream reach (86400 in sagehen example) dleak = 0.0001; %Tolerance level of stream depth used in computing leakage between each stream (0.0001 in sagehen example) istcb1 = -1; %Flag for writing stream-aquifer leakage values (>0: file unit, <0: write to listing file) istcb2 = 0; %Flag for writing to a seperate formatted file information on inflows&outflows isfropt = 3; %defines input structure; saturated or non-saturated zone (1: No UZ; 3: UZ, unsat prop at start of simulation), sagehen uses 3 nstrail = 10; %Number of trailing-waive increments, incr for better mass balance (10-20 rec'd, sagehen uses 8) isuzn = 1; %Maximum number of vertical cells used to define the unsaturated zone beneath a stream reach (for icalc=1 (Mannings for depth): use isuzn=1) nsfrsets = 40; %Maximum number of different sets of trailing waves used to allocate arrays. irtflg = 0; %Flag whether transient streamflow routing is active project_name = 'TestProject'; % used to name the output file (.sfr) % data_indir = '/home/gcng/workspace/matlab_files/GSFLOW_pre-processor/MODFLOW_scripts/sfr_final/data/'; data_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % items reach_data_all = importdata(reach_fil); % used to write item 2: assumes NPER = 2; % used for item 3 % items 4a: # NSEG ICALC OUTSEG IUPSEG IPRIOR NSTRPTS FLOW RUNOFF ETSW PPTSW ROUGHCH ROUGHBK CDPTH FDPTH AWDTH BWDTH segment_data_4A = importdata(segment_fil_all{1}); % used to write items 4a segment_data_4B = importdata(segment_fil_all{2}); % used to write items 4b (ignored for ICALC=3 in 4a) segment_data_4C = importdata(segment_fil_all{3}); % used to write items 4c (ignored for ICALC=3 in 4a) % ------------------------------------------------------------------------- % In case the input text files (e.g. reach_data.txt) contain header lines (comments) if isstruct(reach_data_all) reach_data_all0 = reach_data_all.data; nstrm = size(reach_data_all0,1); if fl_nstrm < 0, nstrm = -nstrm; end % sort rows according to increasing segment numbers [~, ind] = sort(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')), 'ascend'); reach_data_all0 = reach_data_all0(ind,:); nss = max(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG'))); % sort rows according to increasing reach numbers for ii = 1: nss ind1 = find(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')) == ii); [~, ind2] = sort(reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')), 'ascend'); reach_data_all0(ind1,:) = reach_data_all0(ind1(ind2),:); % renumber IREACH to start at 1 for each segment reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')) = [1:length(ind1)]; end X = mat2cell(reach_data_all0, abs(nstrm), ones(size(reach_data_all0,2),1)); [KRCH,IRCH,JRCH,ISEG,IREACH,RCHLEN,STRTOP,SLOPE,STRTHICK,STRHC1,THTS,THTI,EPS,UHC] = X{:}; % -- make sure STRTOP is within 1st layer % - read in TOP and BOTM from .dis file dis_file = [GSFLOW_indir, '/', infile_pre, '.dis']; fid = fopen(dis_file); for ii = 1:2, cmt = fgets(fid); end line0 = fgets(fid); D = textscan(line0, '%d', 6); NLAY = D{1}(1); NROW = D{1}(2); NCOL = D{1}(3); NPER = D{1}(4); ITMUNI = D{1}(5); LENUNI = D{1}(6); line0 = fgets(fid); D = textscan(line0, '%d'); LAYCBD = D{1}; % 1xNLAY (0 if no confining layer) line0 = fgets(fid); D = textscan(line0, '%s %d'); DELR = D{2}; % width of column line0 = fgets(fid); D = textscan(line0, '%s %d'); DELC = D{2}; % height of row TOP = nan(NROW,NCOL); line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); TOP(irow,:) = D{1}(1:NCOL); end BOTM = nan(NROW, NCOL, NLAY); for ilay = 1: NLAY line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); BOTM(irow,:,ilay) = D{1}(1:NCOL); end end fclose(fid); % TOP for cells corresponding to reaches TOP_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), TOP_RCH(ii) = TOP(IRCH(ii),JRCH(ii)); end % BOTM for cells corresponding to reaches BOTM_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), BOTM_RCH(ii) = BOTM(IRCH(ii),JRCH(ii),KRCH(ii)); end % - set STRTOP to be just below TOP STRTOP = TOP_RCH - 2; if ~isempty(find(STRTOP-STRTHICK < BOTM_RCH,1)) fprintf('Error! STRTOP is below BOTM of the corresponding layer! Exiting...\n'); end reach_data_all0(:,strcmp(reach_data_all.colheaders, 'STRTOP')) = STRTOP; % -- plot stream reaches RCH_mask = TOP; for ii = 1:abs(nstrm), RCH_mask(IRCH(ii),JRCH(ii)) = max(TOP(:))*2; end figure subplot(2,2,1) imagesc(TOP), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); subplot(2,2,2) imagesc(RCH_mask), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); for ii = 1:abs(nstrm), RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); end for ii = 1:abs(nstrm), SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); end figure imagesc(RCH_NUM), colorbar, colormap(jet(1+max(IREACH))); caxis([-0.5 max(IREACH)+0.5]) figure imagesc(SEG_NUM), colorbar, colormap(jet(1+max(ISEG))); caxis([-0.5 max(ISEG)+0.5]) % % when running as script: to visualize segments one at a time % for j = 1: max(ISEG) % RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); % ind = find(ISEG==j); % for ii = ind(:)' % RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); % SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); % end % % figure(100) % imagesc(RCH_NUM), colorbar, % colormap(jet(1+max(RCH_NUM(:)))); % caxis([-0.5 max(RCH_NUM(:))+0.5]) % title(['reaches for seg ', num2str(j)]); % figure(101) % imagesc(SEG_NUM), colorbar, % colormap(jet(1+max(SEG_NUM(:)))); % caxis([-0.5 max(SEG_NUM(:))+0.5]) % title(['seg ', num2str(j)]); % pause % end % -- threshold slope at minimum 0.001 ind = reach_data_all0(:,strcmp(reach_data_all.colheaders, 'SLOPE')) < 0.001; reach_data_all0(ind,strcmp(reach_data_all.colheaders, 'SLOPE')) = 0.001; % -- set streambed thickness (Sagehen uses constant 1m) ind = strcmp(reach_data_all.colheaders, 'STRTHICK'); reach_data_all0(:,ind) = 1; % [m] % -- set streambed hydraulic conductivity (Sagehen example: 5 m/d) ind = strcmp(reach_data_all.colheaders, 'STRHC1'); reach_data_all0(:,ind) = 5; % set streambed theta_s ind = strcmp(reach_data_all.colheaders, 'THTS'); reach_data_all0(:,ind) = 0.35; % set streambed initial theta ind = strcmp(reach_data_all.colheaders, 'THTI'); reach_data_all0(:,ind) = 0.3; % set streambed Brooks-Corey exp (sagehen example is 3.5) ind = strcmp(reach_data_all.colheaders, 'EPS'); reach_data_all0(:,ind) = 3.5; % set streambed unsaturated zone saturated hydraulic conductivity % (sagehen example is 0.3 m/d) ind = strcmp(reach_data_all.colheaders, 'UHC'); reach_data_all0(:,ind) = 0.3; reach_data_all = reach_data_all0; end if isstruct(segment_data_4A) segment_data_4A = segment_data_4A.data; nss = size(segment_data_4A,1); %Number of stream segments end if isstruct(segment_data_4B) segment_data_4B = segment_data_4B.data; end if isstruct(segment_data_4C) segment_data_4C = segment_data_4C.data; end % if isstruct(stress_periods) % stress_periods = stress_periods.data; % end % - specify only for 2 stress periods: stress_periods = zeros(NPER, 3); % itmp, irdflg, iptflg (latter 2 are set to 0) stress_periods(1,1) = nss; if NPER > 1, stress_periods(2:end,1) = -1; end % ------------------------------------------------------------------------- % First put 4A, 4B and 4C data all together in a cell array % size(cell) = nitems x 1 x nperiods % In this case, nitems is 3 (i.e. 4A, 4B and 4C) nitems = 3; nperiods = size(stress_periods, 1); segment_data_all = cell(nitems, 1, nperiods); segment_data_all{1, 1, 1} = segment_data_4A; segment_data_all{2, 1, 1} = segment_data_4B; segment_data_all{3, 1, 1} = segment_data_4C; % ------------------------------------------------------------------------- % validate some of the input data msg_invalidISFROPT = ['Error: ISFROPT should be set to an integer of', ... '1, 2, 3, 4 or 5.']; if (nstrm < 0) if ~ismember(isfropt, [1, 2, 3, 4, 5]) error(msg_invalidISFROPT); end end msg_notSupport = ['Error: %s: this variable must be zero because ', ... 'parameters are not supported in GSFLOW.']; if (nsfrpar ~= 0) error(msg_notSupport, 'NSFRPAR'); end if (nparseg ~= 0) error(msg_notSupport, 'NPARSEG'); end % ------------------------------------------------------------------------- % Ouput file fid = fopen([GSFLOW_indir, '/', sfr_file], 'wt'); % Write header lines (item 0) heading = '# Streamflow-Routing (SFR7) input file.\n'; fprintf(fid, heading); fprintf(fid, '# %s simulation -- created on %s.\n', upper(project_name), date); % Item 1 fprintf(fid, ' %5d %5d %5d %5d %8.2f %8.4f %5d %5d', ... nstrm, nss, nsfrpar, nparseg, const, dleak, istcb1, istcb2); if (isfropt >= 1) fprintf(fid, ' %5d', isfropt); if (isfropt == 1) fprintf(fid, ' %5d\n', irtflg); elseif (isfropt > 1) fprintf(fid, ' %5d %5d %5d %5d\n', nstrail, isuzn, nsfrsets, irtflg); end else fprintf(fid, '\n'); end % Item 2 if (isfropt == 1) ncols_reach = 10; elseif (isfropt == 2) ncols_reach = 13; elseif (isfropt == 3) ncols_reach = 14; else ncols_reach = 6; end reach_data_copy = reach_data_all(:, 1:ncols_reach); p = ncols_reach - 5; fmt_reach = [repmat(' %5d', 1, 5), repmat(' %8.3f', 1, p), '\n']; for istrm=1:abs(nstrm) dummy = reach_data_copy(istrm, :); fprintf(fid, fmt_reach, dummy); end % Item 3 and 4 nper = size(stress_periods, 1); for iper=1:nper % write item 3 to the file dummy3 = num2cell(stress_periods(iper, :)); [itmp, irdflg, iptflg] = dummy3{:}; fprintf(fid, ' %5d %5d %5d\n', itmp, irdflg, iptflg); if (itmp > 0) seg_inf_4a = segment_data_all{1, 1, iper}; seg_inf_4b = segment_data_all{2, 1, iper}; seg_inf_4c = segment_data_all{3, 1, iper}; for iitmp=1:itmp % start loop over itmp (num_segments) % write item 4a to the file dummy4a = num2cell(seg_inf_4a(iitmp, :)); [nseg, icalc, outseg, iupseg, iprior, nstrpts, ... flow, runoff, etsw, pptsw, roughch, roughbk, ... cdpth, fdpth, awdth, bwdth] = dummy4a{:}; fmt = [' ', repmat(' %5d', 1, 4)]; fprintf(fid, fmt, nseg, icalc, outseg, iupseg); if (iupseg > 0) fprintf(fid, ' %5d', iprior); end if (icalc == 4) fprintf(fid, ' %5d', nstrpts); end fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, flow, runoff, etsw, pptsw); if ((icalc == 1) || (icalc == 2)) fprintf(fid, ' %8.3f', roughch); end if (icalc == 2) fprintf(fid, ' %8.3f', roughbk); end if (icalc == 3) fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, cdpth, fdpth, awdth, bwdth); end fprintf(fid, '\n'); % write items 4b and 4c to the file suffixes = 'bc'; for i=1:2 % start loop over i suffix = suffixes(i); var_str = ['seg_inf_4', suffix]; var = eval(var_str); dummy4bc = num2cell(var(iitmp, :)); [hcond, thickm, elevupdn, width, ... depth, thts, thti, eps, uhc] = dummy4bc{:}; fl_no_4bc = 0; if (ismember(isfropt, [0, 4, 5]) && (icalc <= 0)) fmt = [' ', repmat(' %8.3f', 1, 5)]; fprintf(fid, fmt, hcond, thickm, elevupdn, width, depth); elseif (ismember(isfropt, [0, 4, 5]) && (icalc == 1)) fprintf(fid, ' %8.3f', hcond); if (iper == 1) % only for the first period fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); if ((isfropt == 4) || (isfropt == 5)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); end if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end elseif ((iper > 1) && (isfropt == 0)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); end elseif (ismember(isfropt, [0, 4, 5]) && (icalc >= 2)) fprintf(fid, ' %8.3f', hcond); if ~(ismember(isfropt, [4, 5]) && (iper > 1) && (icalc == 2)) fprintf(fid, ' %8.3f %8.3f', thickm, elevupdn); if (ismember(isfropt, [4, 5]) && (iper == 1) && (icalc == 2)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end end end elseif ((isfropt == 1) && (icalc <= 1)) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end elseif (ismember(isfropt, [2, 3]) && (icalc <= 1)) if (iper == 1) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end end else fl_no_4bc = 1; end if ~fl_no_4bc fprintf(fid, '\n'); end end % terminate loop over i (4b and 4c, respectively) end % terminate loop over itmp (num_segments) end % enf if (itmp > 0) end % terminate loop over iper (num_periods) fclose(fid); % ------------------------------------------------------------------------- % End of the script
github
UMN-Hydro/GSFLOW_pre-processor-master
write_ba6_MOD2.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_ba6_MOD2.m
6,007
utf_8
bfc6c92e0800b0dfe653046c07f81fc6
% write_ba6_MOD % 11/17/16 function write_ba6_MOD2(GSFLOW_indir, infile_pre, surfz_fil, mask_fil, NLAY, DZ) % % ==== TO RUN AS SCRIPT =================================================== % clear all, close all, fclose all; % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % ========================================================================= %% % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; ba6_file = [infile_pre, '.ba6']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 1; % NROW = 50; % NCOL = 50; % -- IBOUND(NROW,NCOL,NLAY): <0 const head, 0 no flow, >0 variable head % use basin mask (set IBOUND>0 within watershed, =0 outside watershed, <0 at discharge point and 2 neighboring pixels) % mask_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/basinmask_dischargept.asc'; fid = fopen(mask_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); D = textscan(fid, '%f'); IBOUND = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL D = textscan(fid, '%s %s %f %s %f'); dischargePt_rowi = D{3}; dischargePt_coli = D{5}; fclose(fid); % - force some cells to be active to correspond to stream reaches IBOUND(14,33) = 1; IBOUND(11,35) = 1; IBOUND(12,34) = 1; IBOUND(7,43) = 1; % find boundary cells IBOUNDin = IBOUND(2:end-1,2:end-1); IBOUNDu = IBOUND(1:end-2,2:end-1); % up IBOUNDd = IBOUND(3:end,2:end-1); % down IBOUNDl = IBOUND(2:end-1,1:end-2); % left IBOUNDr = IBOUND(2:end-1,3:end); % right % - inner boundary is constant head ind_bound = IBOUNDin==1 & (IBOUNDin-IBOUNDu==1 | IBOUNDin-IBOUNDd==1 | ... IBOUNDin-IBOUNDl==1 | IBOUNDin-IBOUNDr==1); % - outer boundary is constant head % ind_bound = IBOUNDin==0 & (IBOUNDin-IBOUNDu==-1 | IBOUNDin-IBOUNDd==-1 | ... % IBOUNDin-IBOUNDl==-1 | IBOUNDin-IBOUNDr==-1); % -- init head: base on TOP and BOTM % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); if ~isempty(find(NSEW ~= D{2}(1:4),1)) || NROW ~= D{2}(5) || NCOL ~= D{2}(6); fprintf('Error!! NSEW, NROW, or NCOL in data files do not match!\n'); fprintf(' (files: %d and %d\n', mask_fil, surfz_fil); fprintf('exiting...\n'); return end % - space discretization DELR = (NSEW(3)-NSEW(4))/NCOL; % width of column [m] DELC = (NSEW(1)-NSEW(2))/NROW; % height of row [m] % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % DZ = [5; 5]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % - set TOP to surface elevation [m] D = textscan(fid, '%f'); fclose(fid); TOP = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL BOTM = zeros(NROW, NCOL, NLAY); BOTM(:,:,1) = TOP-DZ(1); for ilay = 2:NLAY BOTM(:,:,ilay) = BOTM(:,:,ilay-1)-DZ(ilay); end % - make boundary cells constant head above a certain elevation % IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 4500) = -1; IBOUNDin(ind_bound & TOP(2:end-1,2:end-1) > 3500) = -1; IBOUND(2:end-1,2:end-1,1) = IBOUNDin; % - make discharge point and neighboring cells constant head IBOUND(dischargePt_rowi,dischargePt_coli,1) = -2; % downgrad of discharge pt % IBOUND(dischargePt_rowi-1,dischargePt_coli,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli+1,1) = -2; % downgrad of discharge pt IBOUND(dischargePt_rowi-1,dischargePt_coli+1,1) = -1; % neighbor points IBOUND(dischargePt_rowi+1,dischargePt_coli+1,1) = -1; IBOUND(dischargePt_rowi,dischargePt_coli,1) = 1; % downgrad of discharge pt IBOUND = repmat(IBOUND, [1 1 NLAY]); % - initHead(NROW,NCOL,NLAY) initHead = BOTM(:,:,1) + (TOP-BOTM(:,:,1))*0.9; % within top layer initHead = repmat(initHead, [1, 1, NLAY]); % - assumed values HNOFLO = -999.99; %% ------------------------------------------------------------------------ % -- Write ba6 file fil_ba6_0 = [GSFLOW_indir, slashstr, ba6_file]; fmt1 = [repmat('%4d ', 1, NCOL), '\n']; % for IBOUND fmt2 = [repmat('%7g ', 1, NCOL), '\n']; % for initHead fid = fopen(fil_ba6_0, 'wt'); fprintf(fid, '# basic package file --- %d layers, %d rows, %d columns\n', NLAY, NROW, NCOL); fprintf(fid, 'FREE\n'); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 IBOUND for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt1, IBOUND(:,:,ilay)'); end fprintf(fid, ' %f HNOFLO\n', HNOFLO); for ilay = 1: NLAY fprintf(fid, 'INTERNAL 1 (FREE) 3 init head for layer %d \n', ilay); % 1: CNSTNT multiplier, 3: IPRN>0 to print input to list file fprintf(fid, fmt2, initHead(:,:,ilay)'); end fclose(fid); % -- Plot basics for ii = 1:2 if ii == 1, X0 = IBOUND; ti0 = 'IBOUND'; elseif ii == 2 X0 = initHead; ti0 = 'init head'; end figure for ilay = 1:NLAY subplot(2,2,double(ilay)) X = X0(:,:,ilay); m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; % cm(1,:) = [1 1 1]; colormap(cm); colorbar title([ti0, ' lay', num2str(ilay)]); end end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_OC_PCG_MOD_f.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_OC_PCG_MOD_f.m
2,481
utf_8
f551b71b3d0abcd9c4944b5d685e002b
% write_OC_PCG_MOD.m % 11/20/16 function write_OC_PCG_MOD_f(GSFLOW_indir, infile_pre, perlen_tr) % clear all, close all, fclose all; % - write to this file % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; fil_pcg = [infile_pre, '.pcg']; fil_oc = [infile_pre, '.oc']; slashstr = '/'; % -- shoud match .dis NPER = 2; % 1 SS then 1 transient PERLEN = [1; perlen_tr]; % 2 periods: 1-day steady-state and multi-day transient NSTP = PERLEN; % -- pcg and oc files are not changed with this script % fil_pcg_0 = fullfile(MODtest_dir0, fil_pcg); fil_pcg_0 = [GSFLOW_indir, slashstr, fil_pcg]; fid = fopen(fil_pcg_0, 'wt'); % fprintf(fid, '# Preconditioned conjugate-gradient package\n'); % fprintf(fid, ' 50 30 1 MXITER, ITER1, NPCOND\n'); % fprintf(fid, ' 0000.001 .001 1. 2 1 1 1.00\n'); % fprintf(fid, ' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n'); % % sagehen example: % fprintf(fid, '# Preconditioned conjugate-gradient package\n'); % fprintf(fid, ' 1000 450 1 MXITER, ITER1, NPCOND\n'); % fprintf(fid, ' 0.001 0.08 1.0 2 1 0 -0.05 0.70\n'); % fprintf(fid, ' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n'); % sagehen example: fprintf(fid, '# Preconditioned conjugate-gradient package\n'); fprintf(fid, ' 1000 450 1 MXITER, ITER1, NPCOND\n'); fprintf(fid, ' 0.001 0.08 1.0 2 1 0 -0.05 0.70\n'); fprintf(fid, ' HCLOSE, RCLOSE, RELAX, NBPOL, IPRPCG, MUTPCG damp\n'); fclose(fid); % fil_oc_0 = (MODtest_dir0, fil_oc); % "PRINT": to listing file % "SAVE": to file with unit number in name file fil_oc_0 = [GSFLOW_indir, slashstr, fil_oc]; fid = fopen(fil_oc_0, 'wt'); fprintf(fid, 'HEAD PRINT FORMAT 20\n'); fprintf(fid, 'HEAD SAVE UNIT 51\n'); fprintf(fid, 'COMPACT BUDGET AUX\n'); fprintf(fid, 'IBOUND SAVE UNIT 52\n'); for per_i = 1:NPER for stp_i = 1:30:NSTP(per_i) fprintf(fid, 'PERIOD %d STEP %d\n', per_i, stp_i); if stp_i == NSTP(per_i) % only at end of stress period fprintf(fid, ' PRINT HEAD\n'); fprintf(fid, ' SAVE IBOUND\n'); fprintf(fid, ' PRINT BUDGET\n'); end fprintf(fid, ' SAVE HEAD\n'); fprintf(fid, ' SAVE BUDGET\n'); end end fclose(fid);
github
UMN-Hydro/GSFLOW_pre-processor-master
write_dis_MOD2_f_ok.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_dis_MOD2_f_ok.m
5,215
utf_8
742208d6af6018bc30137be25b31f571
% write_dis_MOD (for 3D domains) % 11/17/16 % % v1 - 11/30/16 start to include GIS data for Chimborazo's Gavilan Machay % watershed; topo.asc for surface elevation (fill in bottom elevation % based on uniform thickness of single aquifer) function write_dis_MOD2_f(GSFLOW_indir, infile_pre, surfz_fil, NLAY, DZ) % % ==== TO RUN AS SCRIPT =================================================== % % - directories % % MODFLOW input files % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % % % infile_pre = 'test1lay'; % % NLAY = 1; % % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % infile_pre = 'test2lay'; % NLAY = 2; % DZ = [50; 50]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % % % for various files: ba6, dis, uzf, lpf % surfz_fil = [GIS_indir, 'topo.asc']; % % for various files: ba6, uzf % mask_fil = [GIS_indir, 'basinmask_dischargept.asc']; % % ========================================================================= % %% % clear all, close all, fclose all; % - write to this file % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; dis_file = [infile_pre, '.dis']; % - read in this file for surface elevation (for TOP(NROW,NCOL)) % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; % - read in this file for elevation of layer bottoms (for BOTM(NROW,NCOL,NLAY)) % (layer 1 is top layer) botmz_fil = ''; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 1; % NROW = 1058; % NCOL = 1996; % % - domain boundary (UTM zone 17S, outer boundaries) % north = 9841200; % south = 9835900; % east = 751500; % west = 741500; % % - space discretization % DELR = (east-west)/NCOL; % width of column [m] % DELC = (north-south)/NROW; % height of row [m] % DZ = 10; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % DZ = [5; 5]; % [NLAYx1] ***temporary: constant 10m thick single aquifer (consider 2-layer?) % - time discretization PERLEN = [1; 365]; % 2 periods: 1-day steady-state and multi-day transient comment1 = '# test file for Gavilan Machay'; comment2 = '# test file'; % - The following will be assumed: LAYCBD = zeros(NLAY,1); % no confining layer below layer ITMUNI = 4; % [d] LENUNI = 2; % [m] NPER = 2; % 1 SS then 1 transient NSTP = PERLEN; TSMULT = 1; % must have daily time step to correspond with PRMS SsTr_flag = ['ss'; 'tr']; %% ------------------------------------------------------------------------ % -- Read in data from files fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); % - space discretization DELR = (NSEW(3)-NSEW(4))/NCOL; % width of column [m] DELC = (NSEW(1)-NSEW(2))/NROW; % height of row [m] % - set TOP to surface elevation [m] D = textscan(fid, '%f'); fclose(fid); fprintf('Done reading...\n'); TOP = reshape(D{1}, NCOL, NROW)'; % NROW x NCOL BOTM = zeros(NROW, NCOL, NLAY); BOTM(:,:,1) = TOP-DZ(1); for ilay = 2:NLAY BOTM(:,:,ilay) = BOTM(:,:,ilay-1)-DZ(ilay); end % -- Discretization file: fmt1 = [repmat('%4d ', 1, NCOL), '\n']; % fmt2 = [repmat('%10g ', 1, NCOL), '\n']; % fid = fopen([GSFLOW_indir, '/', dis_file], 'wt'); fmt3 = [repmat(' %d', 1, NLAY), '\n']; % for LAYCBD fprintf(fid, '%s\n', comment1); fprintf(fid, '%s\n', comment2); fprintf(fid, ' %d %d %d %d %d %d ', NLAY, NROW, NCOL, NPER, ITMUNI, LENUNI); fprintf(fid, ' NLAY,NROW,NCOL,NPER,ITMUNI,LENUNI\n'); fprintf(fid, fmt3, LAYCBD); fprintf(fid, 'CONSTANT %14g DELR\n', DELR); fprintf(fid, 'CONSTANT %14g DELC\n', DELC); fprintf(fid, 'INTERNAL 1.0 (FREE) 0 TOP ELEVATION OF LAYER 1 \n'); fprintf(fid, fmt2, TOP'); for ii = 1: NLAY fprintf(fid, 'INTERNAL 1.0 (FREE) 0 BOTM ELEVATION OF LAYER %d \n', ii); fprintf(fid, fmt2, BOTM(:,:,ii)'); end for ii = 1: NPER fprintf(fid, ' %g %d %g %c%c PERLEN, NSTP, TSMULT, Ss/Tr (stress period %4d)\n', ... PERLEN(ii), NSTP(ii), TSMULT, SsTr_flag(ii,:), ii); end fclose(fid); % -- plot domain discretization figure subplot(2,2,1) imagesc(TOP), m = TOP(TOP>0); m = min(m(:)); caxis([m*0.9, max(TOP(:))]), cm = colormap; cm(1,:) = [1 1 1]; colormap(cm); colorbar title('TOP') for ilay = 1:NLAY subplot(2,2,1+double(ilay)) m = BOTM(BOTM>0); m = min(m(:)); imagesc(BOTM(:,:,ilay)), caxis([m*0.9, max(BOTM(:))]), cm = colormap; cm(1,:) = [1 1 1]; colormap(cm); colorbar title(['BOTM', ' lay', num2str(ilay)]); end figure for ilay = 1:NLAY subplot(2,2,double(ilay)) if ilay == 1 X = TOP - BOTM(:,:,ilay); else X = BOTM(:,:,ilay-1)-BOTM(:,:,ilay); end % m = X(X>0); m = min(m(:)); imagesc(X), %caxis([m*0.9, max(X(:))]), cm = colormap; cm(1,:) = [1 1 1]; colormap(cm); colorbar title(['DZ', ' lay', num2str(ilay)]); end
github
UMN-Hydro/GSFLOW_pre-processor-master
write_nam_MOD_f2_NWT.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_nam_MOD_f2_NWT.m
2,638
utf_8
3261d3b51994f10674a7eb18c50f9eaa
% write_nam_MOD % 11/20/16 function write_nam_MOD_f2_NWT(GSFLOW_indir, GSFLOW_outdir, infile_pre, fil_res_in) % v2 - allows for restart option (init) % _170916: from Leila's email, her work from spring 2017, incorporates % MODFLOW-NWT % % clear all, close all, fclose all; % % - directories % % MODFLOW input filesfil_res_in % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW'; % % MODFLOW output files % GSFLOW_outdir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/'; % - write to this file (within indir) fil_nam = [infile_pre, '.nam']; slashstr = '/'; % all assumed to be in GSFLOW_dir fil_ba6 = [infile_pre, '.ba6']; fil_lpf = [infile_pre, '.lpf']; fil_pcg = [infile_pre, '.pcg']; fil_oc = [infile_pre, '.oc']; fil_dis = [infile_pre, '.dis']; fil_uzf = [infile_pre, '.uzf']; fil_sfr = [infile_pre, '.sfr']; fil_nwt = [infile_pre, '.nwt']; fil_upw = [infile_pre, '.upw']; fil_res_out = [infile_pre, '.out']; % write to restart file %% ------------------------------------------------------------------------ % -- .nam file with full paths % fil_nam_0 = fullfile(MODtest_dir0, fil_nam); fil_nam_0 = [GSFLOW_indir, slashstr, fil_nam]; fid = fopen(fil_nam_0, 'wt'); fprintf(fid, 'LIST 7 %s \n', [GSFLOW_outdir, slashstr, 'test.lst']); % MODFLOW output file fprintf(fid, 'BAS6 8 %s \n', [GSFLOW_indir, slashstr, fil_ba6]); fprintf(fid, 'LPF 11 %s \n', [GSFLOW_indir, slashstr, fil_lpf]); fprintf(fid, 'PCG 19 %s \n', [GSFLOW_indir, slashstr, fil_pcg]); fprintf(fid, 'OC 22 %s \n', [GSFLOW_indir, slashstr, fil_oc]); fprintf(fid, 'DIS 10 %s \n', [GSFLOW_indir, slashstr, fil_dis]); fprintf(fid, 'UZF 12 %s \n', [GSFLOW_indir, slashstr, fil_uzf]); fprintf(fid, 'SFR 13 %s \n', [GSFLOW_indir, slashstr, fil_sfr]); fprintf(fid, 'NWT 17 %s \n', [GSFLOW_indir, slashstr, fil_nwt]); fprintf(fid, 'UPW 25 %s \n', [GSFLOW_indir, slashstr, fil_upw]); if ~isempty(fil_res_in) fprintf(fid, 'IRED 90 %s \n', fil_res_in); end fprintf(fid, 'IWRT 91 %s \n', [GSFLOW_outdir, slashstr, fil_res_out]); fprintf(fid, 'DATA(BINARY) 34 %s \n', fullfile(GSFLOW_outdir, 'test.bud')); % MODFLOW LPF output file, make sure 34 is unit listed in lpf file!! fprintf(fid, 'DATA(BINARY) 51 %s \n', [GSFLOW_outdir, slashstr, 'testhead.dat']); % MODFLOW output file fprintf(fid, 'DATA(BINARY) 61 %s \n', [GSFLOW_outdir, slashstr, 'uzf.dat']); % MODFLOW output file fprintf(fid, 'DATA 52 %s \n', [GSFLOW_outdir, slashstr, 'ibound.dat']); % MODFLOW output file fclose(fid);
github
UMN-Hydro/GSFLOW_pre-processor-master
write_lpf_MOD2_f.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/write_lpf_MOD2_f.m
3,800
utf_8
a0750e358a3de9072fd4e6c5a2a92b06
% write_lpf_MOD % 11/17/16 function write_lpf_MOD2_f(GSFLOW_dir, infile_pre, surfz_fil, NLAY) % clear all, close all, fclose all; % - write to this file % GSFLOW_dir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % lpf_file = 'test.lpf'; lpf_file = [infile_pre, '.lpf']; slashstr = '/'; % - domain dimensions, maybe already in surfz_fil and botm_fil{}? % NLAY = 2; % surfz_fil = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/topo.asc'; fid = fopen(surfz_fil, 'r'); D = textscan(fid, '%s %f', 6); NSEW = D{2}(1:4); NROW = D{2}(5); NCOL = D{2}(6); fclose(fid); % -- Base hydcond, Ss (all layers), and Sy (top layer only) on data from files % (temp place-holder) hydcond = ones(NROW,NCOL,NLAY)*4; % m/d (Sagehen: 0.026 to 0.39 m/d, lower K under ridges for volcanic rocks) Ss = ones(NROW,NCOL,NLAY)* 2e-6; % constant 2e-6 /m for Sagehen Sy = ones(NROW,NCOL,NLAY)*0.15; % 0.08-0.15 in Sagehen (lower Sy under ridges for volcanic rocks) WETDRY = Sy; % = Sy in Sagehen (lower Sy under ridges for volcanic rocks) % -- assumed input values flow_filunit = 34; % make sure this matches namefile!! hdry = 1e30; % head assigned to dry cells nplpf = 0; % number of LPF parameters (if >0, key words would follow) laytyp = zeros(NLAY,1); laytyp(1) = 1; % flag, top>0: "covertible", rest=0: "confined" layave = zeros(NLAY,1); % flag, layave=1: harmonic mean for interblock transmissivity chani = ones(NLAY,1); % flag, chani=1: constant horiz anisotropy mult factor (for each layer) layvka = zeros(NLAY,1); % flag, layvka=0: vka is vert K; >0 is vertK/horK ratio VKA = hydcond; laywet = zeros(NLAY,1); laywet(1)=1; % flag, 1: wetting on for top convertible cells, 0: off for confined fl_Tr = 1; % flag, 1 for at least 1 transient stress period (for Ss and Sy) WETFCT = 1.001; % 1.001 for Sagehen, wetting (convert dry cells to wet) IWETIT = 4; % number itermations for wetting IHDWET = 0; % wetting scheme, 0: equation 5-32A is used: h = BOT + WETFCT (hn - BOT) %% ------------------------------------------------------------------------ fmt1 = repmat('%2d ', 1, NLAY); fil_lpf_0 = [GSFLOW_dir, slashstr, lpf_file]; fid = fopen(fil_lpf_0, 'wt'); fprintf(fid, '# LPF package inputs\n'); fprintf(fid, '%d %g %d ILPFCB,HDRY,NPLPF\n', flow_filunit, hdry, nplpf); fprintf(fid, [fmt1, ' LAYTYP\n'], laytyp); fprintf(fid, [fmt1, ' LAYAVE\n'], layave); fprintf(fid, [fmt1, ' CHANI \n'], chani); fprintf(fid, [fmt1, ' LAYVKA\n'], layvka); fprintf(fid, [fmt1, ' LAYWET\n'], laywet); if ~isempty(find(laywet,1)) fprintf(fid, '%g %d %d WETFCT, IWETIT, IHDWET\n', WETFCT, IWETIT, IHDWET); end % -- Write HKSAT and Ss, Sy (if Tr) in .lpf file format0 = [repmat(' %4.2f ', 1, NCOL), '\n']; format1 = [repmat(' %4.2e ', 1, NCOL), '\n']; % loop thru layers (different entry for each layer) for lay = 1: NLAY fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 HY layer %d\n', lay); % horizontal hyd cond fprintf(fid, format0, hydcond(:,:,lay)'); fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 VKA layer %d\n', lay); % vertical hyd cond fprintf(fid, format0, VKA(:,:,lay)'); if fl_Tr fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Ss layer %d\n', lay); fprintf(fid, format1, Ss(:,:,lay)'); if laytyp(lay) > 0 % convertible, i.e. unconfined fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 Sy layer %d\n', lay); fprintf(fid, format1, Sy(:,:,lay)'); if laywet(lay) > 0 fprintf(fid, 'INTERNAL 1.000E-00 (FREE) 0 WETDRY layer %d\n', lay); fprintf(fid, format0, WETDRY(:,:,lay)'); end end end end fprintf(fid, '\n'); fclose(fid);
github
UMN-Hydro/GSFLOW_pre-processor-master
make_sfr2_f_ok.m
.m
GSFLOW_pre-processor-master/matlab_scripts/MODFLOW_scripts/make_sfr2_f_ok.m
16,998
utf_8
0ad0153cb953fb0dc4dfac073cf5d6b4
% make_sfr.m % 1/8/16 % Leila Saberi % % 2 - gcng function make_sfr2_f(GSFLOW_indir, infile_pre, reach_fil, segment_fil_all) % Note: assume .dis file already created!! (reads in TOP for setting STRTOP) % % ======== TO RUN AS SCRIPT =============================================== % clear all, close all, fclose all; % GSFLOW_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/GSFLOW/inputs/MODFLOW/'; % infile_pre = 'test2lay'; % % % for sfr % GIS_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % reach_fil = [GIS_indir, 'reach_data.txt']; % segment_fil_all = cell(3,1); % segment_fil_all{1} = [GIS_indir, 'segment_data_4A_INFORMATION.txt']; % segment_fil_all{2} = [GIS_indir, 'segment_data_4B_UPSTREAM.txt']; % segment_fil_all{3} = [GIS_indir, 'segment_data_4C_DOWNSTREAM.txt']; % % ========================================================================= %% sfr_file = [infile_pre, '.sfr']; % -- Refer to GSFLOW manual p.202, SFR1 manual, and SFR2 manual % - Refer to Fig. 1 of SFR1 documentation for segment vs. reach numbering % You need the following inputs (with corresponding structures) % the followings are used to write item 1 fl_nstrm = -1; % flag for stream reaches, <0: include unsaturated zone below (sagehen: >0) nsfrpar = 0; %Always Zero nparseg = 0; %Always Zero const = 86400.; %Conversion factor used in calculating depth for a stream reach (86400 in sagehen example) dleak = 0.0001; %Tolerance level of stream depth used in computing leakage between each stream (0.0001 in sagehen example) istcb1 = -1; %Flag for writing stream-aquifer leakage values (>0: file unit, <0: write to listing file) istcb2 = 0; %Flag for writing to a seperate formatted file information on inflows&outflows isfropt = 3; %defines input structure; saturated or non-saturated zone (1: No UZ; 3: UZ, unsat prop at start of simulation), sagehen uses 3 nstrail = 10; %Number of trailing-waive increments, incr for better mass balance (10-20 rec'd, sagehen uses 8) isuzn = 1; %Maximum number of vertical cells used to define the unsaturated zone beneath a stream reach (for icalc=1 (Mannings for depth): use isuzn=1) nsfrsets = 40; %Maximum number of different sets of trailing waves used to allocate arrays. irtflg = 0; %Flag whether transient streamflow routing is active project_name = 'TestProject'; % used to name the output file (.sfr) % data_indir = '/home/gcng/workspace/matlab_files/GSFLOW_pre-processor/MODFLOW_scripts/sfr_final/data/'; data_indir = '/home/gcng/workspace/ProjectFiles/AndesWaterResources/Data/GIS/'; % items reach_data_all = importdata(reach_fil); % used to write item 2: assumes NPER = 2; % used for item 3 % items 4a: # NSEG ICALC OUTSEG IUPSEG IPRIOR NSTRPTS FLOW RUNOFF ETSW PPTSW ROUGHCH ROUGHBK CDPTH FDPTH AWDTH BWDTH segment_data_4A = importdata(segment_fil_all{1}); % used to write items 4a segment_data_4B = importdata(segment_fil_all{2}); % used to write items 4b (ignored for ICALC=3 in 4a) segment_data_4C = importdata(segment_fil_all{3}); % used to write items 4c (ignored for ICALC=3 in 4a) % ------------------------------------------------------------------------- % In case the input text files (e.g. reach_data.txt) contain header lines (comments) if isstruct(reach_data_all) reach_data_all0 = reach_data_all.data; nstrm = size(reach_data_all0,1); if fl_nstrm < 0, nstrm = -nstrm; end % sort rows according to increasing segment numbers [~, ind] = sort(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')), 'ascend'); reach_data_all0 = reach_data_all0(ind,:); nss = max(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG'))); % sort rows according to increasing reach numbers for ii = 1: nss ind1 = find(reach_data_all0(:,strcmp(reach_data_all.colheaders, 'ISEG')) == ii); [~, ind2] = sort(reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')), 'ascend'); reach_data_all0(ind1,:) = reach_data_all0(ind1(ind2),:); % renumber IREACH to start at 1 for each segment reach_data_all0(ind1,strcmp(reach_data_all.colheaders, 'IREACH')) = [1:length(ind1)]; end X = mat2cell(reach_data_all0, abs(nstrm), ones(size(reach_data_all0,2),1)); [KRCH,IRCH,JRCH,ISEG,IREACH,RCHLEN,STRTOP,SLOPE,STRTHICK,STRHC1,THTS,THTI,EPS,UHC] = X{:}; % -- make sure STRTOP is within 1st layer % - read in TOP and BOTM from .dis file dis_file = [GSFLOW_indir, '/', infile_pre, '.dis']; fid = fopen(dis_file); for ii = 1:2, cmt = fgets(fid); end line0 = fgets(fid); D = textscan(line0, '%d', 6); NLAY = D{1}(1); NROW = D{1}(2); NCOL = D{1}(3); NPER = D{1}(4); ITMUNI = D{1}(5); LENUNI = D{1}(6); line0 = fgets(fid); D = textscan(line0, '%d'); LAYCBD = D{1}; % 1xNLAY (0 if no confining layer) line0 = fgets(fid); D = textscan(line0, '%s %d'); DELR = D{2}; % width of column line0 = fgets(fid); D = textscan(line0, '%s %d'); DELC = D{2}; % height of row TOP = nan(NROW,NCOL); line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); TOP(irow,:) = D{1}(1:NCOL); end BOTM = nan(NROW, NCOL, NLAY); for ilay = 1: NLAY line0 = fgets(fid); for irow = 1: NROW line0 = fgets(fid); D = textscan(line0, '%f'); BOTM(irow,:,ilay) = D{1}(1:NCOL); end end fclose(fid); % TOP for cells corresponding to reaches TOP_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), TOP_RCH(ii) = TOP(IRCH(ii),JRCH(ii)); end % BOTM for cells corresponding to reaches BOTM_RCH = nan(abs(nstrm),1); for ii = 1:abs(nstrm), BOTM_RCH(ii) = BOTM(IRCH(ii),JRCH(ii),KRCH(ii)); end % - set STRTOP to be just below TOP STRTOP = TOP_RCH - 2; if ~isempty(find(STRTOP-STRTHICK < BOTM_RCH,1)) fprintf('Error! STRTOP is below BOTM of the corresponding layer! Exiting...\n'); end reach_data_all0(:,strcmp(reach_data_all.colheaders, 'STRTOP')) = STRTOP; % -- plot stream reaches RCH_mask = TOP; for ii = 1:abs(nstrm), RCH_mask(IRCH(ii),JRCH(ii)) = max(TOP(:))*2; end figure subplot(2,2,1) imagesc(TOP), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); subplot(2,2,2) imagesc(RCH_mask), colorbar, cm = colormap; cm(end,:) = [1 1 1]; caxis([min(TOP(:)) max(TOP(:))* 1.25]); colormap(cm); RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); for ii = 1:abs(nstrm), RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); end for ii = 1:abs(nstrm), SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); end figure imagesc(RCH_NUM), colorbar, colormap(jet(1+max(IREACH))); caxis([-0.5 max(IREACH)+0.5]) figure imagesc(SEG_NUM), colorbar, colormap(jet(1+max(ISEG))); caxis([-0.5 max(ISEG)+0.5]) % % when running as script: to visualize segments one at a time % for j = 1: max(ISEG) % RCH_NUM = zeros(NROW,NCOL); SEG_NUM = zeros(NROW,NCOL); % ind = find(ISEG==j); % for ii = ind(:)' % RCH_NUM(IRCH(ii),JRCH(ii)) = IREACH(ii); % SEG_NUM(IRCH(ii),JRCH(ii)) = ISEG(ii); % end % % figure(100) % imagesc(RCH_NUM), colorbar, % colormap(jet(1+max(RCH_NUM(:)))); % caxis([-0.5 max(RCH_NUM(:))+0.5]) % title(['reaches for seg ', num2str(j)]); % figure(101) % imagesc(SEG_NUM), colorbar, % colormap(jet(1+max(SEG_NUM(:)))); % caxis([-0.5 max(SEG_NUM(:))+0.5]) % title(['seg ', num2str(j)]); % pause % end % -- threshold slope at minimum 0.001 ind = reach_data_all0(:,strcmp(reach_data_all.colheaders, 'SLOPE')) < 0.001; reach_data_all0(ind,strcmp(reach_data_all.colheaders, 'SLOPE')) = 0.001; % -- set streambed thickness (Sagehen uses constant 1m) ind = strcmp(reach_data_all.colheaders, 'STRTHICK'); reach_data_all0(:,ind) = 1; % [m] % -- set streambed hydraulic conductivity (Sagehen example: 5 m/d) ind = strcmp(reach_data_all.colheaders, 'STRHC1'); reach_data_all0(:,ind) = 5; % set streambed theta_s ind = strcmp(reach_data_all.colheaders, 'THTS'); reach_data_all0(:,ind) = 0.35; % set streambed initial theta ind = strcmp(reach_data_all.colheaders, 'THTI'); reach_data_all0(:,ind) = 0.3; % set streambed Brooks-Corey exp (sagehen example is 3.5) ind = strcmp(reach_data_all.colheaders, 'EPS'); reach_data_all0(:,ind) = 3.5; % set streambed unsaturated zone saturated hydraulic conductivity % (sagehen example is 0.3 m/d) ind = strcmp(reach_data_all.colheaders, 'UHC'); reach_data_all0(:,ind) = 0.3; reach_data_all = reach_data_all0; end if isstruct(segment_data_4A) segment_data_4A = segment_data_4A.data; nss = size(segment_data_4A,1); %Number of stream segments end if isstruct(segment_data_4B) segment_data_4B = segment_data_4B.data; end if isstruct(segment_data_4C) segment_data_4C = segment_data_4C.data; end % if isstruct(stress_periods) % stress_periods = stress_periods.data; % end % - specify only for 2 stress periods: stress_periods = zeros(NPER, 3); % itmp, irdflg, iptflg (latter 2 are set to 0) stress_periods(1,1) = nss; if NPER > 1, stress_periods(2:end,1) = -1; end % ------------------------------------------------------------------------- % First put 4A, 4B and 4C data all together in a cell array % size(cell) = nitems x 1 x nperiods % In this case, nitems is 3 (i.e. 4A, 4B and 4C) nitems = 3; nperiods = size(stress_periods, 1); segment_data_all = cell(nitems, 1, nperiods); segment_data_all{1, 1, 1} = segment_data_4A; segment_data_all{2, 1, 1} = segment_data_4B; segment_data_all{3, 1, 1} = segment_data_4C; % ------------------------------------------------------------------------- % validate some of the input data msg_invalidISFROPT = ['Error: ISFROPT should be set to an integer of', ... '1, 2, 3, 4 or 5.']; if (nstrm < 0) if ~ismember(isfropt, [1, 2, 3, 4, 5]) error(msg_invalidISFROPT); end end msg_notSupport = ['Error: %s: this variable must be zero because ', ... 'parameters are not supported in GSFLOW.']; if (nsfrpar ~= 0) error(msg_notSupport, 'NSFRPAR'); end if (nparseg ~= 0) error(msg_notSupport, 'NPARSEG'); end % ------------------------------------------------------------------------- % Ouput file fid = fopen([GSFLOW_indir, '/', sfr_file], 'wt'); % Write header lines (item 0) heading = '# Streamflow-Routing (SFR7) input file.\n'; fprintf(fid, heading); fprintf(fid, '# %s simulation -- created on %s.\n', upper(project_name), date); % Item 1 fprintf(fid, ' %5d %5d %5d %5d %8.2f %8.4f %5d %5d', ... nstrm, nss, nsfrpar, nparseg, const, dleak, istcb1, istcb2); if (isfropt >= 1) fprintf(fid, ' %5d', isfropt); if (isfropt == 1) fprintf(fid, ' %5d\n', irtflg); elseif (isfropt > 1) fprintf(fid, ' %5d %5d %5d %5d\n', nstrail, isuzn, nsfrsets, irtflg); end else fprintf(fid, '\n'); end % Item 2 if (isfropt == 1) ncols_reach = 10; elseif (isfropt == 2) ncols_reach = 13; elseif (isfropt == 3) ncols_reach = 14; else ncols_reach = 6; end reach_data_copy = reach_data_all(:, 1:ncols_reach); p = ncols_reach - 5; fmt_reach = [repmat(' %5d', 1, 5), repmat(' %8.3f', 1, p), '\n']; for istrm=1:abs(nstrm) dummy = reach_data_copy(istrm, :); fprintf(fid, fmt_reach, dummy); end % Item 3 and 4 nper = size(stress_periods, 1); for iper=1:nper % write item 3 to the file dummy3 = num2cell(stress_periods(iper, :)); [itmp, irdflg, iptflg] = dummy3{:}; fprintf(fid, ' %5d %5d %5d\n', itmp, irdflg, iptflg); if (itmp > 0) seg_inf_4a = segment_data_all{1, 1, iper}; seg_inf_4b = segment_data_all{2, 1, iper}; seg_inf_4c = segment_data_all{3, 1, iper}; for iitmp=1:itmp % start loop over itmp (num_segments) % write item 4a to the file dummy4a = num2cell(seg_inf_4a(iitmp, :)); [nseg, icalc, outseg, iupseg, iprior, nstrpts, ... flow, runoff, etsw, pptsw, roughch, roughbk, ... cdpth, fdpth, awdth, bwdth] = dummy4a{:}; fmt = [' ', repmat(' %5d', 1, 4)]; fprintf(fid, fmt, nseg, icalc, outseg, iupseg); if (iupseg > 0) fprintf(fid, ' %5d', iprior); end if (icalc == 4) fprintf(fid, ' %5d', nstrpts); end fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, flow, runoff, etsw, pptsw); if ((icalc == 1) || (icalc == 2)) fprintf(fid, ' %8.3f', roughch); end if (icalc == 2) fprintf(fid, ' %8.3f', roughbk); end if (icalc == 3) fmt = repmat(' %8.3f', 1, 4); fprintf(fid, fmt, cdpth, fdpth, awdth, bwdth); end fprintf(fid, '\n'); % write items 4b and 4c to the file suffixes = 'bc'; for i=1:2 % start loop over i suffix = suffixes(i); var_str = ['seg_inf_4', suffix]; var = eval(var_str); dummy4bc = num2cell(var(iitmp, :)); [hcond, thickm, elevupdn, width, ... depth, thts, thti, eps, uhc] = dummy4bc{:}; fl_no_4bc = 0; if (ismember(isfropt, [0, 4, 5]) && (icalc <= 0)) fmt = [' ', repmat(' %8.3f', 1, 5)]; fprintf(fid, fmt, hcond, thickm, elevupdn, width, depth); elseif (ismember(isfropt, [0, 4, 5]) && (icalc == 1)) fprintf(fid, ' %8.3f', hcond); if (iper == 1) % only for the first period fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); if ((isfropt == 4) || (isfropt == 5)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); end if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end elseif ((iper > 1) && (isfropt == 0)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thickm, elevupdn, width); end elseif (ismember(isfropt, [0, 4, 5]) && (icalc >= 2)) fprintf(fid, ' %8.3f', hcond); if ~(ismember(isfropt, [4, 5]) && (iper > 1) && (icalc == 2)) fprintf(fid, ' %8.3f %8.3f', thickm, elevupdn); if (ismember(isfropt, [4, 5]) && (iper == 1) && (icalc == 2)) fmt = repmat(' %8.3f', 1, 3); fprintf(fid, fmt, thts, thti, eps); if (isfropt == 5) fprintf(fid, ' %8.3f', uhc); end end end elseif ((isfropt == 1) && (icalc <= 1)) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end elseif (ismember(isfropt, [2, 3]) && (icalc <= 1)) if (iper == 1) fprintf(fid, ' %8.3f', width); if (icalc <= 0) fprintf(fid, ' %8.3f', depth); end end else fl_no_4bc = 1; end if ~fl_no_4bc fprintf(fid, '\n'); end end % terminate loop over i (4b and 4c, respectively) end % terminate loop over itmp (num_segments) end % enf if (itmp > 0) end % terminate loop over iper (num_periods) fclose(fid); % ------------------------------------------------------------------------- % End of the script