Skip to content

Commit

Permalink
ortensor added to utils
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrolexa committed Mar 20, 2024
1 parent 03995e0 commit 6690ce7
Show file tree
Hide file tree
Showing 7 changed files with 259 additions and 151 deletions.
2 changes: 2 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* added eap and epa Grain methods
* surfor for Grains normalized by factor 2
* vertex_angles property added
* ortensor added to utils
* agg accepts kwargs allowing define names of aggregated columns

### 0.5.4 (05 Mar 2024)
* shapelysmooth methods added for smoothing
Expand Down
25 changes: 15 additions & 10 deletions notebooks/polylx_tutorial.ipynb

Large diffs are not rendered by default.

24 changes: 19 additions & 5 deletions polylx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,24 @@
import networkx as nx
import seaborn as sns
from .core import Grain, Boundary, Grains, Boundaries, Sample, Fractnet
from .utils import deg, circular
from .utils import deg, circular, ortensor

__author__ = 'Ondrej Lexa'
__email__ = '[email protected]'
__author__ = "Ondrej Lexa"
__email__ = "[email protected]"

__all__ = ['Grain', 'Boundary', 'Grains', 'Boundaries', 'Sample', 'Fractnet',
'np', 'plt', 'pd', 'nx', 'sns', 'deg', 'circular']
__all__ = [
"Grain",
"Boundary",
"Grains",
"Boundaries",
"Sample",
"Fractnet",
"np",
"plt",
"pd",
"nx",
"sns",
"deg",
"circular",
"ortensor",
]
30 changes: 22 additions & 8 deletions polylx/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1884,6 +1884,8 @@ def class_names(self):
def df(self, *attrs):
"""Returns ``pandas.DataFrame`` of object attributes.
Note: Use 'class' for class names.
Example:
>>> g.df('ead', 'ar')
Expand Down Expand Up @@ -1912,26 +1914,38 @@ def get(self, attr):
idx = pd.Index(self.fid, name="fid")
return pd.Series(getattr(self, attr), index=idx, name=attr)

def agg(self, *pairs):
def agg(self, **kwargs):
"""Returns concatenated result of multiple aggregations (different
aggregation function for different attributes) based on actual
classification. For single aggregation function use directly
pandas groups, e.g. g.groups('lao', 'sao').agg(circular.mean)
Example:
>>> g.agg('area', np.sum, 'ead', np.mean, 'lao', circular.mean)
area ead lao
>>> g.agg(
total_area=['area', 'sum'],
mean_ead =['ead', 'mean'],
mean_orientation=['lao', circular.mean]
)
total_area mean_ead mean_orientation
class
ksp 2.443733 0.089710 76.875488
pl 1.083516 0.060629 94.197847
qtz 1.166097 0.068071 74.320337
ksp 2.443733 0.089710 76.875488
pl 1.083516 0.060629 94.197847
qtz 1.166097 0.068071 74.320337
"""
assert len(kwargs) > 0, "No aggregation defined"
pieces = []
for attr, aggfunc in zip(pairs[0::2], pairs[1::2]):
columns = []
for lbl, (attr, aggfunc) in kwargs.items():
columns.append(lbl)
df = self.groups(attr).agg(aggfunc)
pieces.append(df)
return pd.concat(pieces, axis=1).reindex(self.class_names)
return (
pd.concat(pieces, axis=1)
.reindex(self.class_names)
.set_axis(columns, axis=1)
)

def accumulate(self, *methods):
"""Returns accumulated result of multiple Group methods based
Expand Down
90 changes: 56 additions & 34 deletions polylx/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,97 +34,119 @@


class Report(object):

def __init__(self, title="Report"):
self.rst = []
self.images = []
poc = len(title)
self.rst.append(poc * '=')
self.rst.append(poc * "=")
self.rst.append(title)
self.rst.append(poc * '=')
self.rst.append(poc * "=")
self.fin()

def fin(self):
self.rst.append('')
self.rst.append("")

def add_chapter(self, title):
poc = len(title)
self.rst.append(title)
self.rst.append(poc * '=')
self.rst.append(poc * "=")
self.fin()

def add_section(self, title):
poc = len(title)
self.rst.append(title)
self.rst.append(poc * '-')
self.rst.append(poc * "-")
self.fin()

def add_subsection(self, title):
poc = len(title)
self.rst.append(title)
self.rst.append(poc * '~')
self.rst.append(poc * "~")
self.fin()

