Im trying to studie likelihood estimation of the transition and emission matrices of an Hmm via a sequence of observation provided from 2 hidden states and 3 possible values at each state
using SeqHmm to generate the sequence
#déclaration des matrices de transition et d 'emission
P.trans <- t(matrix(c(0.2,0.8,
0.7,0.3),nrow=2,ncol=2))
P.emiss <- t(matrix(c(0.2,0.6,0.2,
0.3,0.5,0.2),nrow=3,ncol=2))
# simuler un hmm avec la fonction du package seqHMM
sim <- simulate_hmm(n_sequence=1,transition_probs = P.trans,
emission_probs = P.emiss, initial_probs = c(1/2,1/2),
sequence_length = 100)
# transformer les observations comme un vecteur numeric
sim.obs <- as.numeric(gsub('\\-', ' ', sim$observations))
using Hamilton's 1988 to calculate the log-likelihood function
llh <- function(p,y){
# matrice de transition de la chaine cachée
trans.mat <- matrix(c(1-p[1],p[1],
p[2],1-p[2]), nrow=2, ncol = 2,byrow = TRUE)
# matrice d'émissions
emiss.mat <- matrix(c(p[3],1-p[3]-p[4],p[4],
p[5], p[6],1-p[5]-p[6]), nrow=2,ncol=3,byrow = TRUE)
# la longueur de la chaine
T <- length(y)
Pr <- numeric(T)
#distribution initiale
V <- c(1/2,1/2)
# calcul de la vraisemblance
for(c in 1:T){
w = numeric(nrow(trans.mat))
#i = Y[c-1]
j = y[c]
for (k in 1:nrow(trans.mat)) {
w[k] = 0
for (l in 1:nrow(trans.mat)) {
w[k] = w[k] + V[l]*trans.mat[l,k]*emiss.mat[l,j]
}
}
Pr[c]= sum(w)
V=w/sum(w)
}
# on ajout le - pour minimiser la fonction au lieu de la maximiser
bjf = -sum(log(Pr))
return(bjf)
}
using optim the minimize the - log-likelihood function
prob.init.optim <-c(0.5,0.1,0.3,0.4,0.3,0.7)
# lancer optim
optim(par=prob.init.optim, fn=llh, y=sim.obs)
it returns a negative probabilities values !! does any one can help ?
Related
I am writing this linear system solver for an university assignment, and I have incurred in quite a weird problem. I have defined a recursive function
for calculating the determinant of a square matrix through Laplace's first theorem, which seems to work just fine in all the test cases I have tried.
In the body of the program I then use a do loop to implement Cramer's rule for linear systems, calculating the determinant for the n matrices with the ith column substituted with the known terms of the system. At this moment the determinant function I have defined seems to start misbehaving, and in a pretty specific way: testing with dimension 3 matrices, the det of the matrix with the first column substituted is correct, but that of the second and third is the sum of what is supposed to be the correct determinant and the determinants of the preceding matrices. I am setting the value of the variable where I store this data to zero at every iteration of the loop (and there are no summation operators in that fragment of code so I can't see where this behavior would arise from). Like I said, I have tried quite a lot of test cases so it would seem unlikely that it is just a random occurrence. Since I am no expert in Fortran (nor in programming in general) it very well could be some very simple mistake I am completely missing, but for now I haven't been able to spot it.
module functions
implicit none
contains
recursive function determinant (m, mat2) result (det) !nel definire le funzioni recursive è necessario chiamare la proprietà RESULT
implicit none !e dichiarare esplicitamente la variabile che la funzione ritorna.
integer, intent(in) :: m
real, intent(in), dimension(m, m) :: mat2
integer :: x, sgn = -1
real :: submat(m-1, m-1), det
if (m == 1) then
det = mat2(1, 1)
else if(m == 0) then
det = 0
else if(m==2) then
det = mat2(1,1)*mat2(2,2) - mat2(1,2)*mat2(2,1) !calcolo esplicito del determinante di una matrice quadrata di dimensione 2
else
do x =1, m !il teorema di laplace viene applicato alla prima colonna della matrice
submat(1:x-1, 1:m-1) = mat2(1:x-1, 2:m) !si definisce la sottomatrice associata attraverso
submat(x:m-1, 1:m-1) = mat2(x+1:m, 2:m) !lo slicing dell'array multidimensionale di partenza
det = det + (sgn**(x+1))*mat2(x, 1) * determinant(m-1, submat) !implementazione ricorsiva del primo teorema di Laplace
end do
end if
end function determinant
end module functions
program gaia_leita
use functions
implicit none
real(KIND=16) :: start, finish
integer :: n, i, j, h
real, allocatable :: matrix(:,:), sol_vec(:), known_terms(:)
real, allocatable :: cramer_matrix(:,:)
real :: deter, cr_det = 0
write(*,*) "Questo programma calcola il determinante di una matrice M NxN"
write(*,*) "Inserire la dimensione della matrice:"
read(*,*) n
allocate(matrix(n, n))
write(*,*) "Inserire le entrate della matrice M riga per riga:"
do i = 1, n
do j = 1, n
read(*, *) matrix(i, j)
end do
end do
call cpu_time(start)
deter = determinant(n, matrix)
write(*, *) "Il determinante della matrice M è: |M| = ", deter
write(*,*) "Per risolvere il sistema lineare M*v = b inserire i valori dei termini noti b1...bn:"
allocate(known_terms(n))
allocate(sol_vec(n))
allocate(cramer_matrix(n, n))
do i = 1, n
read(*, *) known_terms(i)
end do
!metodo di cramer per la risoluzione dei sistemi lineari
if(deter == 0) then
write(*,*) "Il sistema non soddisfa le ipotesi del metodo di Cramer"
else
cramer_matrix = matrix
do i = 1, n
cr_det = 0
cramer_matrix = matrix
cramer_matrix(:, i) = known_terms(:)
do j = 1, n
do h=1, n
write(*,*) cramer_matrix(j, h)
end do
end do
cr_det = determinant(n, cramer_matrix)
write(*, *) cr_det
write(*,*)
sol_vec(i) = cr_det/ deter
write(*,*)
end do
end if
Write(*,*) "La soluzione del sistema è il vettore x = ( "
do i = 1, n
write(*,*) sol_vec(i), " "
end do
write(*,*) ")"
deallocate(matrix)
deallocate(known_terms)
deallocate(sol_vec)
deallocate(cramer_matrix)
call cpu_time(finish)
write(*,*) "Time elapsed:", finish-start, "seconds"
read(*,*)
end program gaia_leita
(ignore the comments, I am italian) Thanks a lot, I hope I'm not wasting anyone's time. Here is a test run:
Questo programma calcola il determinante di una matrice M NxN
Inserire la dimensione della matrice:
3
Inserire le entrate della matrice M riga per riga:
2
3
6
-5
-3
5
1
0
2
Il determinante della matrice M è: |M| = 51.0000000
Per risolvere il sistema lineare M*v = b inserire i valori dei termini noti b1...bn:
3
2
4
3.00000000
3.00000000
6.00000000
2.00000000
-3.00000000
5.00000000
4.00000000
0.00000000
2.00000000
102.000000
2.00000000
3.00000000
6.00000000
-5.00000000
2.00000000
5.00000000
1.00000000
4.00000000
2.00000000
-17.0000000
2.00000000
3.00000000
3.00000000
-5.00000000
-3.00000000
2.00000000
1.00000000
0.00000000
4.00000000
34.0000000
La soluzione del sistema è il vettore x = (
2.00000000
-0.333333343
0.666666687
)
The values following the substituted matrices are the determinants as given by the program: only the first one is correct, while the other ones are the sum of the correct value and the preceding values.
I am creating a command that gives specific information but I am unable to get the sum of some of this information out.
It doesn't give me any mistakes so I don't know what the problem is.
#client.command(aliases=["serverinfo","Server_info","Serverinfo","SERVERINFO","si","Si","SI"])
#commands.has_any_role('Moderatori', 'Triumvirato', 'Co-Triumvirato', 'Senatori', '690956686147453048')
async def ServerInfo(ctx):
author = ctx.author.name
guild = ctx.guild
#general info
name_server = guild.name
icon_server = guild.icon_url
create_server = guild.created_at
owner_server = guild.owner.name
#members info
total_member_server = guild.member_count
humans_member_server = sum(not member.bot for member in ctx.guild.members)
bots_member_server = sum(member.bot for member in ctx.guild.members)
online_member_server = sum(member.status !='offline' and not member.bot for member in ctx.guild.members)
offline_member_server = sum(member.status =='offline' and not member.bot for member in ctx.guild.members)
#specific member info
triumvirato = get(guild.roles, id=int("690951634183782461"))
user_with_triumvirato = [m for m in guild.members if triumvirato in m.roles]
count_triumvirato = len(user_with_triumvirato)
co_triumvirato = get(guild.roles, id=int("690954867346243624"))
user_with_co_triumvirato = [m for m in guild.members if co_triumvirato in m.roles]
count_co_triumvirato = len(user_with_co_triumvirato)
presidente = get(guild.roles, id=int("690956686147453048"))
user_with_presidente = [m for m in guild.members if presidente in m.roles]
count_presidente = len(user_with_presidente)
senatore = get(guild.roles, id=int("690960692051705896"))
user_with_senatore = [m for m in guild.members if senatore in m.roles]
count_senatore = len(user_with_senatore)
moderatore = get(guild.roles, id=int("700353561392971877"))
user_with_moderatore = [m for m in guild.members if moderatore in m.roles]
count_moderatore = len(user_with_moderatore)
membro = get(guild.roles, id=int("690963300707729408"))
user_with_membro = [m for m in guild.members if membro in m.roles]
count_membro = len(user_with_membro)
accademico = get(guild.roles, id=int("690964416644251750"))
user_with_accademico = [m for m in guild.members if accademico in m.roles]
count_accademico = len(user_with_accademico)
onorario = get(guild.roles, id=int("690965300769980476"))
user_with_onorario = [m for m in guild.members if onorario in m.roles]
count_onorario = len(user_with_onorario)
gamer = get(guild.roles, id=int("717907485939204126"))
user_with_gamer = [m for m in guild.members if gamer in m.roles]
count_gamer = len(user_with_gamer)
clandestino = get(guild.roles, id=int("690972809219801088"))
user_with_clandestino = [m for m in guild.members if clandestino in m.roles]
count_clandestino = len(user_with_clandestino)
official_member_count = sum(count_triumviro + count_co_triumvirato + count_co_triumvirato + count_senatore + count_moderatore + count_membro)
official_e_accademici_member_count = sum(official_member_count + count_accademico)
non_official_member_count = sum(count_onorario + count_gamer + count_clandestino)
#channels info
total_channel_server = len(guild.channels)
category_server = len(guild.categories)
text_channel_server = len(guild.text_channels)
vocal_channel_server = len(guild.voice_channels)
#role info
total_role_server = len(guild.roles)
#boost info
boost_level_server = guild.premium_tier
number_boost_server = guild.premium_subscription_count
embed = discord.Embed(
title="Informazioni del server",
description=f'Tutte le informazioni generali del nostro server {name_server}',
color=0x003399
)
embed.set_thumbnail(url='')
embed.set_footer(text=f'Richiesto da: {author}')
embed.set_thumbnail(url=f'{icon_server}')
embed.add_field(
name='Server creato il:',
value=f'{create_server}',
inline=False
)
embed.add_field(
name='Owner Attuale del server:',
value=f'{owner_server}',
inline=False
)
embed.add_field(
name='Informazioni membri:',
value=f'I membri totali sono **{total_member_server}** suddivisi in:\n**{humans_member_server}** umani , **{bots_member_server}** bot\nCi sono **{online_member_server}** online e **{offline_member_server}** offline al momento',
inline=False
)
embed.add_field(
name=f'I membri totali del {name_server} sono suddivisi in:',
value=f'{triumvirato.mention}: **{count_triumvirato}**\n{co_triumvirato}: **{count_co_triumvirato}**\n{presidente}: **{count_presidente}**\n{senatore}: **{count_senatore}**\n{moderatore}: **{count_moderatore}**\n{membro}: **{count_membro}**\n{accademico}: **{count_accademico}**\n{onorario}: **{count_onorario}**\n{gamer}: **{count_gamer}**\n{clandestino}: **{count_clandestino}**\n\nI membri ufficiali sono **{official_member_count}** e se contassimo pure gli accademici il totale salirebbe a **{official_e_accademici_member_count}**\nIl resto è composto da **{non_official_member_count}**',
inline=False
)
embed.add_field(
name='Informazioni canali:',
value=f'I canali totali sono **{total_channel_server}** su **{category_server}** categorie suddivisi in:\n**{text_channel_server}** canali testuali\n**{vocal_channel_server}** canali vocali.',
inline=False
)
embed.add_field(
name=f'Numero totale dei ruoli:',
value=f'**{total_role_server}**',
inline=False
)
embed.add_field(
name='Livello Boost del server:',
value=f'**{boost_level_server}**',
inline=True
)
embed.add_field(
name='Numero totale di Boost ricevuti:',
value=f'**{number_boost_server}**',
inline=True
)
await ctx.send(embed=embed)
Specifically I have problems here:
official_member_count = sum(count_triumviro + count_co_triumvirato + count_co_triumvirato + count_senatore + count_moderatore + count_membro)
official_e_accademici_member_count = sum(official_member_count + count_accademico)
non_official_member_count = sum(count_onorario + count_gamer + count_clandestino)
embed.add_field(
name=f'I membri totali del {name_server} sono suddivisi in:',
value=f'{triumvirato.mention}: **{count_triumvirato}**\n{co_triumvirato}: **{count_co_triumvirato}**\n{presidente}: **{count_presidente}**\n{senatore}: **{count_senatore}**\n{moderatore}: **{count_moderatore}**\n{membro}: **{count_membro}**\n{accademico}: **{count_accademico}**\n{onorario}: **{count_onorario}**\n{gamer}: **{count_gamer}**\n{clandestino}: **{count_clandestino}**\n\nI membri ufficiali sono **{official_member_count}** e se contassimo pure gli accademici il totale salirebbe a **{official_e_accademici_member_count}**\nIl resto è composto da **{non_official_member_count}**',
inline=False
)
What it should bring is to show the complete sum of some roles to have an even more detailed statistic.
count_onorario + count_gamer + count_clandestino is already a sum, you don't have to call sum on it
I solved the problem:
official_member_count = len(user_with_triumvirato) + len(user_with_co_triumvirato) + len(user_with_presidente) + len(user_with_senatore) + len(user_with_moderatore) + len(user_with_membro)
official_e_accademici_member_count = len(user_with_triumvirato) + len(user_with_co_triumvirato) + len(user_with_presidente) + len(user_with_senatore) + len(user_with_moderatore) + len(user_with_membro) + len(user_with_accademico)
non_official_member_count = len(user_with_gamer) + len(user_with_onorario) + len(user_with_clandestino)
Before it did not go because I simply added between variables, instead we have to do the sum using the len function on each role in which we want to add.
I'm working with signal processing in Scilab. A low pass Butterworth filter was chosen to be applied to experimental data. First, I've created a test signal and the butterworth filter just works fine. But, when I've tried to do the same steps to the experimental data an error has occurred.
The function flts shows a message which says "flts: Arguments #1 and #2: Incompatible sizes.". How can I debug this?
I've had already tried the system function and did not work. The z variable receives the experimental data. There are some comments in Portuguese (sorry).
Here are the Scilab code:
//artificial signal for the butterworth filter
//
//clear all
clear
//
//Data
//
//acceleration data (z)
z=[];
//
//
//Sampling frequency (Hz);
wap=428;
//
//Signal frequency (Hz)
//fs=6;
//
//Noise frequency (Hz)
fn=10;
//
//Cut off frequecy (fcut)
fcut=fn/wap;
//
//Butteworth filter order (k)
k=2;
//
//Time unit=2^n (unidTempo)
n=9;
unidTempo=2^n;
//
//Time length (tempoMaximo)
tempoMaximo=(1/wap)*unidTempo;
//time
tt=0:(1/wap):((unidTempo-1)*(1/wap));
t=tt';
//
//
//Extract data length from z equals to 2^n
sn=z(1:unidTempo,1);
//
//
//
//
///////////////////////////////////// FAST FOURIER TRANSFORM - FFT ////////////////////////////////////////////////////////////////////////////////////////////
//Total time and lenght of the sample
ttotal=t($);
N=length(sn);
//
//Tempo para cada amostra (tamostra)
tamostra=ttotal/N;
//
//Taxa de aquisição (T)
T=1/tamostra;
//
//Determinar 2^n, onde n deve ser menor ou igual a Nrdt1
//n= ;
_2n=N;
//
//FFT
FFT=fft(sn);
//
//Para determinar a frequência é necessário realizar N-1. Neste caso, cria-se um vetor de uma linha e depois transforma-o em colunna. Deve-se incluir a
//variável (Nfft=1:1:___), onde o último espaço deve ser igual ao número de registros de aceleração.Assim:
Nfft=1:1:N;
//
//A transformação da linha em coluna é:
Nfft_t=Nfft';
//
//O N-1 sempre apresenta o primeiro valor da célula igual a zero e é realizado com:
N_1=Nfft_t-1;
//
//Dados de frequência - o primeiro valor é sempre zero:
fft_freq=(T/N)*(N_1);
//
//Dados de magnitude
fft_mag=(T/N)*abs(FFT);
//
//Gráfico de frequência resultante - selecionar apenas metade do gráfico
plot(fft_freq,fft_mag);xlabel('Frequência (Hz)');ylabel('Magnitude (dB)');title('Frequência x Magnitude');
//
//
//
//
//
//
///////////////////////////////////////////////////////////////////////////Filtro Butterworth from iir function//
hz=iir(k,'lp','butt',[fcut 0],[])
//Change from transfer function to linear system
sl= tf2ss(hz)
//
//Filter the signal
fs=flts(sn,sl);
The input parameter to flts must be of size 1xn in your case (sl has one input), so change the last line to
fs=flts(sn',sl);
or make sure that input vector is always a row vector.
I want to generate a PWM signal. I have not achieved the expected result.
close all
clear all
fs=1000;
ts=1/fs;
t=[-5:ts:5];
fc =10; %Frecuencia señal portadora
fm = 1; %Frecuencia señal del mensaje
a = 5; %Amplitud de la señal portadora
b = 0.25; %Amplitud de la señal del mensaje
vm = b.*sin(2*pi*fm*t); %Genera la Señal del mensaje
bits = [1, 0, 1, 1];
amp = (2*bits-1);
vc = rect(t/b) + rect((t+1)/b) ...
+ rect((t+2)/b) + rect((t+3)/b)+ rect((t+4)/b)+ rect((t+5)/b)+...
rect((t-1)/b) ...
+ rect((t-2)/b) + rect((t-3)/b)+ rect((t-4)/b)+ rect((t-5)/b)
n = length(vc);
for i = 1:n
if (vm(i)>=vc(i))
pwm(i) = 1;
else
pwm(i) = 0;
end
end
I don't get the real PWM signal. Help me.
The below Latex is written in one line, but it could have been over several.
The problem is # in caption commands have to be escaped, so the question is how to do this only within captions?
Or does there exist a Perl/Ruby module that can find the closing } in such a complicated case?
\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel} og eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
Here is a brute force solution in Ruby, now that you have added the Ruby tag. It is not efficient, but safe and simple.
x.split('\caption').each_with_index.map { |str, i|
next str if i == 0
indent = 0
end_caption = str.length
str.split('').each_with_index do |c, ci|
if c == '{'
indent = indent + 1
elsif c == '}'
indent = indent - 1
if (indent == 0)
end_caption = ci
break
end
end
end
str[0..(end_caption)].gsub(/([^\\])#/,'\1\\#')+ str[(end_caption+1)..-1]
}.join(‘\caption')
or if you are looking for a one-liner, then
x.gsub(/\\caption\{((?:[^{}]+|\{\g<1>\})+)\}/m) { |xx| Regexp.last_match[0].gsub(/([^\\])#/,’\1\\#’) }
All of these of course requires that your Latex file can compile.
For Perl you could consider Text::Balanced
This can be done in Perl using two substitutions: the first to find the \caption elements, end the second to replace all hash symbols # within the elements found
It is convenient to use Regexp::Common::balanced to match the required balanced sequence of braces
The output of this program shows the string before and after editing. It's not the best test data as there is only a single instance of a hash symbol, and none outside the \caption element, but it does show that it works with the example data
use strict;
use warnings 'all';
use feature 'say';
use Regexp::Common 'balanced';
my $latex = <<'END';
\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel} og eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
END
say $latex;
$latex =~ s{ ( \\caption $RE{balanced}{-parens=>'{}'} ) }{
$1 =~ s/#/\\#/gr;
}xeg;
say $latex;
output
\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel} og eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K }_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10 \cdot y + 13$. Se opgave \ref{exercEllipseLevel} og eksempel \href{./20-Keglesnit.pdf\#evncount.20.1}{ 20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}
Just Try this:
my $str = '\caption{\small{Et elliptisk område i planen er afgrænset af en ellipse som er niveaukurven $\mathcal{K
}_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10
\cdot y + 13$. Se opgave \ref{exercEllipseLevel} og eksempel \href{./20-Keglesnit.pdf#evncount.20.1}{
20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}';
You can modify this regex (This is what I am using in my live)
my $reg = qw/((?:[^{}]*(?:{(?:[^{}]*(?:{(?:[^{}]*(?:{[^{}]*})*[^{}]*)*})*[^{}]*)*})*[^{}]*)*)/;
$str=~s/$reg/$1=~s{\#}{\\#}gr; /seg;
print $str;
Output:
\caption{\small{Et elliptisk omrσde i planen er afgrµnset af en ellipse som er niveaukurven $\mathcal{K
}_{0}(f)$ for andengradspolynomiet $f(x,y) = 2\cdot x^{2} + 2\cdot y^{2} + 2\cdot x\cdot y -8\cdot x -10
\cdot y + 13$. Se opgave \ref{exercEllipseLevel} og eksempel \href{./20-Keglesnit.pdf\#evncount.20.1}{
20.1} i eNote \ref{tn20}.}} \label{figEllipseLevel}