discord.py: sum between counts - discord.py

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.

Related

function does not return embed discord.py

I have a problem with a function:
In order not to have to rewrite the same 100 strings for each if I decided to create this function that would return the embed but unfortunately it does not return the same.
I have no errors so I don't understand where the problem is
Code function:
def rob_true():
ratm = random.randrange(50, 500)
economy_system[id_other]["wallet"] -= ratm
if economy_system[id_other]["wallet"] < 0:
negative_wallet = economy_system[id_other]["wallet"]
ratm = ratm + negative_wallet
economy_system[id_other]["wallet"] = 0
economy_system[id_author]["wallet"] += ratm
if ratm < 100:
embed = discord.Embed(
title="Rob!",
description=f"Non sei stato molto fortunato.\nHai rubato solo {ratm}€ a {other.name}",
color=0x03c03c
)
embed.set_author(
name=f"{ctx.author.name}",
icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=ctx.guild.icon_url)
if 100 < ratm < 250:
embed = discord.Embed(
title="Rob!",
description=f"Ti è andata bene!\nHai rubato {ratm}€ a {other.name}",
color=0x03c03c
)
embed.set_author(
name=f"{ctx.author.name}",
icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=ctx.guild.icon_url)
if 250 < ratm < 450:
embed = discord.Embed(
title="Rob!",
description=f"Hai rubato un'ottima somma!\nHai rubato {ratm}€ a {other.name}",
color=0x03c03c
)
embed.set_author(
name=f"{ctx.author.name}",
icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=ctx.guild.icon_url)
else:
embed = discord.Embed(
title="Rob!",
description=f"Guarda che fortuna!\nHai rubato {ratm}€ a {other.name}",
color=0x03c03c
)
embed.set_author(
name=f"{ctx.author.name}",
icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=ctx.guild.icon_url)
return embed
Whole code:
#client.command()
async def rob_(ctx, other: discord.Member=None):
#PRE-INIZIO: Primissime cose che deve fare il comando prima di iniziare, di solito cancellare se si vuole il messaggio del comando.
await ctx.message.delete()
id_author = str(ctx.author.id)
#ERRORI: Settaggio dei vari errori che darà il comando se non viene eseguito perfettamente.
embed = discord.Embed(
color=0xa61022
)
if not other:
embed.set_author(
name="Per favore specifica la persona che vuoi rubare!",
)
await ctx.send(embed=embed, delete_after=10.0)
return
id_other = str(other.id)
if id_author not in economy_system:
embed.set_author(
name=f"{ctx.author.name} prima di accedere a questo comando devi creare un account!"
)
await ctx.send(embed=embed, delete_after=10)
await client.get_command("superdaily").reset_cooldown(ctx)
return
if id_other not in economy_system:
embed.set_author(
name=f"{other.name} non ha un account!"
)
await ctx.send(embed=embed, delete_after=10)
return
#INSERIMENTO: Qui iniziamo a definire le variabili che serviranno al nostro comando
template = [
("1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", 0, 1, 0, 3, 2, 0,)
]
reac1, reac2, reac3, reac4, reac5, reac6, res1, res2, res3, res4, res5, res6 = random.choice(template)
print(reac1, reac2, reac3, reac4, reac5, reac6, res1, res2, res3, res4, res5, res6)
count = 0
value = 0
if res1 == 1:
value1 = reac1
if res2 == 1:
value1 = reac2
if res3 == 1:
value1 = reac3
if res4 == 1:
value1 = reac4
if res5 == 1:
value1 = reac5
if res6 == 1:
value1 = reac6
if res1 == 2:
value2 = reac1
if res2 == 2:
value2 = reac2
if res3 == 2:
value2 = reac3
if res4 == 2:
value2 = reac4
if res5 == 2:
value2 = reac5
if res6 == 2:
value2 = reac6
if res1 == 3:
value3 = reac1
if res2 == 3:
value3 = reac2
if res3 == 3:
value3 = reac3
if res4 == 3:
value3 = reac4
if res5 == 3:
value3 = reac5
if res6 == 3:
value3 = reac6
print(value1, value2, value3)
#USCITA: Da qui tutte il comando verrà eseguito con tutte le azioni che vogliamo, questa parte può essere la più lunga
embed = discord.Embed(
title="Rob!",
description="Per rubare dei soldi bisogna essere veloci senza farsi scoprire!\nCerto non saprai se ruberai tanto o poco ma l'importante è non farsi sgamare!\n\nHai 5 secondi di tempo per cliccare 3 reazione nel seguente ordine scritte su **status**\n__N.B Il tempo partirà non appena lo status ti darà le 3 reazioni__\n**STATUS**: Aggiungendo le reazioni...",
color=0x003399
)
embed.set_author(
name=f"{ctx.author.name}",
icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=ctx.guild.icon_url)
message = await ctx.send(embed=embed)
await message.add_reaction(reac1)
await message.add_reaction(reac2)
await message.add_reaction(reac3)
await message.add_reaction(reac4)
await message.add_reaction(reac5)
await message.add_reaction(reac6)
embed = discord.Embed(
title="Rob!",
description=f"**STATUS**:\n {value1} **->** {value2} **->** {value3}",
color=0x003399
)
embed.set_author(
name=f"{ctx.author.name}",
icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=ctx.guild.icon_url)
await message.edit(embed=embed)
def rob_check(reaction, user):
return user == ctx.author and str(reaction.emoji) in [reac1, reac2, reac3, reac4, reac5, reac6]
def rob_true():
#inserted above
#def rob_false()
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=5, check=rob_check)
if str(reaction.emoji) == reac1:
count = count + 1
if count == 1:
if res1 == 1:
value = value + 1
else:
await message.delete()
return
if count == 2:
if res1 == 2:
value = value + 1
else:
await message.delete()
return
if count == 3:
if res1 == 3:
rob_true()
return
else:
await message.delete()
return
if str(reaction.emoji) == reac2:
count = count + 1
if count == 1:
if res2 == 1:
value = value + 1
else:
await message.delete()
return
if count == 2:
if res2 == 2:
value = value + 1
else:
await message.delete()
return
if count == 3:
if res2 == 3:
rob_true()
return
else:
await message.delete()
return
if str(reaction.emoji) == reac3:
count = count + 1
if count == 1:
if res3 == 1:
value = value + 1
else:
await message.delete()
return
if count == 2:
if res3 == 2:
value = value + 1
else:
await message.delete()
return
if count == 3:
if res3 == 3:
rob_true()
return
else:
await message.delete()
return
if str(reaction.emoji) == reac4:
count = count + 1
if count == 1:
if res4 == 1:
value = value + 1
else:
await message.delete()
return
if count == 2:
if res4 == 2:
value = value + 1
else:
await message.delete()
return
if count == 3:
if res4 == 3:
if economy_system[id_other]["wallet"] == 0:
embed = discord.Embed(
title="Rob!",
description=f"{other.name} non ha nulla quindi non guadagni nulla!",
color=0xa61022
)
embed.set_author(
name=f"{ctx.author.name}",
icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=ctx.guild.icon_url)
await message.edit(embed=embed)
return
rob_true()
await ctx.send(embed=embed)
_save()
return
else:
await message.delete()
return
if str(reaction.emoji) == reac5:
count = count + 1
if count == 1:
if res5 == 1:
value = value + 1
else:
await message.delete()
return
if count == 2:
if res5 == 2:
value = value + 1
else:
await message.delete()
return
if count == 3:
if res5 == 3:
rob_true()
return
else:
await message.delete()
return
if str(reaction.emoji) == reac6:
count = count + 1
if count == 1:
if res6 == 1:
value = value + 1
else:
await message.delete()
return
if count == 2:
if res6 == 2:
value = value + 1
else:
await message.delete()
return
if count == 3:
if res6 == 3:
rob_true()
return
else:
await message.delete()
return
except asyncio.TimeoutError:
print("ok")
break
The code is still incomplete for now I was just testing this function and unfortunately it gives me this error.
Is there any way to fix?
N.B I ask this question because I have not found it anywhere and I think it could be useful in the future
It might be because you are only returning the embed, not sending it. So every time you call rob_true(), you need to send it instead, by doing await ctx.send(embed=rob_true()) (in place of when you call rob_true()), which sends the returned embed.

