% PROGRAM:        SHAPE [Seismic HAzard Parameters Evaluation]  
% VERSION:        V_2.0 [Wrapper (fast) Standalone Version] 
% LAST UPDATED:   September 2019
% COMPATIBLE with Matlab version 2017b or later
% REQUIREMENTS: "Statistics and Machine Learning" Matlab Toolbox installed
% TOOLBOX: "Hazard Analysis Toolbox" within SERA Project
% DOCUMENT: "READ_ME_SHAPE_ver2.docx"
% --------------------------------------------------------------------------------------------------------------------
% Time-and-Technology Dependent Seismic Hazard Assessment (SHA)  
% --------------------------------------------------------------------------------------------------------------------
% !!! ----------------------------  INPUT DATA REQUIREMENTS ----------------------------- !!!
% the program works with ASCII input data files (e.g. *.txt). The files needed are:
% >   File with the parameters of seismic data [mandatory]
% >   File with the parameters of production data [optional]
% >   File specifying time windows for SHA analysis [optional]
% >   Files(s) with the fields description of the corresponding parameters in the seismic data file
% >   Files(s) with the fields description of the corresponding parameters in the production data files
% FOR DETAILS on data requirements please refer to the document:
%                            "READ_ME_SHAPE_ver2.pdf"
% --------------------------------------------------------------------------------------------------------------------
% OVERVIEW:THE PROGRAM takes as input a Seismic and optionally, a Production data parameters files to provides Seismic 
% Hazard Assessment for specified time-windows, following User's specifications. 
% --------------------------------------------------------------------------------------------------------------------
% AUTHORS: K. Leptokaropoulos and S. Lasocki
% Based on magnitude distribution and stationary hazard parameters estimation functions originally developed by S. Lasocki 
% Last Updated: 01/2020, within SERA PROJECT, EU Horizon 2020 R&I 
% programme under grant agreement No.730900
% CURRENT VERSION: v2.0        ****    [WRAPPER (fast) STANDALONE VERSION!!]
%% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% PLEASE refer to the accompanying document:
%                                           "READ_ME_SHAPE_ver2.pdf" 
% for description of the Application and its requirements.
%% -----------------------------------------------------------------------------------------------------------------------
% DESCRIPTION: The Application performs time-dependent Seismic Hazard Analysis (SHA), 
% taking into account the activity rate and the magnitude distribution of seismicity 
% for selected time windows. The hazard parameters estimated are: 
%    1) The Mean Return Period (MRP) of a given magnitude, M, which is defined as the 
%       average elapsed time between the occurrence of consecutive events of M and 
%    2) The Exceedance Probability (EPR) of a given magnitude, M, within a given time 
%       period of length, T, which is defined as the probability of an earthquake of 
%      M to occur during T.  
% These hazard parameters are estimated for different time windows which are constructed 
% upon User’s particular specifications. 4 different magnitude distribution models can 
% be chosen. The input files must be in ASCII format (e.g. *.txt). A brief description 
% of the preparation process is given here:
% !!! THE USER SETS THE PARAMETERS IN LINES 115-130 !!! then the following steps are executed
% (please see in the script for more comments and details for each STEP)
% STEP_1. Upload Data
% STEP_2. Select Magnidue Scale
% STEP_3. Filter Data for Mc 
% STEP_4. TIME WINDOWS GENERATION
% STEP_5. SHA PARAMETERS ESTIMATION
% STEP_6. Plotting (optional)
% STEP_7. save OUTPUTS
% ---------------------------------------------------------------------------------------------------------------------
%% INPUT:   All input data are sufficiently explained in the script as well as 
%               while running the code (interaction with the user). NOTE that
%               all input files (seismic catalog, production data, time windows) 
%               must be in ASCII format (i.e. *.txt). 
%               Please refer to the APPLICATION DOCUMENTATION for further 
%               instructions and input data requirement specifications:  "READ_ME_SHAPE_ver2.pdf"
% ----------------------------------------------------------------------------------------------------------------------
%% OUTPUT:
%                 <> Output Report with summary of the Results as well as data and parameters used 
%                 <> Output Figure with the results in *.mat and *.jpeg formats (optional)
%                 <> Output Matlab Structure with input parameter values and output results, having
%                    as many cells as the number of time windows generated. 
%                                 Structure fields are:
%                    - Time      : vector with origin times of the events included in each time window
%                    - M         : vector with events magnitudes
%                    - Mmin      : Completeness magnitude
%                    - eps       : Magnitude round-off interval
%                    - lambd     : mean activity rate
%                    - lambd_err : events number sufficiency (0-all parametes estiamated, 1-all parameters set as NaNs)
%                    - unit      : Time Unit
%                    - method    : Magnitude Distribution Model
%                    - b         : b-value of GR law    
%                                  [applies only when "method" is set to 'GRU' or 'GRT']
%                    - h         : Kernel smoothing factor 
%                                  [applies only when "method" is set to 'NPU' or 'NPT']
%                    - xx        : Background sample for kernel magnitude estimate 
%                                  [applies only when "method" is set to 'NPU' or 'NPT']
%                    - ambd      : weigthing factors for the adaptive kernel 
%                                  [applies only when "method" is set to 'NPU' or 'NPT']
%                    - ierr      : h convergence indicator (0-converges,1-multiple zeros, 2-no zeros) 
%                                  [applies only when "method" is set to 'NPU' or 'NPT']
%                    - Mmax      : Upper limit of magnitude distribution (truncated) 
%                                  [applies only when "method" is set to 'GRT' or 'NPT']
%                    - err       : Mmax convergence indicator (0-converge, 1-no converge) 
%                                  [applies only when "method" is set to 'GRT' or 'NPT']
% -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
% REFERENCES:
% Kijko A, Lasocki S, Graham G (2001), Pure Appl. Geophys. 158:1655–1676
% Kijko A, Sellevoll MA (1989), Bull Seismol. Soc. Am. 79:645–654
% Lasocki S, Urban P (2011), Acta Geophys. 59:659–673
% Lasocki S, Orlecka-Sikora B (2008), Tectonophysics 456:28–37
% Leptokaropoulos K, Staszek M, Cielesta S, Urban P, Olszewska D, Lizurek G (2017), Acta Geophys. 65:493-505 
% ---------------------------------------------------------------------------------------------------------------------
% LICENSE 
%     This is free software: you can redistribute it and/or modify it under 
%     the terms of the GNU General Public License as published by the
%     Free Software Foundation, either version 3 of the License, or 
%     (at your option) any later version.
%     This program is distributed in the hope that it will be useful, but 
%     WITHOUT ANY WARRANTY; without even the implied warranty 
%     of MERCHANTABILITY or FITNESS FOR A PARTICULAR
%     PURPOSE. See the GNU General Public License for more details.
% -------------------------------------------------------------------------------------------------------------------

