Python, remove specific columns from file - python

I have a file in the following format ;
string1 string2 ........ stringN
value1,1 value1,2 ........ value1,N
. . ........ .
. . ........ .
. . ........ .
valueM,1 valueM,2 ........ valueM,N
M is on the scale of 10000
N is on the scale of 100
Which I need to;
remove empty lines
remove first two columns
keep 7th,14th,21th ... columns and delete the rest
from this file respectively.
it gets very tricky with numpy since there are strings (titles of each column) in this data as well. I would appreciate any guidance.

You have a custom ASCII-table-like format with fixed-with columns:
*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
* Row * Instance * test_string * test_string * test_string * test_string * test_string * test_string * test_string * string__722 * string__722 * string__722 * string__722 * string__722 * string__722 * string__722 * string__720 * string__720 * string__720 * string__720 * string__720 * string__720 * string__720 * HCAL_SlowDa * HCAL_SlowDa * HCAL_SlowDa * HCAL_SlowDa * HCAL_SlowDa * HCAL_SlowDa * HCAL_SlowDa * string__718 * string__718 * string__718 * string__718 * string__718 * string__718 * string__718 * string__719 * string__719 * string__719 * string__719 * string__719 * string__719 * string__719 * string__723 * string__723 * string__723 * string__723 * string__723 * string__723 * string__723 * string__721 * string__721 * string__721 * string__721 * string__721 * string__721 * string__721 * another_str * another_str * another_str * another_str * another_str * another_str * another_str * another_str * another_str *
*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
* 0 * 0 * 0 * 50331648 * test_string * 2 * 1 * 13 * 5.76460e+18 * 0 * 50331648 * string__722 * 2 * 1 * 606 * 5.83666e+18 * 0 * 50331648 * string__720 * 2 * 1 * 575 * 5.83666e+18 * 0 * 50331648 * HCAL_SlowDa * 2 * 1 * 36 * 5.76460e+18 * 0 * 50331648 * string__718 * 2 * 1 * 529 * 5.83666e+18 * 0 * 50331648 * string__719 * 2 * 1 * 529 * 5.83666e+18 * 0 * 50331648 * string__723 * 2 * 1 * 529 * 5.83666e+18 * 0 * 50331648 * string__721 * 2 * 1 * 529 * 5.83666e+18 * 0 * 50331648 * 212135 * 15080 * 1 * 1 * 3340 * 1057 * 1.399999976 *
* 0 * 1 * 0 * 50331648 * * 2 * 1 * 13 * 0 * 0 * 50331648 * * 2 * 1 * 606 * 53440 * 0 * 50331648 * * 2 * 1 * 575 * 53440 * 0 * 50331648 * * 2 * 1 * 36 * 0 * 0 * 50331648 * * 2 * 1 * 529 * 53440 * 0 * 50331648 * * 2 * 1 * 529 * 53440 * 0 * 50331648 * * 2 * 1 * 529 * 53440 * 0 * 50331648 * * 2 * 1 * 529 * 53440 * 0 * 50331648 * 212135 * * 1 * 1 * 3340 * 1057 * 1.399999976 *
* 0 * 2 * 0 * 50331648 * * 2 * 1 * 13 * 4294970636 * 0 * 50331648 * * 2 * 1 * 606 * 1.09780e+16 * 0 * 50331648 * * 2 * 1 * 575 * 1.09780e+16 * 0 * 50331648 * * 2 * 1 * 36 * 2.70217e+16 * 0 * 50331648 * * 2 * 1 * 529 * 1.09780e+16 * 0 * 50331648 * * 2 * 1 * 529 * 1.09780e+16 * 0 * 50331648 * * 2 * 1 * 529 * 1.09780e+16 * 0 * 50331648 * * 2 * 1 * 529 * 1.09780e+16 * 0 * 50331648 * 212135 * * 1 * 1 * 3340 * 1057 * 1.399999976 *
* 0 * 3 * 0 * 50331648 * * 2 * 1 * 13 * 352321545 * 0 * 50331648 * * 2 * 1 * 606 * 2.30610e+18 * 0 * 50331648 * * 2 * 1 * 575 * 2.30610e+18 * 0 * 50331648 * * 2 * 1 * 36 * 7.30102e+18 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * 212135 * * 1 * 1 * 3340 * 1057 * 1.399999976 *
* 0 * 4 * 0 * 50331648 * * 2 * 1 * 13 * 0 * 0 * 50331648 * * 2 * 1 * 606 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 575 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 36 * 2.82590e+16 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * * 2 * 1 * 529 * 1.15294e+19 * 0 * 50331648 * 212135 * * 1 * 1 * 3340 * 1057 * 1.399999976 *
If we assume that none of the actual data fields contain asterisks themselves, the easiest way to read each row is to use a regular expression to split out the lines.
To output, I'd still use the csv module, because that would make future processing that much easier:
import csv
import re
from itertools import islice
row_split = re.compile('\s*\*\s*')
with open(someinputfile, 'rb') as infile, open(outputfile, 'wb') as outfile:
writer = csv.writer(outfile, delimiter='\t')
next(islice(infile, 3, 3), None) # skip the first 3 lines in the input file
for line in infile:
row = row_split.split(line)[1:-1]
if not row: continue
writer.writerow(row[8::7])
This skips empty rows, and writes only every 7th column (counting from number nine) and skips the rest.
The first row thus is:
['5.76460e+18', '5.83666e+18', '5.83666e+18', '5.76460e+18', '5.83666e+18', '5.83666e+18', '5.83666e+18', '5.83666e+18', '3340']