def transition(self):
self.rst.append('---------')
self.rst.append("---------")
self.fin()

def figure(self, filename, width=None, height=None):
self.rst.append('.. figure:: {}'.format(filename))
self.rst.append(".. figure:: {}".format(filename))
if width:
self.rst.append(' :width: {}'.format(width))
self.rst.append(" :width: {}".format(width))
if height:
self.rst.append(' :height: {}'.format(height))
self.rst.append(" :height: {}".format(height))
self.fin()

def matplotlib_fig(self, fig, width=None, height=None, bbox_inches='tight', dpi=150):
f = tempfile.NamedTemporaryFile(suffix='.png')
fig.savefig(f, format='png', bbox_inches=bbox_inches, dpi=dpi)
def matplotlib_fig(
self, fig, width=None, height=None, bbox_inches="tight", dpi=150
):
f = tempfile.NamedTemporaryFile(suffix=".png")
fig.savefig(f, format="png", bbox_inches=bbox_inches, dpi=dpi)
self.figure(f.name, width, height)
self.images.append(f)

def plot(self, g, legend=None, loc='auto', alpha=0.8, dpi=150, width=None, height=None):
f = tempfile.NamedTemporaryFile(suffix='.png')
def plot(
self, g, legend=None, loc="auto", alpha=0.8, dpi=150, width=None, height=None
):
f = tempfile.NamedTemporaryFile(suffix=".png")
g.savefig(f, legend, loc, alpha, dpi)
self.figure(f.name, width, height)
self.images.append(f)

def pagebreak(self):
self.rst.append('.. raw:: pdf')
self.rst.append(".. raw:: pdf")
self.fin()
self.rst.append(' PageBreak')
self.rst.append(" PageBreak")
self.fin()

def table(self, rows, title='Table', header=None, format=None, stub_columns=None, widths=None):
self.rst.append('.. csv-table:: {}'.format(title))
def table(
self,
rows,
title="Table",
header=None,
format=None,
stub_columns=None,
widths=None,
):
self.rst.append(".. csv-table:: {}".format(title))
if header:
self.rst.append(' :header: {}'.format(','.join(header)))
self.rst.append(" :header: {}".format(",".join(header)))
if widths:
self.rst.append(' :widths: {}'.format(','.join([str(w) for w in widths])))
self.rst.append(" :widths: {}".format(",".join([str(w) for w in widths])))
if stub_columns:
self.rst.append(' :stub-columns: {}'.format(stub_columns))
self.rst.append(" :stub-columns: {}".format(stub_columns))
self.fin()
if format is None:
format = len(rows[0]) * ['']
row_template = ' ' + ','.join(['{' + f + '}' for f in format])
format = len(rows[0]) * [""]
row_template = " " + ",".join(["{" + f + "}" for f in format])
for row in rows:
self.rst.append(row_template.format(*row))
self.fin()

def dataframe(self, df, title='Table', header=None, format=None, stub_columns=None, widths=None):
rows = [row.split(',') for row in df.to_csv().split()]
def dataframe(
self,
df,
title="Table",
header=None,
format=None,
stub_columns=None,
widths=None,
):
rows = [row.split(",") for row in df.to_csv().split()]
if not header:
header = [df.index.name] + list(df.columns)
rows = [[df.ix[i].name] + list(df.ix[i]) for i in range(len(df))]
self.table(rows, title, header, format, stub_columns, widths)

def write_rst(self, file='report.rst'):
with open(file, 'w') as rstfile:
def write_rst(self, file="report.rst"):
with open(file, "w") as rstfile:
for ln in self.rst:
print(ln, file=rstfile)

def write_pdf(self, file='report.pdf'):
p = subprocess.Popen(['rst2pdf', '-s', 'dejavu', '-o', file],
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.STDOUT)
p.communicate(input='\n'.join(self.rst).encode(encoding='UTF-8'))
def write_pdf(self, file="report.pdf"):
p = subprocess.Popen(
["rst2pdf", "-s", "dejavu", "-o", file],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
p.communicate(input="\n".join(self.rst).encode(encoding="UTF-8"))
4 changes: 2 additions & 2 deletions polylx/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import readline
except ImportError:
pass
import numpay as np
import matplotlib.pyplot as pyplot
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from polylx import *

Expand Down
Loading

0 comments on commit 6690ce7

Please sign in to comment.