clc;clear; 
close all;

% PLEASE SET INPUT ARGUMENTS [LINES 115-131]
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SEIS_DATA='ST2_SEIS_Data.txt';               % Seismic Data File - NOTE: SEIS_DATA=[] is valid as well
SEIS_FIELDS='ST2_SEIS_Fields.txt';           % Seismic Data Fields File
PROD_DATA='ST2_PROD_Data.txt';               % Production Data (non-seismic) File - NOTE: PROD_DATA=[] is valid as well
PROD_FIELDS='ST2_PROD_Fields.txt';           % Production Data (non-seismic) Fields File
PROD_FIELD=2;                                % field (column) corresponding to a selected Production Parameter  
MScale='ML';                                 % Magnitude Scale (e.g. 'ML', 'Mw' etc). NOTE: MScale=[] is also valid
Mc=1.0;                                      % Select Mc
Mmax=3.5;                                    % Valid for GRT and NPT/ if Mmax=[], it is calculated internally
winmode='File';                              % Select MODE for windows creation: 'Time' or 'Events' or 'File'
file_n='ST2_test_timewindows.txt';           % Select file name with starting and ending time of time windows, applicable only for winmode='File'
window_size=30;                              % time window span (days or events, depending on "winmode")
dt=30;                                       % time step (days)
method='NPU';                                % Select M distribution model among 'GRU','GRT','NPU','NPT'
Tunit='month';                                 % Select time unit among 'day', 'month', 'year'
MaG=3.0;                                     % set target Magnitude for EPR and MRP calculation
Plength=1;                                   % set target time Period (days) for EPR calculation
Plotopt='ON';                                % To enable ('ON') or disable ('OFF') plotting
%% -------------------------------------------------------------------------------------------------------------------------

if method=='GRT' & isempty(Mmax)==0 & MaG>Mmax | method=='NPT' & isempty(Mmax)==0 & MaG>Mmax 
error('Mmax is smaller than the target magnitude (MaG), please change input')
end

%% STEP 1:  Load data
[Catalog,PROD_Data,s1]=Data_Hand_A2M_ver2...
    (SEIS_DATA,SEIS_FIELDS,PROD_DATA,PROD_FIELDS,PROD_FIELD);

%% STEP 2: Select Magnitude Scale
[Ctime,Cmag]=Select_Magnitude_Scale_ver2(Catalog,MScale);

%% STEP 3: Filter data for Mc
[Ctime,Cmag,Catalog]=FiltMc_ver2(Ctime,Cmag,Catalog,s1,Mc);


%% STEP 4: Create Time Windows
time_windows=struct;time_windows.Time=[];
 to=Ctime-Ctime(1);tmin=min(to);tmax=max(to);

switch winmode
%%    TIME 
    case 'Time'
        if window_size>tmax;n=1;warning('time window is set larger than data time span');end
        n=ceil((tmax-window_size)/dt);
        for i=1:n
        time_windows(i).Time=Ctime(to>=(i-1)*dt & to<(i-1)*dt+window_size);
        time_windows(i).M=Cmag(to>=(i-1)*dt & to<(i-1)*dt+window_size);
        time_windows(i).Tstart=Ctime(1)+(i-1)*dt;
        time_windows(i).Tend=Ctime(1)+(i-1)*dt+window_size;
        end  
%%    EVENTS
    case 'Events'
 if window_size>numel(to);window_size=numel(to);warning('events window is set larger than given data');end    
   n=ceil(tmax/dt);
        for i=1:n
        To=find(to>=(i-1)*dt);To=To(1);
        if To<=length(Ctime)-window_size+1;
        time_windows(i).Time=Ctime(To:To+window_size-1);
        time_windows(i).M=Cmag(To:To+window_size-1);
        time_windows(i).Tstart=Ctime(1)+(i-1)*dt;
        time_windows(i).Tend=max(time_windows(i).Time);
        end     
        end
 %%    FILE
    case 'File'
    cd TIME_WINDOWS
    Twindows=dlmread(file_n);
    T1=Twindows(:,1);T2=Twindows(:,2);n=numel(T1);
    for i=1:n
       time_windows(i).Time=Ctime(Ctime>=T1(i) & Ctime<T2(i));
       time_windows(i).M=Cmag(Ctime>=T1(i) & Ctime<T2(i));
       time_windows(i).Tstart=T1(i);
       time_windows(i).Tend=T2(i);
    end
    cd ../
end
 
%% STEP 5: ESTIMATE HAZARD PARAMETERS
if strcmp(Tunit,'day');iop=0;elseif strcmp(Tunit,'month');iop=1;elseif strcmp(Tunit,'year');iop=2;
else; error('Please set "Tunit" Parameter as "day", "month" or "year"');end

%% RUN MAGDIST
[HP] = TDHMagDistWrapper(method, time_windows, Mc, iop,Mmax)

%% Harzard Parameters Estimate
[MRPer,ExPr]=TDHRetPeriodExcProbWrapper(method,MaG,Plength,Mc,HP)


%% 
%% STEP 6: Ploting (optional)
Zplo_ver2

%% STEP 7: Save outputs
Zsave_output_ver2


%% -*-*-*-*-*-*-*-*-*-*-*-*-*- F U N C T I O N S -*-*-*-*-*-*-*-*-*-*-*-*-*-
   
%% ------------------------- DATA HANDLING FUNCTION   --------------------------

function [Catalog,PROD_data,ss1]=Data_Hand_A2M_ver2...
    (SEIS_DATA,SEIS_FIELDS,PROD_DATA,PROD_FIELDS,PROD_FIELD)

if isempty(PROD_DATA)
%% SEISMIC DATA
cd CATALOGS
 SData=load(SEIS_DATA);
 SFields=fileread(SEIS_FIELDS);
cd ../

Na=length(SFields);if SFields(Na)~=' ';SFields(Na+1)=' ';end
[cou,c,Datime,Catalog]=Fields_dat(SData,SFields,1);
ss1=1:length(Catalog);% ss1=SetParams(Catalog);%Catalog=Catalog(ss1);
PROD_data=[];ss=[];s2=[];ss2=[];dstr2=[];