This is removing empty lines:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
To remove a specific column (I assume your data is stored in a text file):
f = open("textfile.txt","r")
lines = f.readlines()
f.close()
f = open("newfile.txt","w")
Write your lines back, except the lines you want to delete:
list = [0, 1, 6, 13, 20] # remove first,second as well as 7th, 14th and 21th line
for i,line in enumerate(lines):
if i not in list:
f.write(line)
At the end, close the file again.
f.close()

Related

Cant exit while loop on Simpson's Rule

I am trying to calculate an integral using Simpson's Rule formula.The catch is that the value of the integral is the one that satisfies the following condition:You find the Ih and Ih/2.If the absolute of (Ih-Ih/2)<error the loop is complete.Otherwise you repeat the process with half the h,which means it calculates the absolute of (Ih/2-Ih/4) and so on and so on.
while True:
###Ih part
h = (b - a) / N
y1 = np.linspace(a, b, N)
Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \
+ 4*sum(Ez11[1:N-1:2]) + Ez11[N-1])
#####Ih/2 part
h = (b-a)/(2*N)
y2 = np.linspace(a, b, 2*N)
Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
print(Ez22)
I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \
+ 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1])
# error condition I1=Ih I2=Ih/2
if np.abs(I11 - I22) < error:
break
else:
N = 2*N # h/2
print(np.abs(I11 - I22))
As far as I can tell,my approach should be correct.However the loop goes on and on,never to stop.
My code is as follows:
import numpy as np
from scipy.integrate import simps
import scipy.integrate as integrate
import scipy.special as special
# variables
a = 0
b = np.pi * 2
N = 100
ra = 0.1 # ρα
R = 0.05
fa = 35 * (np.pi / 180) # φα
za = 0.4
Q = 10 ** (-6)
k = 9 * 10 ** 9
aa = np.sqrt(ra ** 2 + R ** 2 + za ** 2)
error = 0.55 * 10 ** (-8)
h=(b-a)/N
I1 = np.nan
I11 = np.nan
#Simpsons section
############ Ez
#automated Simpson
while True:
###Ih part
y1 = np.linspace(a, b, N)
Ez1 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
print(len(Ez1))
I1 = simps(Ez1, y1)
#####Ih/2 part
y2 = np.linspace(a, b, 2*N)
Ez2 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
I2 = simps(Ez2, y2)
# error condition I1=Ih I2=Ih/2
if np.abs(I1 - I2) < error:
break
else:
N *= 2 # h/2
#custom-made Simpson
N = 100
while True:
###Ih part
h = (b - a) / N
y1 = np.linspace(a, b, N)
Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \
+ 4*sum(Ez11[1:N-1:2]) + Ez11[N-1])
#####Ih/2 part
h = (b-a)/(2*N)
y2 = np.linspace(a, b, 2*N)
Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
print(Ez22)
I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \
+ 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1])
# error condition I1=Ih I2=Ih/2
if np.abs(I11 - I22) < error:
break
else:
N = 2*N # h/2
print(np.abs(I11 - I22))
print(I1)
print(I11)
Simpson's Rule is as follows:
After a while it's stuck in this situation
The 5.23 part is the absolute diff of those 2 which shouldnt be that high.

