Skip to content

Commit

Permalink
Some generic Python cleanup (#216)
Browse files Browse the repository at this point in the history
  • Loading branch information
PeterMeisrimelModelon authored Jan 29, 2024
1 parent e9fc6ac commit 43b9fcd
Show file tree
Hide file tree
Showing 36 changed files with 834 additions and 1,144 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,4 @@ jobs:
run: |
rm src/pyfmi/__init__.py
cp -rv src/pyfmi/tests/files tests
python3 -m nose --verbose tests/*
python3 -m nose --verbose tests/*.py
9 changes: 7 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import distutils
import os
import shutil
import numpy as N
import numpy as np
import ctypes.util
import sys

Expand Down Expand Up @@ -244,9 +244,14 @@ def check_extensions():
compile_time_env=compile_time_env,
compiler_directives={'language_level' : "3str"})

# Test utilities
ext_list += cythonize([os.path.join("src", "pyfmi", "tests", "test_util.pyx")],
include_path = incl_path,
compiler_directives={'language_level' : "3str"})

for i in range(len(ext_list)):

ext_list[i].include_dirs = [N.get_include(), "src", os.path.join("src", "pyfmi"), incdirs]
ext_list[i].include_dirs = [np.get_include(), "src", os.path.join("src", "pyfmi"), incdirs]
ext_list[i].library_dirs = [libdirs]
ext_list[i].language = "c"
ext_list[i].libraries = ["fmilib_shared"] if sys.platform.startswith("win") else ["fmilib"] #If windows shared, else static
Expand Down
24 changes: 8 additions & 16 deletions src/common/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,17 @@

__all__ = ['algorithm_drivers', 'core', 'diagnostics', 'io', 'plotting']

import sys
python3_flag = True if sys.hexversion > 0x03000000 else False
## for backwards compatibility, to not break 'from pyfmi.common import diagnostics_prefix'
## TODO: Future: remove this
from .diagnostics import DIAGNOSTICS_PREFIX as diagnostics_prefix

if python3_flag:
def encode(x):
if isinstance(x, str):
return x.encode()
else:
return x
def decode(x):
if isinstance(x, bytes):
return x.decode()
else:
return x
else:
def encode(x):
def encode(x):
if isinstance(x, str):
return x.encode()
else:
return x
def decode(x):
def decode(x):
if isinstance(x, bytes):
return x.decode()
else:
return x
18 changes: 11 additions & 7 deletions src/common/algorithm_drivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
Module containing optimization, simulation and initialization algorithms.
"""

import numpy as N
import numpy as np

default_int = int
int = N.int32
N.int = N.int32
int = np.int32
np.int = np.int32

class AlgorithmBase(object):
"""
Expand All @@ -33,16 +33,20 @@ class AlgorithmBase(object):
# __metaclass__=ABCMeta

# @abstractmethod
def __init__(self, model, alg_args): pass
def __init__(self, model, alg_args):
pass

# @abstractmethod
def solve(self): pass
def solve(self):
pass

# @abstractmethod
def get_result(self): pass
def get_result(self):
pass

@classmethod
def get_default_options(self): pass
def get_default_options(self):
pass

class ResultBase(object):
"""
Expand Down
56 changes: 28 additions & 28 deletions src/common/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@

import zipfile
import tempfile
import platform as PL
import platform as plat
import os
import sys
import shutil

import numpy as N
import numpy as np

# location for temporary JModelica files
def get_temp_location():
Expand Down Expand Up @@ -261,7 +261,7 @@ def get_platform_dir():
else:
platform = 'linux'

if PL.architecture()[0].startswith('32'):
if plat.architecture()[0].startswith('32'):
platform += '32'
else:
platform += '64'
Expand Down Expand Up @@ -490,20 +490,20 @@ def __init__(self, abscissa, ordinate, tol=1e-8):
"""
self._abscissa = abscissa.astype('float')
self._ordinate = ordinate
self._n = N.size(abscissa)
self._n_ordinate = N.size(self.ordinate,1)
self._n = np.size(abscissa)
self._n_ordinate = np.size(self.ordinate,1)
self._x0 = abscissa[0]
self._xf = abscissa[-1]

if not N.all(N.diff(self.abscissa) >= 0):
if not np.all(np.diff(self.abscissa) >= 0):
raise Exception("The abscissae must be increasing.")

[double_point_indices] = N.nonzero(N.abs(N.diff(self.abscissa)) <= tol)
[double_point_indices] = np.nonzero(np.abs(np.diff(self.abscissa)) <= tol)
while (len(double_point_indices) > 0):
for i in double_point_indices:
self.abscissa[i+1] = self.abscissa[i+1] + tol
[double_point_indices] = N.nonzero(
N.abs(N.diff(self.abscissa)) <= tol)
[double_point_indices] = np.nonzero(
np.abs(np.diff(self.abscissa)) <= tol)

def eval(self,x):
"""
Expand Down Expand Up @@ -561,9 +561,9 @@ def eval(self,x):
Two dimensional n x m matrix containing the ordinate values
corresponding to the argument x.
"""
y = N.zeros([N.size(x),self._n_ordinate])
y = np.zeros([np.size(x),self._n_ordinate])
for i in range(self._n_ordinate):
y[:,i] = N.interp(x,self.abscissa,self.ordinate[:,i])
y[:,i] = np.interp(x,self.abscissa,self.ordinate[:,i])
return y

class TrajectoryLinearInterpolationExtrapolation(Trajectory):
Expand All @@ -590,11 +590,11 @@ def eval(self, x):
See http://stackoverflow.com/questions/2745329/how-to-make-scipy-interpolate-give-a-an-extrapolated-result-beyond-the-input-ran
"""
y = N.zeros([N.size(x),N.size(self.ordinate,1)])
for i in range(N.size(y,1)):
y[:,i] = N.interp(x,self.abscissa,self.ordinate[:,i])
y[:,i] = N.where(x < self.abscissa[0], self.ordinate[0,i]+(x-self.abscissa[0])*(self.ordinate[0,i]-self.ordinate[1,i])/(self.abscissa[0]-self.abscissa[1]), y[:,i])
y[:,i] = N.where(x > self.abscissa[-1], self.ordinate[-1,i]+(x-self.abscissa[-1])*(self.ordinate[-1,i]-self.ordinate[-2,i])/(self.abscissa[-1]-self.abscissa[-2]), y[:,i])
y = np.zeros([np.size(x),np.size(self.ordinate,1)])
for i in range(np.size(y,1)):
y[:,i] = np.interp(x,self.abscissa,self.ordinate[:,i])
y[:,i] = np.where(x < self.abscissa[0], self.ordinate[0,i]+(x-self.abscissa[0])*(self.ordinate[0,i]-self.ordinate[1,i])/(self.abscissa[0]-self.abscissa[1]), y[:,i])
y[:,i] = np.where(x > self.abscissa[-1], self.ordinate[-1,i]+(x-self.abscissa[-1])*(self.ordinate[-1,i]-self.ordinate[-2,i])/(self.abscissa[-1]-self.abscissa[-2]), y[:,i])
return y

class TrajectoryConstantInterpolationExtrapolation(Trajectory):
Expand Down Expand Up @@ -634,27 +634,27 @@ def eval(self, x):
See http://stackoverflow.com/questions/2745329/how-to-make-scipy-interpolate-give-a-an-extrapolated-result-beyond-the-input-ran
"""
y = N.zeros([N.size(x),N.size(self.ordinate,1)])
x = N.array([x]).flatten()
y = np.zeros([np.size(x),np.size(self.ordinate,1)])
x = np.array([x]).flatten()

if self._mode == 1:
for i in range(N.size(y,1)):
for j in range(N.size(x)):
for i in range(np.size(y,1)):
for j in range(np.size(x)):
try:
y[j,i] = self.ordinate[self.abscissa<=x[j],i][-1]
except IndexError:
pass
y[:,i] = N.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i])
y[:,i] = N.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i])
y[:,i] = np.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i])
y[:,i] = np.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i])
else:
for i in range(N.size(y,1)):
for j in range(N.size(x)):
for i in range(np.size(y,1)):
for j in range(np.size(x)):
try:
y[j,i] = self.ordinate[self.abscissa>=x[j],i][0]
except IndexError:
pass
y[:,i] = N.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i])
y[:,i] = N.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i])
y[:,i] = np.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i])
y[:,i] = np.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i])
return y

class TrajectoryUserFunction(Trajectory):
Expand Down Expand Up @@ -686,9 +686,9 @@ def eval(self, x):
corresponding to the argument x.
"""
try:
y = N.array(N.matrix(self.traj(float(x))))
y = np.array(np.matrix(self.traj(float(x))))
except TypeError:
y = N.array(N.matrix(self.traj(x)).transpose())
y = np.array(np.matrix(self.traj(x)).transpose())
#In order to guarantee that the
#return values are on the correct
#form. May need to be evaluated
Expand Down
Loading

0 comments on commit 43b9fcd

Please sign in to comment.