else
%% ------------------------------------------------------------------------------------------------------------------------------------
% BOTH -SEISMIC and PRODUCTION DATA

cd CATALOGS                                          %Seismic Data
 SData=load(SEIS_DATA);
 SFields=fileread(SEIS_FIELDS);
cd ../

Na=length(SFields);if SFields(Na)~=' ';SFields(Na+1)=' ';end
[cou,c,Datime,Catalog]=Fields_dat(SData,SFields,1);
ss1=1:length(Catalog);
% ss1=SetParams(Catalog);%Catalog=Catalog(ss1);
 
cd PRODUCTION_DATA                         % Production (non-Seismic) Data
OData=load(PROD_DATA);
OFields=fileread(PROD_FIELDS);
cd ../

Na1=length(OFields);if OFields(Na1)~=' ';OFields(Na1+1)=' ';end
[cou1,c1,Datime1,PROD_data]=Fields_dat(OData,OFields,2);

end
 % save('Catalog_ST2_Test','Catalog')
 % save('Catalog_ST2_Test','Catalog')


%% -----------------------------------------    F U N C T I O N S    -----------------------------------------
function [cou,c,Datime,OUT]=Fields_dat(indata,infields,iop)

Datime=datenum(indata(:,1),indata(:,2),indata(:,3),indata(:,4),indata(:,5),indata(:,6));       % Convert time to matlab format

% Define Fields
c=1;
for i=1:length(infields)-1
if strcmp(infields(i),' ')==1;cou(i)=0;
else cou(i)=c;end
if strcmp(infields(i),' ')==0 & strcmp(infields(i+1),' ')==1;c=c+1;end
end

if iop==1
OUT(1).field='Occurrence_Time';OUT(1).val=Datime;
elseif iop==2
OUT(1).field='Production_Time';OUT(1).val=Datime;
end

for i=2:c-1
OUT(i).field=infields(cou==i);    
OUT(i).val=indata(:,i+5);
end

%Set Field Type for Magnitude Recognition
for i=1:size(OUT,2)
    if strcmp(OUT(i).field,'ML') || strcmp(OUT(i).field,'Mw') || strcmp(OUT(i).field,'M') ...
   || strcmp(OUT(i).field,'Ms') || strcmp(OUT(i).field,'mb') || strcmp(OUT(i).field,'Md')
         OUT(i).fieldType='Magnitude';
    else
    OUT(i).fieldType=[];
    end
end

end

%% -----------------------------------------------------------------------------------------------------------


% ----------------------------------------------------------------------------------------------------------------


end

%%
function [Ctime,Cmag,Data]=FiltMc_ver2(Ctime,Cmag,Catalog,s1,Mc)
clc
id_time=findfield(Catalog,'Occurrence_Time');
                                                                            %opts.Interpreter='tex';opts.Default='Yes';
                                                                            %quest='Do you wish to filter Data for Mc?';
                                                                            %answer=questdlg(quest,'Data Completenes','Yes','No',opts);
                                                                            %if strcmp(answer,'Yes')

%% THIS HAS MOVED TO A SEPARATE FUNCTION IN THE BEGINNING OF THE APPLICATION
% cou=1;
% for i=1:length(Catalog)
%     if strcmp(Catalog(i).fieldType,'Magnitude')==1
%         C(cou).field=Catalog(i).field;cou=cou+1;
%     end
% end
% 
% % Check for no magnitude
% if cou==1;error('MyComponent:incorrectType',...
% 'No magnitude column detected!! Please check: Magnitude fields must be noted as one of the following:\nM  ,  Mw  ,  ML  ,  Ms  ,  mb  ,  Md\n or select the entire sample for analysis');end
% 
% %Select Parameters from Seismic Catalog -
% [ss1,ok]=listdlg('PromptString','Please Select M scale:',...
%     'ListString',{C.field}, 'SelectionMode','single');
% 
%  id=findfield(Catalog,C(ss1).field);
%   Mtype=Catalog(id).field;
% Ctime=Catalog(id_time).val;
% id_M=findfield(Catalog,Mtype);
% Cmag=Catalog(id_M).val;

%% 

cou=1;


for i=1:length(s1)
    x=Catalog(s1(i)).val;x=x(Cmag>=Mc);
    index=isnan(x)==0;
    x=x(isnan(x)==0);
    Data(cou).field=Catalog(s1(i)).field;
    Data(cou).fieldType=Catalog(s1(i)).fieldType;
    Data(cou).val=nan(size(index)); Data(cou).val(index)=x;
    cou=cou+1;
end

Ctime=Ctime(Cmag>=Mc);Cmag=Cmag(Cmag>=Mc);

n=length(Ctime);
disp(['number of events: ',num2str(n)]) 

end

%% --------------------------------------------------------------------------------------
% finds a field defined by a certain (string) name
function [id] = findfield( catalog,field )
id=0;
j=1;
while j <= size(catalog,2) && id==0
        if (strcmp(catalog(j).field,field)==1)
        id=j;
        end
        j=j+1;
end
end

%% 
function [Ctime,Cmag]=Select_Magnitude_Scale_ver2(Catalog,MType)

cou=1;
for i=1:length(Catalog)
    if strcmp(Catalog(i).fieldType,'Magnitude')==1
        C(cou).field=Catalog(i).field;cou=cou+1;
    end
end

% Check for no magnitude
if cou==1;error('MyComponent:incorrectType',...
'No magnitude column detected!! Please check: Magnitude fields must be noted as one of the following:\nM  ,  Mw  ,  ML  ,  Ms  ,  mb  ,  Md\n or select the entire sample for analysis');end


 id=findfield(Catalog,MType);
 id_time=findfield(Catalog,'Occurrence_Time');
Cmag=Catalog(id).val;Ctime=Catalog(id_time).val;

end

%% -----------!!!!!!!!!!! HAZARD PARAM<ETERS ESTIMATE FUNCTIONS !!!!!!!!!!!-----------

function [HP] = TDHMagDistWrapper(method, time_win_data, mmin, iop,Mmax)
cd SSH
	for i=1:size(time_win_data,2)
		mags_vec = time_win_data(i).M;
		time_vec = time_win_data(i).Time;
		HP(i).mmin = mmin;
		HP(i).iop = iop;
		HP(i).method = method;
		switch method
			case 'GRU'
				try
					[HP(i).lamb_all, HP(i).lamb, HP(i).lamb_err, HP(i).unit, HP(i).eps, HP(i).b]=UnlimitGR(time_vec, mags_vec, iop, mmin);
                    HP(i).Mmax=NaN;
				catch err
	                HP(i).lamb_all=NaN; HP(i).lamb=NaN; HP(i).lamb_err=2; HP(i).unit=''; HP(i).eps=NaN; HP(i).b=NaN;HP(i).Mmax=NaN;
	                warning('%s: %s', err.identifier, err.message);
				end
			case 'GRT'
				try
					[HP(i).lamb_all, HP(i).lamb, HP(i).lamb_err, HP(i).unit, HP(i).eps, HP(i).b, HP(i).Mmax, HP(i).err]=TruncGR_O(time_vec, mags_vec, iop, mmin,Mmax);
				catch err
	                HP(i).lamb_all=NaN; HP(i).lamb=NaN; HP(i).lamb_err=2; HP(i).unit=''; HP(i).eps=NaN; HP(i).b=NaN; HP(i).Mmax=NaN; HP(i).err=NaN;
	                warning('%s: %s', err.identifier, err.message);
				end
			case 'NPU'
				try
					[HP(i).lamb_all, HP(i).lamb, HP(i).lamb_err, HP(i).unit, HP(i).eps, HP(i).ierr, HP(i).h, HP(i).xx, HP(i).ambd]=Nonpar_O(time_vec, mags_vec, iop, mmin);
                    HP(i).Mmax=NaN;
               catch err
	               HP(i).lamb_all=NaN; HP(i).lamb=NaN; HP(i).lamb_err=2; HP(i).unit=''; HP(i).eps=NaN; HP(i).ierr=NaN; HP(i).h=NaN; HP(i).xx=[]; HP(i).ambd=[];HP(i).Mmax=NaN;
	               warning('%s: %s', err.identifier, err.message);
				end
			case 'NPT'
				try
					[HP(i).lamb_all, HP(i).lamb, HP(i).lamb_err, HP(i).unit, HP(i).eps, HP(i).ierr, HP(i).h, HP(i).xx, HP(i).ambd, HP(i).Mmax, HP(i).err]=Nonpar_tr_O(time_vec, mags_vec, iop, mmin,Mmax);
                catch err
	                HP(i).lamb_all=NaN; HP(i).lamb=NaN; HP(i).lamb_err=2; HP(i).unit=''; HP(i).eps=NaN; HP(i).ierr=NaN; HP(i).h=NaN; HP(i).xx=[]; HP(i).ambd=[]; HP(i).Mmax=NaN; HP(i).err=NaN;
	                warning('%s: %s', err.identifier, err.message);
				end
        end
  
   %   K12NOV2015
  % Calculate lamb and lamb_all in case of 0, 1, or 2 events. 
  % It may be generalized in all cases. Rate is now calculated
  % by division of the event number by the duration of the set 
  % - not the time difference between the first and last events.
   if numel(mags_vec(mags_vec>=mmin))<3  
    HP(i).lamb_all= numel(mags_vec)/(time_win_data(i).Tend-time_win_data(i).Tstart);    
    HP(i).lamb= numel(mags_vec(mags_vec>=mmin))/(time_win_data(i).Tend-time_win_data(i).Tstart);    
       switch iop
           case 0
            %OK   
           case 1
    HP(i).lamb_all=HP(i).lamb_all*30;
    HP(i).lamb=HP(i).lamb*30;
           case 2
    HP(i).lamb_all=HP(i).lamb_all*365;           
    HP(i).lamb=HP(i).lamb*365;
       end
   end   
 %   K12NOV2015

    end