Python - Converting list of coordinates to latitude and longitude

I recently started learning programing and Python.
Now I've been trying to convert a list of coordinates x,y to latitude and longitude. I searched and found a method in python in this post: How to convert from UTM to LatLng in python or Javascript
But when I try to apply the function to a list of floats from a dataframe I get an error:" cannot convert the series to <class 'float'> ".
What could I be doing wrong?
My code:
import math
def utmToLatLng(zone, easting, northing, northernHemisphere=True):
if not northernHemisphere:
northing = 10000000 - northing
a = 6378137
e = 0.081819191
e1sq = 0.006739497
k0 = 0.9996
arc = northing / k0
mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0))
ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0)))
ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0
cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32
cc = 151 * math.pow(ei, 3) / 96
cd = 1097 * math.pow(ei, 4) / 512
phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)
n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))
r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0))
fact1 = n0 * math.tan(phi1) / r0
_a1 = 500000 - easting
dd0 = _a1 / (n0 * k0)
fact2 = dd0 * dd0 / 2
t0 = math.pow(math.tan(phi1), 2)
Q0 = e1sq * math.pow(math.cos(phi1), 2)
fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24
fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720
lof1 = _a1 / (n0 * k0)
lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0
lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120
_a2 = (lof1 - lof2 + lof3) / math.cos(phi1)
_a3 = _a2 * 180 / math.pi
latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi
if not northernHemisphere:
latitude = -latitude
longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3
return (latitude, longitude)
import pandas as pd
df = pd.read_csv('Coord_rj.csv')
x = df['x']
y = df['y']
for i in range(len(df)):
lati,longi = utmToLatLng(23,x,y, False)
What my data looks like:
x y
529025.0 7422210.0
529114.0 7422343.0
545227.0 7435702.0
545582.0 7435741.0
The error:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7368/1776418913.py in <module>
1 for i in range(len(df)):
----> 2 lati,longi = utmToLatLng(23,x,y, False)
3
~\AppData\Local\Temp/ipykernel_7368/3107957551.py in utmToLatLng(zone, easting, northing, northernHemisphere)
20 cc = 151 * math.pow(ei, 3) / 96
21 cd = 1097 * math.pow(ei, 4) / 512
---> 22 phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)
23
24 n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))
~\anaconda3\lib\site-packages\pandas\core\series.py in wrapper(self)
183 if len(self) == 1:
184 return converter(self.iloc[0])
--> 185 raise TypeError(f"cannot convert the series to {converter}")
186
187 wrapper.__name__ = f"__{converter.__name__}__"
TypeError: cannot convert the series to <class 'float'>
When you're reading in your input file you're assigning all of the first column to a variable, and all of the second column to a variable:
>>> import pandas as pd
>>> df = pd.read_csv('Coord_rj.csv')
>>> df
x y
0 529025.0 7422210.0
1 529114.0 7422343.0
2 545227.0 7435702.0
3 545582.0 7435741.0
>>> df['x']
0 529025.0
1 529114.0
2 545227.0
3 545582.0
Name: x, dtype: float64
>>> df['y']
0 7422210.0
1 7422343.0
2 7435702.0
3 7435741.0
Name: y, dtype: float64
When you call your function you're passing the entire column to it for x and y, rather than just a row.
Try this instead:
for i in range(len(df)):
lati,longi = utmToLatLng(23, x[i], y[i], False)

