Skip to content

Commit

Permalink
Add spectrum output to text file, closes #190 (#192)
Browse files Browse the repository at this point in the history
* Add initial to_text_file and from_text_file methods

* Enable reading of header data

* Add spectrum1dcollection tests

* Add tests for spectrum1d

* Update from_text_file docstring

* Add Codecov to Github actions

* Force use of {} after Column i: y_data[j]

* Remove from_text_file method

* Simplify header writing

* Small comment correction

* Remove unused import

* Add note that text files cannot be re-read

* Small comment correction

* Update changelog
  • Loading branch information
rebeccafair authored Sep 22, 2021
1 parent ae85195 commit 4710816
Show file tree
Hide file tree
Showing 10 changed files with 6,964 additions and 40 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/run_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ jobs:
with:
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
coverage-reports: tests_and_analysis/test/reports/coverage.xml
- uses: codecov/codecov-action@v2
if: startsWith(matrix.os, 'ubuntu')
with:
files: tests_and_analysis/test/reports/coverage.xml

publish-test-results:
needs: test
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
`Unreleased <https://github.com/pace-neutrons/Euphonic/compare/v0.6.2...HEAD>`_
----------

- New Features:

- New ``Spectrum1D.to_text_file`` and ``Spectrum1DCollection.to_text_file``
methods to write to column text files

`v0.6.2 <https://github.com/pace-neutrons/Euphonic/compare/v0.6.1...v0.6.2>`_
------

Expand Down
55 changes: 54 additions & 1 deletion euphonic/spectra.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import copy
import itertools
import math
import json
from numbers import Integral
from typing import (Any, Dict, List, Optional, overload,
Sequence, Tuple, TypeVar, Union, Type, Iterable)
Expand All @@ -15,7 +16,7 @@
_obj_to_dict, _process_dict)
from euphonic.readers.castep import read_phonon_dos_data
from euphonic.util import _get_unique_elems_and_idx
from euphonic import ureg, Quantity
from euphonic import ureg, Quantity, __version__


class Spectrum(ABC):
Expand Down Expand Up @@ -374,6 +375,25 @@ def to_dict(self) -> Dict[str, Any]:
return _obj_to_dict(self, ['x_data', 'y_data', 'x_tick_labels',
'metadata'])

def to_text_file(self, filename: str,
fmt: Optional[Union[str, Sequence[str]]] = None) -> None:
"""
Write to a text file. The header contains metadata and unit
information, the first column contains x_data and the second
column contains y_data. Note that text files written in this
format cannot be read back in by Euphonic.
Parameters
----------
filename
Name of the text file to write to
fmt
A format specifier or sequence of specifiers (one for each
column), to be passed to numpy.savetxt
"""
spec = Spectrum1DCollection.from_spectra([self])
spec.to_text_file(filename, fmt)

@classmethod
def from_dict(cls: Type[T], d: Dict[str, Any]) -> T:
"""
Expand Down Expand Up @@ -733,6 +753,39 @@ def to_dict(self) -> Dict[str, Any]:
return _obj_to_dict(self, ['x_data', 'y_data', 'x_tick_labels',
'metadata'])

def to_text_file(self, filename: str,
fmt: Optional[Union[str, Sequence[str]]] = None) -> None:
"""
Write to a text file. The header contains metadata and unit
information, the first column is x_data and each subsequent
column is a y_data spectrum. Note that text files written in
this format cannot be read back in by Euphonic.
Parameters
----------
filename
Name of the text file to write to
fmt
A format specifier or sequence of specifiers (one for each
column), to be passed to numpy.savetxt
"""
common_metadata = copy.deepcopy(self.metadata)
line_data = common_metadata.pop('line_data',
[{} for i in self.y_data])
header = [f'Generated by Euphonic {__version__}',
f'x_data in ({self.x_data.units})',
f'y_data in ({self.y_data.units})',
f'Common metadata: {json.dumps(common_metadata)}',
f'Column 1: x_data']
for i, line in enumerate(line_data):
header += [f'Column {i + 2}: y_data[{i}] {json.dumps(line)}']
out_data = np.hstack((self.get_bin_centres().magnitude[:, np.newaxis],
self.y_data.transpose().magnitude))
kwargs = {'header': '\n'.join(header)}
if fmt is not None:
kwargs['fmt'] = fmt
np.savetxt(filename, out_data, **kwargs)

@classmethod
def from_dict(cls: Type[T], d) -> T:
"""
Expand Down
Loading

0 comments on commit 4710816

Please sign in to comment.