cd ../
    
end

%% 
function [MRPer,ExPr]=TDHRetPeriodExcProbWrapper(meth,mag,time_period,Mmin,HP)
        nn=size(HP,2);
        if nn==0; 'All datasets are empty'
                MRPer=[]; ExPr=[];
        else
                for i=1:nn
                    Mmax=HP(i).Mmax;
                        if HP(i).lamb_err==0;
							try
                        		[MRPer(i),ExPr(i)]=SingleRetPeriodExcProbWrapper(meth,mag,time_period,Mmin,HP(i),Mmax);
							catch err
				                MRPer(i)=NaN; ExPr(i)=NaN;
				                warning('%s: %s', err.identifier, err.message);cd ../
							end
                        else 
                        	MRPer(i)=NaN; ExPr(i)=NaN;
                        if MRPer(i)==inf;MRPer(i)=NaN;end   %K 21OCT2016
                        end
                end
        end
end

%% Function - SingleRetPeriodExcProbWrapper

function [MRPer,ExPr]=SingleRetPeriodExcProbWrapper(meth,mag,time_period,Mmin,HP,Mmax)
cd SSH
	%Md=3;Mu=3;dM=3;Mmin=0.6;
	Md = mag;
	Mu = mag;
	dM = mag;
	
	if isnan(Mmax) && isfield(HP,'Mmax')
		Mmax = HP.Mmax;
	end
	
	m = []; rper = []; prob = [];
	
	switch meth
	    case 'GRU'
	    	[m,rper]=Ret_periodGRU(Md,Mu,dM,Mmin,HP.lamb,HP.eps,HP.b);
	    	[m,prob]=ExcProbGRU(0,Md,Mu,dM,time_period,Mmin,HP.lamb,HP.eps,HP.b);
	    case 'GRT'
	    	[m,rper]=Ret_periodGRT(Md,Mu,dM,Mmin,HP.lamb,HP.eps,HP.b,Mmax);
	    	[m,prob]=ExcProbGRT(0,Md,Mu,dM,time_period,Mmin,HP.lamb,HP.eps,HP.b,Mmax);
	    case 'NPU'    
	    	[m,rper]=Ret_periodNPU(Md,Mu,dM,Mmin,HP.lamb,HP.eps,HP.h,HP.xx,HP.ambd);
	    	[m,prob]=ExcProbNPU(0,Md,Mu,dM,time_period,Mmin,HP.lamb,HP.eps,HP.h,HP.xx,HP.ambd); 
	    case 'NPT'  
	    	[m,rper]=Ret_periodNPT(Md,Mu,dM,Mmin,HP.lamb,HP.eps,HP.h,HP.xx,HP.ambd,Mmax);
	    	[m,prob]=ExcProbNPT(0,Md,Mu,dM,time_period,Mmin,HP.lamb,HP.eps,HP.h,HP.xx,HP.ambd,Mmax);
	end

	if isempty(rper)
		MRPer = NaN;
		ExPr = NaN;
	else
		MRPer = rper(1);
		ExPr = prob(1);
	end
cd ../
end