How to print this diamond pattern using python?

I want to print this pattern in python:(10 rows rhombus increment-decrement numbers)
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
12321
121
1
Note : 1234321 is missing in the last but fourth line, so I think it is not a perfect rhombus. Plus instead of 10, 1 is printed in the tenth line.How to achieve this shape? Please let me know.
I had no idea on how to do this using numbers so,tried the below basic program using * but I don't know how to print the same using numbers as shown above.
n=11
for i in range(n):
print(''*(n-i-1)+'* '*(i+1))
for j in range(n-1,0,-1):
print(''*(n-j)+'* '*(j))
Also this prints half the shape only
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
How to print the pattern I mentioned(using increment-decrement numbers)?
Plus is the question wrong because it misses 1234321 line or it can be achieved?
Please help me.I am new to coding so how to achieve this using the simplest way i.e using looping constructs like for loop? Thanks in advance for your help and time.
Here is a possibility for how to generate the geometry:
n = 11
for i in range(n // 2 + 1):
print(' ' * (n // 2 - i) + '* ' * (i + 1))
for i in reversed(range(n // 2)):
print(' ' * (n // 2 - i) + '* ' * (i + 1))
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
EDIT: Here is an actual implementation with numbers, that fails at n = 10, unfortunately.
from itertools import chain
n = 9
ranges = chain(range(n), reversed(range(n - 1)))
for i in ranges:
print(' ' * (n - i - 1), *[x + 1 for x in range(i + 1)],
*[x + 1 for x in reversed(range(i))])
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
I'd do a function for one line, and run it twice, skipping the 4 at the end:
def oneline(i):
for j in range(i,10):
print(' ', end='')
for j in range(1, i+1):
print(j if j<10 else 1, end='')
for j in range(i-1, 0, -1):
print(j if j<10 else 1, end='')
print()
for i in range(1,11):
oneline(i)
for i in range(9,0,-1):
if i == 4:
continue
oneline(i)
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
12321
121
1
I believe this would be more pythonic:
size = 10
pattern = (size-1)*" " + size*"123456789" # indented pattern
rhombus = [ pattern[i:i+size] for i in range(size) ] # top-left
rhombus = [ d+d[-2::-1] for d in rhombus ] # horizontal mirror
rhombus = rhombus+rhombus[-2::-1] # vertical mirror
The approach leverages the horizontal and vertical symmetry of the output by only generating the top-left corner and then mirroring horizontally and vertically
output:
for line in rhombus: print(line)
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Alternatively, if you want to print as you go, you can work with the left side of the pattern for all the lines and print the horizontally mirrored substring of the pattern for each line:
size = 10
pattern = size*" " + size*"123456789" # indented pattern (1 based)
for i in range(1,size*2): # for each line (1 based)
line = pattern[size-abs(size-i):][:size] # left side of line
print(line + line[-2::-1]) # print mirrored line
Here's a simple version using for loops. Should work for large numbers.
def r(upper=10):
for i in range(-1 * (upper-1), upper):
j = upper - abs(i)
print(' ' * (abs(i)), end ='')
for k in range(-1 * (j-1), j):
print(str(j - abs(k))[0], end='')
print()
r(10)
..
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Hope it helps :)

How to create python game board

I need help with creating something like this. (I´m just a beginner and I need some inspiration on how to create this board with these numbers, this board should parameter n, with this parameter i can choose how big will be this board [9x9 or 13x13]) Thx for every idea!
0 1 2 3 4 5 6 7 8
0 * * *
1 * D *
2 * D *
3 * * * * D * * * *
4 * D D D X D D D *
5 * * * * D * * * *
6 * D *
7 * D *
8 * * *
My Board list looks like this:
board = [[' ',' ',' ','*','*','*',' ',' ',' '],
[' ',' ',' ','*','D','*',' ',' ',' '],
[' ',' ',' ','*','D','*',' ',' ',' '],
['*','*','*','*','D','*','*','*','*'],
['*','D','D','D','X','D','D','D','*'],
['*','*','*','*','D','*','*','*','*'],
[' ',' ',' ','*','D','*',' ',' ',' '],
[' ',' ',' ','*','D','*',' ',' ',' '],
[' ',' ',' ','*','*','*',' ',' ',' ']]
These two lines would work:
print(' '+' '.join(map(str,range(9))))
print('\n'.join([' '.join([str(i)]+v) for i,v in enumerate(board)]))
Output:
0 1 2 3 4 5 6 7 8
0 * * *
1 * D *
2 * D *
3 * * * * D * * * *
4 * D D D X D D D *
5 * * * * D * * * *
6 * D *
7 * D *
8 * * *
Bunch of str.joins can do it!!!

Python: Filling in a gap between two plots

How can I connect two plots at a discontinues point? I have an equation for the point of discontinuity.
import numpy as np
import pylab
r1 = 1 # AU Earth
r2 = 1.524 # AU Mars
deltanu = 75 * np.pi / 180 # angle in radians
mu = 38.86984154054163
c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu))
s = (r1 + r2 + c) / 2
am = s / 2
def f(a):
alpha = 2 * np.arcsin(np.sqrt(s / (2 * a)))
beta = 2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
return (np.sqrt(a **3 / mu) * (alpha - beta - (np.sin(alpha)
- np.sin(beta))))
def g(a):
alphag = 2* np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a)))
betag = -2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
return (np.sqrt(a ** 3 / mu)
* (alphag - betag - (np.sin(alphag) - np.sin(betag))))
a = np.linspace(am, 2, 500000)
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(a, f(a), color = '#000000')
ax.plot(a, g(a), color = '#000000')
pylab.xlim((0.9, 2))
pylab.ylim((0, 2))
pylab.show()
The equation that reflects the point is: dt = np.sqrt(s ** 3 / 8) * (np.pi - betam + np.sin(betam)) where betam = 2 * np.arcsin(np.sqrt(1 - c / s)) so dt = 0.5 at a = s / 2. However, the gap between the plots looks bigger than a point.
I added: ax.plot([am, am], [.505, .55], color = '#000000') which fills in the gap but it feels out of place.
It seems as though perhaps you should only be using one value for betag:
import numpy as np
import matplotlib.pyplot as plt
r1 = 1 # AU Earth
r2 = 1.524 # AU Mars
deltanu = 75 * np.pi / 180 # angle in radians
mu = 38.86984154054163
c = np.sqrt(r1 ** 2 + r2 ** 2 - 2 * r1 * r2 * np.cos(deltanu))
s = (r1 + r2 + c) / 2
am = s / 2
def g(a, alphag, betag):
return (np.sqrt(a ** 3 / mu)
* (alphag - betag - (np.sin(alphag) - np.sin(betag))))
a = np.linspace(am, 2, 500000)
fig, ax = plt.subplots()
alphag = 2 * np.pi - 2 * np.arcsin(np.sqrt(s / (2 * a)))
betag = 2 * np.arcsin(np.sqrt((s - c) / (2 * a)))
ax.plot(a, g(a, alphag, betag), color = 'r')
alphag = 2 * np.arcsin(np.sqrt(s / (2 * a)))
ax.plot(a, g(a, alphag, betag), color = 'r')
plt.show()
yields
I really don't know what's going on here; I found this serendipitously.
ax.plot([am,am],[f(am),g(am)],color== '#000000')

Categories