Undefined Variable "xgetfile" in SciLab

[\n ENTER SAMPLE SIZE:28428
\n ENTER TOLERANCE LIMIT:100
Undefined variable: xgetfile]1
So basically when I run this program that I have, downloaded from the internet, it always tells me that the variable xgetfile is undefined rather than prompting me to select a file with the data in it. The full code for said program is pasted down below. My question is how to remedy this issue and be able to input my data. The line that says xgetfile is pretty near the top so you don't have to do too much reading to get to it.
n=0;
tol_lim=0;
// ENTERING SAMPLE SIZE
while n<=5 | n==[] , n=input("\n ENTER SAMPLE SIZE:");
if (n<=5) printf("\n\n SAMPLE SIZE SHOULD BE GREATER THAN 5\n\n");end
if n==[] printf("\n\n SAMPLE SIZE CANNOT BE LEFT BLANK\n\n");end
end
//ENTERING TOLERANCE LIMIT
while tol_lim <= 0 | tol_lim==[], tol_lim=input("\n ENTER TOLERANCE LIMIT:");
if (tol_lim<=0) printf("\n TOLERANCE LIMIT SHOULD BE GREATER THAN 0\n\n");end
if tol_lim==[] printf("\n TOLERANCE LIMIT CANNOT BE LEFT BLANK\n\n");end
end
//INITIALIZING VARIABLES
F = zeros(n,3);
Y = zeros(n,1);
OY = zeros(n,1);
EY = zeros(n,1);
DOY = zeros(n,1);
Estimated_Y = zeros(n,1);
d = zeros(3,1);
THETA = zeros(3,1);
GN1=0;GN2=0;GN3=0;
sig=0;y=0;
sigma_hat_square=0; y_bar=0; dff=0; R_square=0;
U_t_hat=0; U_t_hat_square=0; U_t_minusone_hat=0; dd=0; DW=0;Covariance_Matrix=zeros(3,3);
f_obs=0; l_obs=0; r=0; D1=0; D2=0;
S1=0;S2=0;S3=0;D1=0;D2=0;r=0;sum_Y=0;Y_bar=0;Y_square=0;D_den=0;D=0;
AY=zeros(n,1);
OBS=zeros(n,1);
EST=zeros(n,1);
g=[];gh=[];
EXISTING_DATA='';
//CHOOSING INPUT EXCEL DATA FILE
gh=xgetfile();
while gh==[], gh=xgetfile('*.*',title='CHOOSE A FILE NAME');
if g==[] printf("FILE NAME CANNOT BE LEFT BLANK");end
end
Sheets=readxls(gh);
EXISTING_DATA=Sheets(1);
typeof(EXISTING_DATA);
printf("\n\n");
//DISPLAYING EXISTING DATA FROM EXCEL FILE
EXISTING_DATA
for i=2:(n+1),DOY(i-1,1)=EXISTING_DATA(i,2);end
while f_obs<=0 | f_obs==[] , f_obs=input("\n ENTER FIRST OBSERVATION NO:");
//if (f_obs<=0) printf("\n\n IT SHOULD BE GREATER THAN 0\n\n");end
//if f_obs==[] printf("\n\n IT CANNOT BE LEFT BLANK\n\n");end
end
while l_obs<f_obs | l_obs==[] , l_obs=input("\n ENTER LAST OBSERVATION NO:");
//if (l_obs<=f_obs) printf("\n\n IT SHOULD BE GREATER THAN FIRST OBSERVATION NO:\n\n");end
//if l_obs==[] printf("\n\n IT CANNOT BE LEFT BLANK\n\n");end
end
for i=1:n,OY(i,1)=log(DOY(i,1));end
r = ((l_obs - f_obs) + 1)/3;
for i=1:r, S1 = S1 + OY(i,1);end
for i=r+1:2*r, S2 = S2 + OY(i,1);end
for i=2*r+1:3*r, S3 = S3 + OY(i,1);end
D1 = S1 - S2;
D2 = S2 - S3;
A=0;B=0;C=0;
// CALCULATING INITIAL ESTIMATES OF A, B, C
C = (D2/D1)^(1/r);
B = ((1 - C)/C)* [(D1^3)/(D1-D2)^2];
A = (1/3)*(1/r)*[(S1 + S2 + S3) - (D1^2 + D1*D2 + D2^2)/(D1 - D2)];
Ini_A=A; Ini_B=B;Ini_C=C;
for i=1:n, F(i,1)=1;end
for i=1:n, F(i,2)=C^i;end
for i=1:n, F(i,3)=i*B*(C^(i-1));end
for i=1:n, EY(i,1)=A + B*(C^i);end
for i=1:n, Y(i,1) = OY(i,1) - EY(i,1);end
d = inv(F'*F)*F'*Y;
THETA(1,1) = A + d(1,1);
THETA(2,1) = B + d(2,1);
THETA(3,1) = C + d(3,1);
if abs(d(1,1)/A) < tol_lim & abs(d(2,1)/B) < tol_lim & abs(d(3,1)/C) < tol_lim
break;
end
for cnt=1:100
A = THETA(1,1);
B = THETA(2,1);
C = THETA(3,1);
for i=1:n, F(i,1)=1;end
for i=1:n, F(i,2)=C^i;end
for i=1:n, F(i,3)=i*B*(C^(i-1));end
for i=1:n, EY(i,1)=A + B*(C^i);end
for i=1:n, Y(i,1) = OY(i,1) - EY(i,1);end
d = inv(F'*F)*F'*Y;
THETA(1,1) = A + d(1,1);
THETA(2,1) = B + d(2,1);
THETA(3,1) = C + d(3,1);
if abs(d(1,1)/A) < tol_lim & abs(d(2,1)/B) < tol_lim & abs(d(3,1)/C) < tol_lim
break;
end
end
A=THETA(1,1);
B=THETA(2,1);
C=THETA(3,1);
for i=1:n,
GN1 = GN1 + (OY(i,1) - A - B*(C^i));
GN2 = GN2 + (OY(i,1) - A - B*(C^i))*(C^i);
GN3 = GN3 + (OY(i,1) - A - B*(C^i))*B*i*(C^(i-1));
end
p_GN1=GN1;
p_GN2=GN2;
p_GN3=GN3;
for i=1:n, EY(i,1) = A + B*(C^i);end
for i=1:n, Y(i,1) = OY(i,1) - EY(i,1);end
for i=1:n, sig =sig + Y(i,1)*Y(i,1);end
sigma_hat_square = sig/n;
for i=1:n, y = y + OY(i,1);end
y_bar = y/n;
for i=1:n, dff = dff + (OY(i,1) - y_bar)*(OY(i,1) - y_bar);end
R_square = 1 - (sig/dff);
for i=1:n,
F(i,1)=1;
F(i,2)=C^i;
F(i,3)=i*B*(C^(i-1));
end
//Showing Covariance Matrix
Covariance_Matrix = sigma_hat_square*inv(F'*F);
G = zeros(3,3);
G = inv(F'*F);
//Showing Standard Errors
std_err_A = sqrt((sigma_hat_square)*G(1,1));
std_err_B = sqrt((sigma_hat_square)*G(2,2));
std_err_C = sqrt((sigma_hat_square)*G(3,3));
for i=1:n,
U_t_hat_square = U_t_hat_square+ ((OY(i,1) - A - B*(C^i))^2);
end
for i=2:n,
U_t_hat = OY(i,1) - A - B*(C^i);
U_t_minusone_hat = OY(i-1,1) - A - B*(C^(i-1));
dd = dd + (U_t_hat - U_t_minusone_hat)*(U_t_hat - U_t_minusone_hat);
end
DW = dd/U_t_hat_square;
for i=1:n, EY(i,1) = A + B*(C^i);end
for i=1:n, Y(i,1) = OY(i,1) - EY(i,1);end
for i=1:n,sum_Y = sum_Y + OY(i,1);end
Y_bar = sum_Y /n;
for i=1:n, Y_square = Y_square + Y(i,1)*Y(i,1);end
for i=1:n, D_den = D_den + (OY(i,1) - Y_bar)*(OY(i,1) - Y_bar);end
D = Y_square/D_den;
printf("\n\n\nREPORT SHOWING RESULTS\n");
printf("----------------------\n\n\n");
printf("Sample Size = %d Tolerance Limit=%f\n\n",n,tol_lim);
printf("PARAMETER INITIAL ESTIMATES FINAL ESTIMATES STD. ERRORS DW ");
printf("\n------- ----------------- ---------------- ------------ ---- \n");
printf("\nA %f %f %f %f", Ini_A,A, std_err_A, DW);
printf("\nB %f %f %f ", Ini_B,B, std_err_B);
printf("\nC %f %f %f ", Ini_C,C, std_err_C);
printf("\n\n\n ");
printf("No. of Iterations: = %d\n\n",cnt+1);
printf("GN1 = %.7f\n\n", p_GN1);
printf("GN2 = %.7f\n\n", p_GN2);
printf("GN3 = %.7f\n\n", p_GN3);
printf("Sigma_Hat_Square= %f \t\t R_Square= %f\t D=%f",sigma_hat_square, R_square,D);
printf("\n\n COVARIANCE MATRIX \n");
printf("-------------------------\n");
printf("%f\t\t%f\t\t%f\n",Covariance_Matrix(1,1), Covariance_Matrix(1,2), Covariance_Matrix(1,3));
printf("%f\t\t%f\t\t%f\n",Covariance_Matrix(2,1), Covariance_Matrix(2,2), Covariance_Matrix(2,3));
printf("%f\t\t%f\t\t%f",Covariance_Matrix(3,1), Covariance_Matrix(3,2), Covariance_Matrix(3,3));
printf("\n\n Residuals\n\n ");
printf("Y = %f\n",Y);
x=input("\n\n Exit Program??...Press 1 to exit or enter to save");
if (x==1)
exit();
end
g=x_dialog(['enter file name:']);
u=mopen(g,'w');
mfprintf(u,"REPORT SHOWING RESULTS\n");
mfprintf(u,"----------------------\n\n\n");
mfprintf(u,"Sample Size = %d Tolerance Limit = %f\n\n\n",n,tol_lim);
mfprintf(u,"PARAMETER INITIAL ESTIMATES FINAL ESTIMATES STD. ERRORS DW ");
mfprintf(u,"\n------- ----------------- ---------------- ------------ ------ \n");
mfprintf(u,"\nA %f %f %f %f", Ini_A,A, std_err_A, DW);
mfprintf(u,"\nB %f %f %f ", Ini_B,B, std_err_B);
mfprintf(u,"\nC %f %f %f ", Ini_C,C, std_err_C);
mfprintf(u,"\n\n\n ");
mfprintf(u,"No. of Iterations: = %d\n\n",cnt+1);
mfprintf(u,"GN1 = %.7f\n\n", p_GN1);
mfprintf(u, "GN2 = %.7f\n\n", p_GN2);
mfprintf(u, "GN3 = %.7f\n\n", p_GN3);
mfprintf(u, "Sigma_Hat_Square= %f \t\t R_Square= %f\t D=%f",sigma_hat_square, R_square,D);
mfprintf(u,"\n\n COVARIANCE MATRIX \n");
mfprintf(u,"-------------------------\n");
mfprintf(u,"%f\t\t%f\t\t%f\n",Covariance_Matrix(1,1), Covariance_Matrix(1,2), Covariance_Matrix(1,3));
mfprintf(u,"%f\t\t%f\t\t%f\n",Covariance_Matrix(2,1), Covariance_Matrix(2,2), Covariance_Matrix(2,3));
mfprintf(u,"%f\t\t%f\t\t%f",Covariance_Matrix(3,1), Covariance_Matrix(3,2), Covariance_Matrix(3,3));
mfprintf(u,"\n\n SHOWING RESIDUALS\n\n ");
mfprintf(u, "Y = %f\n",Y);
mclose(u);
t=[1:1:n]';
Estimated_Y=A + B*(C^t);
for i=1:n, OBS(i,1)=OY(i,1);end
for i=1:n,EST(i,1)=Estimated_Y(i,1);end
plot2d(t,[OBS,EST],[2,3],leg="Observed#Estimated",nax=[1,n,1,n]);
legends(['t';'(Year)'],[1,1],opt="lr")
legends(['Y';'(Dependent Variable)'],[1,1],opt="ul")
xtitle("GOMPERTZ GROWTH CURVE");
end_prog=input("\n\n Continue??..PRESS 1 TO CONTINUE.....PRESS 2 TO EXIT");
if (end_prog==1)
exec("C:\SCILAB\Gompertz.sce");
end
if (end_prog==2)
printf("CLOSING PROGRAM........");
exit;
end
Your Scilab program seems to be written for a very old version since xgetfile disappeared with version 5.2 (year 2001). Just replace the line with
gh=uigetfile('*.*','CHOOSE A FILE NAME');
and this part of your program will work.

Local infeasibility in MATLAB

I need help with a dynamic optimization problem that consist in a consumed energy optimization of a UAV with this optimal control problem.
enter image description here
enter image description here
My code is this
Ecuations:
Parameters
tf
#Velocidad de rotores rad/s
#Las condiciones iniciales permiten igualar la acción de la gravedad
#Se tomo 4000rad/s como la velocidad maxima de los rotores
w1 = 912.32, >=0, <=3000
w2 = 912.32, >=0, <=3000
w3 = 912.32, >=0, <=3000
w4 = 912.32, >=0, <=3000
t1 = 0, >=0
t2 = 0, >=0
t3 = 0, >=0
t4 = 0, >=0
Constants
!----------------COEFICIENTES DEL MODELO-----------------!
#Gravedad
g = 9.81 !m/s^2
pi = 3.14159265359
#Motor Coefficients
J = 4.1904e-5 !kg*m^2
kt = 0.0104e-3 !N*m/A
kv = 96.342 !rad/s/volt
Dv = 0.2e-3 !N*m*s/rad
R = 0.2 !Ohms
#Battery parameters
Q = 1.55 !Ah
Rint = 0.02 !Ohms
E0 = 1.24 !volt
K = 2.92e-3 !volt
A = 0.156
B =2.35
#Quadrotor parameters
l = 0.175 !m
m = 1.3 !kg
Ix = 0.081 !kg*m^2
Iy = 0.081 !kg*m^2
Iz = 0.142 !kg*m^2
kb = 3.8305e-6 !N/rad/s
ktau = 2.2518e-8 !(N*m)/rad/s
#Parametrizacion del polinomio
a1 = -1.72e-5
a2 = 1.95e-5
a3 = -6.98e-6
a4 = 4.09e-7
b1 = 0.014
b2 = -0.0157
b3 = 5.656e-3
b4 = -3.908e-4
c1 = -0.8796
c2 = 0.3385
c3 = 0.2890
c4 = 0.1626
Variables
!------------------CONDICONES INICIALES------------------!
x = 0
xp = 0
y = 0
yp = 0
z = 0
zp = 0
pitch = 0, >=-pi/2, <=pi/2 !theta - restricciones
pitchp = 0
roll = 0, >=-pi/2, <=pi/2 !phi - restricciones
rollp = 0
yaw = 0 !psi
yawp = 0%, >=-200/180, <=200/180
#Función objetivo
of = 0 !condición inicial de la función objetivo
Intermediates
#Motor 1
aw1 = a1*w1^2 + b1*w1 + c1
bw1 = a2*w1^2 + b2*w1 + c2
cw1 = a3*w1^2 + b3*w1 + c3
dw1 = a4*w1^2 + b4*w1 + c4
#Motor 2
aw2 = a1*w2^2 + b1*w2 + c1
bw2 = a2*w2^2 + b2*w2 + c2
cw2 = a3*w2^2 + b3*w2 + c3
dw2 = a4*w2^2 + b4*w2 + c4
#Motor 3
aw3 = a1*w3^2 + b1*w3 + c1
bw3 = a2*w3^2 + b2*w3 + c2
cw3 = a3*w3^2 + b3*w3 + c3
dw3 = a4*w3^2 + b4*w3 + c4
#Motor 4
aw4 = a1*w4^2 + b1*w4 + c1
bw4 = a2*w4^2 + b2*w4 + c2
cw4 = a3*w4^2 + b3*w4 + c3
dw4 = a4*w4^2 + b4*w4 + c4
#frj(wj(t),Tj(t))
fr1=aw1*t1^3 + bw1*t1^2 + cw1*t1 + dw1
fr2=aw2*t2^3 + bw2*t2^2 + cw2*t2 + dw2
fr3=aw3*t3^3 + bw3*t3^2 + cw3*t3 + dw3
fr4=aw4*t4^3 + bw4*t4^2 + cw4*t4 + dw4
!---------------------CONTROL INPUTS---------------------!
T = kb * (w1^2 + w2^2 + w3^2 + w4^2)
u1 = kb * (w2^2 - w4^2)
u2 = kb * (w3^2 - w1^2)
u3 = ktau * (w1^2 - w2^2 + w3^2 - w4^2)
wline = w1 - w2 + w3 - w4
!-------------------ENERGIA POR ROTOR--------------------!
Ec1 = ((J*$w1 + ktau*w1^2 + Dv*w1)/fr1)*w1
Ec2 = ((J*$w2 + ktau*w2^2 + Dv*w2)/fr2)*w2
Ec3 = ((J*$w3 + ktau*w3^2 + Dv*w3)/fr3)*w3
Ec4 = ((J*$w4 + ktau*w4^2 + Dv*w4)/fr4)*w4
Ectotal = Ec1 + Ec2 + Ec3 + Ec4
Equations
!---------------MINIMIZAR FUNCIÓN OBJETIVO---------------!
minimize tf * of
!-----------------RELACION DE VARIABLES------------------!
xp = $x
yp = $y
zp = $z
pitchp = $pitch
rollp = $roll
yawp = $yaw
!-----------------CONDICONES DE FRONTERA-----------------!
#Condiciones finales del modelo
tf * x = 4
tf * y = 5
tf * z = 6
tf * xp = 0
tf * yp = 0
tf * zp = 0
tf * roll = 0
tf * pitch = 0
tf * yaw = 0
!-----------------TORQUE DE LOS MOTORES------------------!
t1 = J*$w1 + ktau*w1^2 + Dv*w1
t2 = J*$w2 + ktau*w2^2 + Dv*w2
t3 = J*$w3 + ktau*w3^2 + Dv*w3
t4 = J*$w4 + ktau*w4^2 + Dv*w4
!------------------------SUJETO A------------------------!
#Modelo aerodinámico del UAV
m*$xp = (cos(roll)*sin(pitch)*cos(yaw) + sin(roll)*sin(yaw))*T
m*$yp = (cos(roll)*sin(pitch)*sin(yaw) - sin(roll)*cos(yaw))*T
m*$zp = (cos(roll)*cos(pitch))*T-m*g
Ix*$rollp = ((Iy - Iz)*pitchp*yawp + J*pitchp*wline + l*u1)
Iy*$pitchp = ((Iz - Ix)*rollp*yawp - J*rollp*wline + l*u2)
Iz*$yawp = ((Ix - Iy)*rollp*pitchp + u3)
!--------------------FUNCIÓN OBJETIVO--------------------!
$of = Ectotal
MATLAB:
clear all; close all; clc
server = 'http://127.0.0.1';
app = 'traj_optima';
addpath('C:/Program Files/MATLAB/apm_matlab_v0.7.2/apm')
apm(server,app,'clear all');
apm_load(server,app,'ecuaciones_mod.apm');
csv_load(server,app,'tiempo2.csv');
apm_option(server,app,'apm.max_iter',200);
apm_option(server,app,'nlc.nodes',3);
apm_option(server,app,'apm.rtol',1);
apm_option(server,app,'apm.otol',1);
apm_option(server,app,'nlc.solver',3);
apm_option(server,app,'nlc.imode',6);
apm_option(server,app,'nlc.mv_type',1);
costo=1e-5;%1e-5
%VARIABLES CONTROLADAS
%Velocidades angulares
apm_info(server,app,'MV','w1');
apm_option(server,app,'w1.status',1);
apm_info(server,app,'MV','w2');
apm_option(server,app,'w2.status',1);
apm_info(server,app,'MV','w3');
apm_option(server,app,'w3.status',1);
apm_info(server,app,'MV','w4');
apm_option(server,app,'w4.status',1);
% Torques
apm_info(server,app,'MV','t1');
apm_option(server,app,'t1.status',1);
apm_info(server,app,'MV','t2');
apm_option(server,app,'t2.status',1);
apm_info(server,app,'MV','t3');
apm_option(server,app,'t3.status',1);
apm_info(server,app,'MV','t4');
apm_option(server,app,'t4.status',1);
%Salida
output = apm(server,app,'solve');
disp(output)
y = apm_sol(server,app);
z = y.x;
tiempo2.csv
time,tf
0,0
0.001,0
0.2,0
0.4,0
0.6,0
0.8,0
1,0
1.2,0
1.4,0
1.6,0
1.8,0
2,0
2.2,0
2.4,0
2.6,0
2.8,0
3,0
3.2,0
3.4,0
3.6,0
3.8,0
4,0
4.2,0
4.4,0
4.6,0
4.8,0
5,0
5.2,0
5.4,0
5.6,0
5.8,0
6,0
6.2,0
6.4,0
6.6,0
6.8,0
7,0
7.2,0
7.4,0
7.6,0
7.8,0
8,0
8.2,0
8.4,0
8.6,0
8.8,0
9,0
9.2,0
9.4,0
9.6,0
9.8,0
10,1
Finally the answer obtained is:
enter image description here
I need help with this local infeasibility problem, please.
The infeasible solution is caused by the terminal constraints:
tf * z = 4
tf * z = 5
tf * z = 6
When tf=0, the constraints are evaluated to 0=4, 0=5, 0=6 and the solver reports that these can not be satisfied by the solver. Instead, you can pose the constraints as:
tf * (x-4) = 0
tf * (y-5) = 0
tf * (z-6) = 0
That way, the constraint is valid when tf=0 and when tf=1 at the final time. A potential better way yet is to convert the terminal constraints to objective terms with f=1000 such as:
minimize f*tf*((x-4)^2 + (y-5)^2 + (z-6)^2)
minimize f*tf*(xp^2 + yp^2 + zp^2)
minimize f*tf*(roll^2 + pitch^2 + yaw^2)
That way, the optimizer won't report an infeasible solution if it can't reach the terminal constraints as discussed in the pendulum problem. I made a few other modifications to your model and script to achieve a successful solution. Here is a summary:
Converted terminal constraints to objective function (soft constraints)
Parameters t1-t4 should be variables
Fixed degree of freedom issue by making w1-w4 variables and w1p-w4p variables. w1-w4 are differential states.
Added constraints to w1p-w4p between -10 and 10 to help the solver converge
Added initialization step to simulate the model before optimizing. There are more details on initialization strategies in this paper: Safdarnejad, S.M., Hedengren, J.D., Lewis, N.R., Haseltine, E., Initialization Strategies for Optimization of Dynamic Systems, Computers and Chemical Engineering, 2015, Vol. 78, pp. 39-50, DOI: 10.1016/j.compchemeng.2015.04.016
Model
Parameters
tf
w1p = 0 > -10 < 10
w2p = 0 > -10 < 10
w3p = 0 > -10 < 10
w4p = 0 > -10 < 10
Constants
!----------------COEFICIENTES DEL MODELO-----------------!
#Gravedad
g = 9.81 !m/s^2
pi = 3.14159265359
#Motor Coefficients
J = 4.1904e-5 !kg*m^2
kt = 0.0104e-3 !N*m/A
kv = 96.342 !rad/s/volt
Dv = 0.2e-3 !N*m*s/rad
R = 0.2 !Ohms
#Battery parameters
Q = 1.55 !Ah
Rint = 0.02 !Ohms
E0 = 1.24 !volt
K = 2.92e-3 !volt
A = 0.156
B =2.35
#Quadrotor parameters
l = 0.175 !m
m = 1.3 !kg
Ix = 0.081 !kg*m^2
Iy = 0.081 !kg*m^2
Iz = 0.142 !kg*m^2
kb = 3.8305e-6 !N/rad/s
ktau = 2.2518e-8 !(N*m)/rad/s
#Parametrizacion del polinomio
a1 = -1.72e-5
a2 = 1.95e-5
a3 = -6.98e-6
a4 = 4.09e-7
b1 = 0.014
b2 = -0.0157
b3 = 5.656e-3
b4 = -3.908e-4
c1 = -0.8796
c2 = 0.3385
c3 = 0.2890
c4 = 0.1626
Variables
!------------------CONDICONES INICIALES------------------!
x = 0
xp = 0
y = 0
yp = 0
z = 0
zp = 0
pitch = 0, >=-pi/2, <=pi/2 !theta - restricciones
pitchp = 0
roll = 0, >=-pi/2, <=pi/2 !phi - restricciones
rollp = 0
yaw = 0 !psi
yawp = 0 %, >=-200/180, <=200/180
#Velocidad de rotores rad/s
#Las condiciones iniciales permiten igualar la acción de la gravedad
#Se tomo 4000rad/s como la velocidad maxima de los rotores
w1 = 912.32, >=0, <=3000
w2 = 912.32, >=0, <=3000
w3 = 912.32, >=0, <=3000
w4 = 912.32, >=0, <=3000
t1 = 0, >=0
t2 = 0, >=0
t3 = 0, >=0
t4 = 0, >=0
#Función objetivo
of = 0 !condición inicial de la función objetivo
Intermediates
#Motor 1
aw1 = a1*w1^2 + b1*w1 + c1
bw1 = a2*w1^2 + b2*w1 + c2
cw1 = a3*w1^2 + b3*w1 + c3
dw1 = a4*w1^2 + b4*w1 + c4
#Motor 2
aw2 = a1*w2^2 + b1*w2 + c1
bw2 = a2*w2^2 + b2*w2 + c2
cw2 = a3*w2^2 + b3*w2 + c3
dw2 = a4*w2^2 + b4*w2 + c4
#Motor 3
aw3 = a1*w3^2 + b1*w3 + c1
bw3 = a2*w3^2 + b2*w3 + c2
cw3 = a3*w3^2 + b3*w3 + c3
dw3 = a4*w3^2 + b4*w3 + c4
#Motor 4
aw4 = a1*w4^2 + b1*w4 + c1
bw4 = a2*w4^2 + b2*w4 + c2
cw4 = a3*w4^2 + b3*w4 + c3
dw4 = a4*w4^2 + b4*w4 + c4
#frj(wj(t),Tj(t))
fr1=aw1*t1^3 + bw1*t1^2 + cw1*t1 + dw1
fr2=aw2*t2^3 + bw2*t2^2 + cw2*t2 + dw2
fr3=aw3*t3^3 + bw3*t3^2 + cw3*t3 + dw3
fr4=aw4*t4^3 + bw4*t4^2 + cw4*t4 + dw4
!---------------------CONTROL INPUTS---------------------!
T = kb * (w1^2 + w2^2 + w3^2 + w4^2)
u1 = kb * (w2^2 - w4^2)
u2 = kb * (w3^2 - w1^2)
u3 = ktau * (w1^2 - w2^2 + w3^2 - w4^2)
wline = w1 - w2 + w3 - w4
!-------------------ENERGIA POR ROTOR--------------------!
Ec1 = ((J*$w1 + ktau*w1^2 + Dv*w1)/fr1)*w1
Ec2 = ((J*$w2 + ktau*w2^2 + Dv*w2)/fr2)*w2
Ec3 = ((J*$w3 + ktau*w3^2 + Dv*w3)/fr3)*w3
Ec4 = ((J*$w4 + ktau*w4^2 + Dv*w4)/fr4)*w4
Ectotal = Ec1 + Ec2 + Ec3 + Ec4
! scaling factor for terminal constraint
f = 1000
Equations
!---------------MINIMIZAR FUNCIÓN OBJETIVO---------------!
minimize tf * of
!-----------------RELACION DE VARIABLES------------------!
xp = $x
yp = $y
zp = $z
pitchp = $pitch
rollp = $roll
yawp = $yaw
w1p = $w1
w2p = $w2
w3p = $w3
w4p = $w4
!-----------------CONDICONES DE FRONTERA-----------------!
#Condiciones finales del modelo
#tf * (x-4) = 0
#tf * (y-5) = 0
#tf * (z-6) = 0
#tf * xp = 0
#tf * yp = 0
#tf * zp = 0
#tf * roll = 0
#tf * pitch = 0
#tf * yaw = 0
minimize f*tf*((x-4)^2 + (y-5)^2 + (z-6)^2)
minimize f*tf*(xp^2 + yp^2 + zp^2)
minimize f*tf*(roll^2 + pitch^2 + yaw^2)
!-----------------TORQUE DE LOS MOTORES------------------!
t1 = J*w1p + ktau*w1^2 + Dv*w1
t2 = J*w2p + ktau*w2^2 + Dv*w2
t3 = J*w3p + ktau*w3^2 + Dv*w3
t4 = J*w4p + ktau*w4^2 + Dv*w4
!------------------------SUJETO A------------------------!
#Modelo aerodinámico del UAV
m*$xp = (cos(roll)*sin(pitch)*cos(yaw) + sin(roll)*sin(yaw))*T
m*$yp = (cos(roll)*sin(pitch)*sin(yaw) - sin(roll)*cos(yaw))*T
m*$zp = (cos(roll)*cos(pitch))*T-m*g
Ix*$rollp = ((Iy - Iz)*pitchp*yawp + J*pitchp*wline + l*u1)
Iy*$pitchp = ((Iz - Ix)*rollp*yawp - J*rollp*wline + l*u2)
Iz*$yawp = ((Ix - Iy)*rollp*pitchp + u3)
!--------------------FUNCIÓN OBJETIVO--------------------!
$of = Ectotal
MATLAB Script
clear all; close all; clc
server = 'http://byu.apmonitor.com';
app = 'traj_optima';
addpath('apm')
apm(server,app,'clear all');
apm_load(server,app,'ecuaciones_mod.apm');
csv_load(server,app,'tiempo2.csv');
apm_option(server,app,'apm.max_iter',1000);
apm_option(server,app,'apm.nodes',3);
apm_option(server,app,'apm.rtol',1e-6);
apm_option(server,app,'apm.otol',1e-6);
apm_option(server,app,'apm.solver',3);
apm_option(server,app,'apm.imode',6);
apm_option(server,app,'apm.mv_type',1);
costo=1e-5;%1e-5
%VARIABLES CONTROLADAS
%Velocidades angulares
apm_info(server,app,'MV','w1p');
apm_option(server,app,'w1p.status',1);
apm_info(server,app,'MV','w2p');
apm_option(server,app,'w2p.status',1);
apm_info(server,app,'MV','w3p');
apm_option(server,app,'w3p.status',1);
apm_info(server,app,'MV','w4p');
apm_option(server,app,'w4p.status',1);
%Salida
disp('')
disp('------------- Initialize ----------------')
apm_option(server,app,'apm.coldstart',1);
output = apm(server,app,'solve');
disp(output)
disp('')
disp('-------------- Optimize -----------------')
apm_option(server,app,'apm.time_shift',0);
apm_option(server,app,'apm.coldstart',0);
output = apm(server,app,'solve');
disp(output)
y = apm_sol(server,app);
z = y.x;
This gives a successful solution but the terminal constraints are not met. The solver optimizes the use of w1p-w4p to minimize the objective but there is no solution that makes it to the terminal constraints.
The solution was found.
The final value of the objective function is 50477.4537378181
---------------------------------------------------
Solver : IPOPT (v3.12)
Solution time : 3.06940000000759 sec
Objective : 50477.4537378181
Successful solution
---------------------------------------------------
As a next step, I recommend that you increase the number of time points or allow the final time to change to meet the terminal constraints. You may also want to consider switching to Python Gekko that uses the same underlying engine as APM MATLAB. In this case, the modeling language is fully integrated with Python.

How can I generate PWM in MatLab

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.

Find the distance from camera to vanishing point in matlab

I have this program that finds the vanishing point for a given set of images. Is there a way to find the distance from the camera and the vanishing point?
Also once the vanishing point is found out, I manually need to find the X and Y coordinates using the tool provided in matlab. How can i code a snippet that writes all the X and Y coordinates into a text or excel file?
Also is there a better and simpler way to find the vanishing point in matlab?
Matlab Calling Function to find Vanishing Point:
clear all; close all;
dname = 'Height';
files = dir(dname);
files(1) = [];
files(1) = [];
for i=1:size(files, 1)
original = imread(fullfile(dname, files(i).name));
original = imresize(original,0.35);
im = im2double(rgb2gray(original));
[row, col] = findVanishingPoint(im);
imshow(original);hold;plot(col,row,'rx');
saveas(gcf,strcat('Height_Result',num2str(i)),'jpg');
close
end
The findVanishingPoint function:
function [row, col] = findVanishingPoint(im)
DEBUG = 0;
IM = fft2(im);
ROWS = size(IM,1); COLS = size(IM,2);
PERIOD = 2^floor(log2(COLS)-5)+2;
SIZE = floor(10*PERIOD/pi);
SIGMA = SIZE/9;
NORIENT = 72;
E = 8;
[C, S] = createGaborBank(SIZE, PERIOD, SIGMA, NORIENT, ROWS, COLS, E);
D = ones(ROWS, COLS);
AMAX = ifftshift(real(ifft2(C{1}.*IM)).^2+real(ifft2(S{1}.*IM))).^2;
for n=2:NORIENT
A = ifftshift(real(ifft2(C{n}.*IM)).^2+real(ifft2(S{n}.*IM))).^2;
D(find(A > AMAX)) = n;
AMAX = max(A, AMAX);
if (DEBUG==1)
colormap('hot');subplot(131);imagesc(real(A));subplot(132);imagesc(real(AMAX));colorbar;
subplot(133);imagesc(D);
pause
end
end
if (DEBUG==2)
figure('DoubleBuffer','on');
end
T = mean(AMAX(:))-3*std(AMAX(:));
VOTE = zeros(ROWS, COLS);
for row=round(1+SIZE/2):round(ROWS-SIZE/2)
for col=round(1+SIZE/2):round(COLS-SIZE/2)
if (AMAX(row,col) > T)
indices = lineBresenham(ROWS, COLS, col, row, D(row, col)*pi/NORIENT-pi/2);
VOTE(indices) = VOTE(indices)+AMAX(row,col);
end
end
if (DEBUG==2)
colormap('hot');imagesc(VOTE);pause;
end
end
if (DEBUG==2)
close
end
M=1;
[b index] = sort(-VOTE(:));
col = floor((index(1:M)-1) / ROWS)+1;
row = mod(index(1:M)-1, ROWS)+1;
col = round(mean(col));
row = round(mean(row));
The creatGaborBank function:
function [C, S] = createGaborBank(SIZE, PERIOD, SIGMA, NORIENT, ROWS, COLS, E)
if (length(NORIENT)==1)
orientations=[1:NORIENT];
else
orientations = NORIENT;
NORIENT = max(orientations);
end
for n=orientations
[C{n}, S{n}] = gabormask(SIZE, SIGMA, PERIOD, n*pi/NORIENT);
C{n} = fft2(padWithZeros(C{n}, ROWS, COLS));
S{n} = fft2(padWithZeros(S{n}, ROWS, COLS));
end
The gabormask function:
function [cmask, smask] = gabormask(Size, sigma, period, orient, E)
if nargin < 5; E = 8; end;
if nargin < 4; orient = 0; end;
if nargin < 3; period = []; end;
if nargin < 2; sigma = []; end;
if nargin < 1; Size = []; end;
if isempty(period) & isempty(sigma); sigma = 5; end;
if isempty(period); period = sigma*2*sqrt(2); end;
if isempty(sigma); sigma = period/(2*sqrt(2)); end;
if isempty(Size); Size = 2*round(2.575*sigma) + 1; end;
if length(Size) == 1
sx = Size-1; sy = sx;
elseif all(size(Size) == [1 2])
sy = Size(1)-1; sx = Size(2)-1;
else
error('Size must be scalar or 1-by-2 vector');
end;
hy = sy/2; hx = sx/2;
[x, y] = meshgrid(-hx:sx-hx, -hy:sy-hy);
omega = 2*pi/period;
cs = omega * cos(orient);
sn = omega * sin(orient);
k = -1/(E*sigma*sigma);
g = exp(k * (E*x.*x + y.*y));
xp = x * cs + y * sn;
cx = cos(xp);
cmask = g .* cx;
sx = sin(xp);
smask = g .* sx;
cmask = cmask - mean(cmask(:));
cmask = cmask/sum(abs(cmask(:)));
smask = smask - mean(smask(:));
smask = smask/sum(abs(smask(:)));
The padWithZeros function:
function out = padWithZeros(in, ROWS, COLS)
out = padarray(in,[floor((ROWS-size(in,1))/2) floor((COLS-size(in,2))/2)],0,'both');
if size(out,1) == ROWS-1
out = padarray(out,[1 0],0,'pre');
end
if size(out,2) == COLS-1
out = padarray(out,[0 1],0,'pre');
end
The findHorizonEdge function:
function row = findHorizon(im)
DEBUG = 2;
ROWS = size(im,1); COLS = size(im,2);
e = edge(im,'sobel', [], 'horizontal');
dd = sum(e, 2);
N=3;
row = 1;
M = 0;
for i=1+N:length(dd)-N
m = sum(dd(i-N:i+N));
if (m > M)
M = m;
row = i;
end
end
imshow(e);pause
The findHorizon function:
function row = findHorizon(im)
DEBUG = 2;
IM = fft2(im);
ROWS = size(IM,1); COLS = size(IM,2);
PERIOD = 2^floor(log2(COLS)-5)+2;
SIZE = floor(10*PERIOD/pi);
SIGMA = SIZE/9;
NORIENT = 72;
E = 16;
orientations = [NORIENT/2-10:NORIENT/2+10];
[C, S] = createGaborBank(SIZE, PERIOD, SIGMA, orientations, ROWS, COLS, E);
ASUM = zeros(ROWS, COLS);
for n=orientations
A = ifftshift(real(ifft2(C{n}.*IM)).^2+real(ifft2(S{n}.*IM))).^2;
ASUM = ASUM + A;
if (DEBUG==1)
colormap('hot');subplot(131);imagesc(real(A));subplot(132);imagesc(real(AMAX));colorbar;
pause
end
end
ASUM(1:round(1+SIZE/2), :)=0; ASUM(end-round(SIZE/2):end, :)=0;
ASUM(:,end-round(SIZE/2):end)=0; ASUM(:, 1:1+round(SIZE/2))=0;
dd = sum(ASUM, 2);
[temp, row] = sort(-dd);
row = round(mean(row(1:10)));
if (DEBUG == 2)
imagesc(ASUM);hold on;line([1:COLS],repmat(row,COLS));
pause
end
The lineImage function:
function v = lineimage(x0, y0, angle, s)
if (abs(tan(angle)) > 1e015)
a(1,:) = repmat(x0,s(1),1)';
a(2,:) = [1:s(1)];
elseif (abs(tan(angle)) < 1e-015)
a(2,:) = repmat(y0,s(2),1)';
a(1,:) = [1:s(2)];
else
k = tan(angle);
hiX = round((1-(s(1)-y0+1)+k*x0)/k);
loX = round((s(1)-(s(1)-y0+1)+k*x0)/k);
temp = max(loX, hiX);
loX = max(min(loX, hiX), 1);
hiX = min(s(2),temp);
a(1,:) = [loX:hiX];
a(2,:) = max(1, floor(s(1)-(k*a(1,:)+(s(1)-y0+1)-k*x0)));
end
v = (a(1,:)-1).*s(1)+a(2,:);
The lineVector function:
function [abscissa, ordinate] = linevector(x0, y0, angle, s)
if (rad2deg(angle) == 90)
abscissa = repmat(x0,s(1),1);
ordinate = [1:s(1)];
else
k = tan(angle);
hiX = round((1-(s(1)-y0+1)+k*x0)/k);
loX = round((s(1)-(s(1)-y0+1)+k*x0)/k);
temp = max(loX, hiX);
loX = max(min(loX, hiX), 1);
hiX = min(s(2),temp);
abscissa = [loX:hiX];
ordinate = k*abscissa+((s(1)-y0+1)-k*x0);
end
The lineBresenham function:
function [i] = lineBresenham(H,W,Sx,Sy,angle)
k = tan(angle);
if (angle == pi || angle == 0)
Ex = W;
Ey = Sy;
Sx = 1;
elseif (angle == pi/2)
Ey = 1;
i = (Sx-1)*H+[Ey:Sy];
return;
elseif k>0 & k < (Sy-1)/(W-Sx)
Ex = W;
Ey = round(Sy-tan(angle)*(Ex-Sx));
elseif k < 0 & abs(k) < (Sy-1)/(Sx-1)
Ex = 1;
Ey = round(Sy-tan(angle)*(Ex-Sx));
else
Ey = 1;
Ex = round((Sy-1)/tan(angle)+Sx);
end
Dx = Ex - Sx;
Dy = Ey - Sy;
iCoords=1;
if(abs(Dy) <= abs(Dx))
if(Ex >= Sx)
D = 2*Dy + Dx;
IncH = 2*Dy;
IncD = 2*(Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sx-1)*H+Sy;
iCoords = iCoords + 1;
while(X < Ex)
if(D >= 0)
D = D + IncH;
X = X + 1;
else
D = D + IncD;
X = X + 1;
Y = Y - 1;
end
i(iCoords) = (X-1)*H+Y;
iCoords = iCoords + 1;
end
else
D = -2*Dy + Dx;
IncH = -2*Dy;
IncD = 2*(-Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sx-1)*H+Sy;
iCoords = iCoords + 1;
while(X > Ex)
if(D <= 0)
D = D + IncH;
X = X - 1;
else
D = D + IncD;
X = X - 1;
Y = Y - 1;
end
i(iCoords) = (X-1)*H+Y;
iCoords = iCoords + 1;
end
end
else
Tmp = Ex;
Ex = Ey;
Ey = Tmp;
Tmp = Sx;
Sx = Sy;
Sy = Tmp;
Dx = Ex - Sx;
Dy = Ey - Sy;
if(Ex >= Sx)
D = 2*Dy + Dx;
IncH = 2*Dy;
IncD = 2*(Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sy-1)*H+Sx;
iCoords = iCoords + 1;
while(X < Ex)
if(D >= 0)
D = D + IncH;
X = X + 1;
else
D = D + IncD;
X = X + 1;
Y = Y - 1;
end
i(iCoords) = (Y-1)*H+X;
iCoords = iCoords + 1;
end
else
D = -2*Dy + Dx;
IncH = -2*Dy;
IncD = 2*(-Dy + Dx);
X = Sx;
Y = Sy;
i(iCoords) = (Sy-1)*H+Sx;
iCoords = iCoords + 1;
while(X > Ex)
if(D <= 0)
D = D + IncH;
X = X - 1;
else
D = D + IncD;
X = X - 1;
Y = Y - 1;
end
i(iCoords) = (Y-1)*H+X;
iCoords = iCoords + 1;
end
end
end
The vanishing point is at infinity hence the distance to the camera is of no use.
Use xlswrite or dlmwrite to write into excel or text file respectively.

Resources