Commit 3d0a8071 authored by mgoullie's avatar mgoullie
Browse files

Merge branch 'master' of http://c4science.ch/source/sp4e

parents a46e44b8 f5ac71cc
from __future__ import print_function
from series import Series
################################################################
class ComputeArithmetic(Series):
def __init__(self):
Series.__init__(self)
def __del__(self):
pass
def getAnalyticPrediction(self):
return 1.*self.current_term*(self.current_term+1)/2.
def computeTerm(self, k):
return 1.*k
from __future__ import print_function
import math
from series import Series
################################################################
class ComputePi(Series):
def __init__(self,):
Series.__init__(self)
self.current_value = 0
def __del__(self):
pass
def compute(self, N):
Series.compute(self, N)
return math.sqrt(6.*self.current_value)
def computeTerm(self, k):
return 1./(1.*k*k)
def getAnalyticPrediction(self):
return math.pi
import sys
from abc import ABC, abstractmethod
class DumperSeries(ABC):
def __init__(self, series):
self.series = series
self.precision = 4
self._file = sys.stdout
self.outfile = ''
def __del__(self):
pass
@abstractmethod
def dump(self):
pass
def setPrecision(self, precision):
self.precision = precision
def setOutFile(self, outfile):
self.outfile = outfile
if outfile == '':
return
self._file = open(outfile, 'w')
def __str__(self):
return self.dump()
################################################################
from __future__ import print_function
import sys
import argparse
from compute_pi import ComputePi
from compute_arithmetic import ComputeArithmetic
from print_series import PrintSeries
from plot_series import PlotSeries
################################################################
def main():
parser = argparse.ArgumentParser(
description='Series exercise in python')
parser.add_argument('-s', '--series_type', type=str,
help=('pi or arithmetic'),
required=True)
parser.add_argument('-d', '--dumper_type', type=str,
help=('print or plot'),
required=True)
parser.add_argument('-n', '--maxiter', type=int, required=True,
help='number of loop iteration to compute the series')
parser.add_argument('-f', '--frequency', type=int, default=1,
help='frequency at which dumps/plots are made')
parser.add_argument('-o', '--outfile', type=str, default="",
help='file where to store the output')
args = parser.parse_args()
series_type = args.series_type
dumper_type = args.dumper_type
maxiter = args.maxiter
freq = args.frequency
outfile = args.outfile
#################################################################
# creation of ojects
#################################################################
if series_type == "pi":
serie_object = ComputePi()
elif series_type == "arithmetic":
serie_object = ComputeArithmetic()
else:
raise RuntimeError("unknown series type: " + series_type)
if dumper_type == "print":
dumper_object = PrintSeries(serie_object, maxiter, freq)
elif dumper_type == "plot":
dumper_object = PlotSeries(serie_object, maxiter, freq)
else:
print("unknown dumper type: " + dumper_type)
sys.exit(-1)
dumper_object.setPrecision(20)
dumper_object.setOutFile(outfile)
#################################################################
# start of the run
#################################################################
dumper_object.dump()
if __name__ == "__main__":
main()
from __future__ import print_function
from dumper_series import DumperSeries
import matplotlib.pyplot as plt
################################################################
class PlotSeries(DumperSeries):
def __init__(self, series, maxiter, freq):
DumperSeries.__init__(self, series)
self.maxiter = maxiter
self.freq = freq
def __del__(self):
pass
def dump(self):
fig = plt.figure()
axe = fig.add_subplot(1, 1, 1)
x = []
numerical = []
analytic = []
for i in range(1, int(self.maxiter/self.freq)):
res = self.series.compute(i*self.freq-1)
x.append(i*self.freq)
numerical.append(res)
analytic.append(self.series.getAnalyticPrediction())
axe.plot(x, numerical, marker='o', label='Numerical')
axe.plot(x, analytic, label='Analytical')
axe.set_xlabel(r'$k$')
axe.set_ylabel(r'Series')
axe.legend()
if self.outfile == '':
plt.show()
else:
plt.savefig(self.outfile)
return "Plotted"
from __future__ import print_function
import math
from dumper_series import DumperSeries
################################################################
class PrintSeries(DumperSeries):
def __init__(self, series, maxiter, freq):
DumperSeries.__init__(self, series)
self.maxiter = maxiter
self.freq = freq
def __del__(self):
pass
def dump(self):
out = ""
for i in range(1, int(self.maxiter/self.freq)):
res = self.series.compute(i*self.freq-1)
res2 = self.series.compute(i*self.freq)
my_format = '{:.' + str(self.precision) + 'e}'
out += str(i*self.freq) + " "
out += my_format.format(res) + " "
out += my_format.format(res2 - res)
try:
out += " " + my_format.format(
math.fabs(res2 - self.series.getAnalyticPrediction()))
except Exception:
pass
out += "\n"
self._file.write(out)
from abc import ABC, abstractmethod
class Series(ABC):
def __init__(self):
self.current_term = 0
self.current_value = 0
def __del__(self):
pass
def compute(self, N):
if self.current_term <= N:
N -= self.current_term
else:
self.current_value = 0.
self.current_term = 0
for k in range(0, N):
self.addTerm()
return self.current_value
@abstractmethod
def getAnalyticPrediction(self):
pass
def addTerm(self):
self.current_term += 1
self.current_value += self.computeTerm(self.current_term)
def computeTerm(self, k):
pass
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment