ptypy.core package¶
Submodules¶
ptypy.core.classes module¶
Container management.
This module defines flexible containers for the various quantities needed for ptychographic reconstructions.
- Container class
A high-level container that keeps track of sub-containers (Storage) and Views onto them. A container can copy itself to produce a buffer needed for calculations. Some basic Mathematical operations are implemented at this level as in place operations. In general, operations on arrays should be done using the Views, which simply return numpy arrays.
- Storage class
The sub-container, wrapping a numpy array buffer. A Storage defines a system of coordinate (for now only a scaled translation of the pixel coordinates, but more complicated affine transformation could be implemented if needed). The sub-class DynamicStorage can adapt the size of its buffer (cropping and/or padding) depending on the Views.
- View class
A low-weight class that contains all information to access a 2D piece of a Storage within a Container. The basic idea is that the View access is controlled by a physical position and its frame, such that one is not bothered by memory/array addresses when accessing data.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- class ptypy.core.classes.Base(owner=None, ID=None, BeOwner=True)¶
Bases:
object
Ptypy Base class to support some kind of hierarchy, conversion to and from dictionaries as well as a ‘cross-node’ ID management of python objects
- Parameters
owner (Other subclass of Base or Base) – Owner gives IDs to other ptypy objects that refer to it as owner. Owner also keeps a reference to these objects in its internal _pool where objects are key-sorted according to their ID prefix
ID (None, str or int) –
BeOwner (bool) – Set to False if this instance is not intended to own other ptypy objects.
- ID¶
- calc_mem_usage()¶
- numID¶
- owner¶
- class ptypy.core.classes.Container(owner=None, ID=None, data_type='complex', data_dims=2, distribution='cloned')¶
Bases:
ptypy.core.classes.Base
High-level container class.
Container can be seen as a “super-numpy-array” which can contain multiple sub-containers of type
Storage
, potentially of different shape, along with allView
instances that act on these Storages to extract data from the internal data bufferStorage.data
.Typically there will be five such base containers in a
Ptycho
reconstruction instance:Cprobe, Storages for the illumination, i.e. probe,
Cobj, Storages for the sample transmission, i.e. object,
Cexit, Storages for the exit waves,
Cdiff, Storages for diffraction data, usually one per scan,
Cmask, Storages for masks (and weights), usually one per scan,
A container can conveniently duplicate all its internal
Storage
instances into a new Container usingcopy()
. This feature is intensively used in the reconstruction engines where buffer copies are needed to temporarily store results. These copies are referred by the “original” container through the propertycopies()
and a copy refers to its original through the attributeoriginal
In order to reduce the number ofView
instances, Container copies do not hold views and use instead the Views held by the original container- Variables
original (Container) – If self is copy of a Container, this attribute refers to the original Container. Otherwise it is None.
data_type (str) – Either “single” or “double”
- Parameters
ID (str or int) – A unique ID, managed by the parent.
owner (Base) – A possible subclass of
Base
that holds this Container.data_type (str or numpy.dtype) – data type - either a numpy.dtype object or ‘complex’ or ‘real’ (precision is taken from ptycho.FType or ptycho.CType)
data_dims (int) – dimension of data, can be 2 or 3
distribution (str) – Indicates if the data is “cloned” in all MPI processes or “scattered”
- ID¶
- property S¶
A property that returns the internal dictionary of all
Storage
instances in thisContainer
- property Sp¶
A property that returns the internal dictionary of all
Storage
instances in thisContainer
as aParam
- property Vp¶
A property that returns the internal dictionary of all
View
instances in thisContainer
as aParam
- __setitem__(view, newdata)¶
Set content given by view.
- allreduce(op=None)¶
Performs MPI parallel
allreduce
with a sum as reduction for allStorage
instances held by self- Parameters
c (Container) – Input
op – Reduction operation. If
None
uses sum.
- clear()¶
Reduce / delete all data in attached storages
- copy(ID=None, fill=None, dtype=None)¶
Create a new
Container
matching self.The copy does not manage views.
- Parameters
fill (scalar or None) – If None (default), copy content. If scalar, initializes to this value
dtype (valid data type or None) – If None, the copy will have the same data type as the original, is specified the returned instance will contain empty buffers.
- delete_copy(copy_IDs=None)¶
Delete a copy or all copies of this container from owner instance.
- Parameters
copy_IDs (str) – ID of copy to be deleted. If None, deletes all copies
- property dtype¶
Property that returns numpy dtype of all internal data buffers
- fill(fill=0.0)¶
Fill all storages with scalar value fill
- formatted_report(table_format=None, offset=8, align='right', separator=' : ', include_header=True)¶
Returns formatted string and a dict with the respective information
- Parameters
table_format (list) –
List of (item, length) pairs where item is name of the info to be listed in the report and length is the column width. The following items are allowed:
memory, for memory usage of the storages and total use
shape, for shape of internal storages
dimensions, is
shape \* psize
psize, for pixel size of storages
views, for number of views in each storage
offset (int, optional) – First column width
separator (str, optional) – Column separator
align (str, optional) – Column alignment, either
'right'
or'left'
include_header (bool) – Include a header if True
- Returns
fstring (str) – Formatted string
dct (dict) – Dictionary containing with the respective info to the keys in table_format
See also
- info()¶
Returns the container’s total buffer space in bytes and storage info.
- Returns
space (int) – Accumulated memory usage of all data buffers in this Container
fstring (str) – Formatted string
Note
May get deprecated in future. Use formatted_report instead.
See also
- property nbytes¶
Return total number of bytes used by numpy array buffers in this container. This is not the actual size in memory of the whole container, as it does not include the views or dictionary overhead.
- ndim¶
Default data dimensionality for Views and Storages.
- new_storage(ID=None, **kwargs)¶
Create and register a storage object.
- Parameters
ID (str) – An ID for the storage. If None, a new ID is created. An error will be raised if the ID already exists.
kwargs – Arguments for new storage creation. See doc for
Storage
.
- numID¶
- owner¶
- reformat(also_in_copies=False)¶
Reformats all storages in this container.
- Parameters
also_in_copies (bool) – If True, also reformat associated copies of this container
- report()¶
Returns a formatted report string on all storages in this container.
- property size¶
Return total number of pixels in this container.
- property storages¶
A property that returns the internal dictionary of all
Storage
instances in thisContainer
- class ptypy.core.classes.POD(ptycho=None, model=None, ID=None, views=None, geometry=None, **kwargs)¶
Bases:
ptypy.core.classes.Base
POD : Ptychographic Object Descriptor
A POD brings together probe view, object view and diff view. It also gives access to “exit”, a (coherent) exit wave, and to propagation objects to go from exit to diff space.
- Parameters
ptycho (Ptycho) – The instance of Ptycho associated with this pod.
model (ScanModel) – The instance of ScanModel (or it subclasses) which describes this pod.
ID (str or int) – The pod ID, If None it is managed by the ptycho.
views (dict or Param) – The views. See
DEFAULT_VIEWS
.geometry (Geo) – Geometry class instance and attached propagator
- DEFAULT_VIEWS = {'diff': None, 'exit': None, 'mask': None, 'obj': None, 'probe': None}¶
Default set of
View
s used by a POD
- ID¶
- property active¶
Convenience property that describes whether this pod is active or not. Equivalent to
self.di_view.active
- property bw¶
Convenience property that returns backward propagator of attached Geometry instance. Equivalent to
self.geometry.propagator.bw
.
- property diff¶
Convenience property that links to slice of diffraction
Storage
. Equivalent toself.di_view.data
.
- property downsample¶
Convencience property that returns downsample function of attached Geometry instance. Equivalent to
self.geometry.downsample
.
- property exit¶
Convenience property that links to slice of exit wave
Storage
. Equivalent toself.pr_view.data
.
- property fw¶
Convenience property that returns forward propagator of attached Geometry instance. Equivalent to
self.geometry.propagator.fw
.
- property mask¶
Convenience property that links to slice of masking
Storage
. Equivalent toself.ma_view.data
.
- numID¶
- property object¶
Convenience property that links to slice of object
Storage
. Usually equivalent toself.ob_view.data
.
- owner¶
- pr_view¶
A reference to the (pr)obe-view. (ob)ject-, (ma)sk- and (di)ff-view are accessible in the same manner (
self.xx_view
).
- property probe¶
Convenience property that links to slice of probe
Storage
. Equivalent toself.pr_view.data
.
- property upsample¶
Convencience property that returns upsample function of attached Geometry instance. Equivalent to
self.geometry.upsample
.
- class ptypy.core.classes.Storage(container, ID=None, data=None, shape=(1, 1, 1), fill=0.0, psize=1.0, origin=None, layermap=None, padonly=False, padding=0, **kwargs)¶
Bases:
ptypy.core.classes.Base
Inner container handling access to data arrays.
This class essentially manages access to an internal numpy array buffer called
data
It returns a view to coordinates given (slicing)
It contains a physical coordinate grid
- Parameters
container (Container) – The container instance
ID (None, str or int) – A unique ID, managed by the parent, if None ID is generated by parent.
data (ndarray or None) – A numpy array to use as initial buffer. Deprecated in v0.3, use fill method instead.
shape (tuple, int, or None) – The shape of the buffer. If None or int, the dimensionality is found from the owning Container instance. Otherwise the dimensionality is len(shape)-1.
fill (float or complex) – The default value to fill storage with, will be converted to data type of owner.
psize (float or (ndim)-tuple of float) – The physical pixel size.
origin ((ndim)-tuple of int) – The physical coordinates of the [0,..,0] pixel (upper-left corner of the storage buffer).
layermap (list or None) – A list (or 1D numpy array) mapping input layer indices to the internal buffer. This may be useful if the buffer contains only a portion of a larger data set (as when using distributed data with MPI). If None, provide direct access. to the 3d internal data.
padonly (bool) – If True, reformat() will enlarge the internal buffer if needed, but will not shrink it.
padding (int) – Number of pixels (voxels) to add as padding around the area defined by the views.
- ID¶
- __getitem__(v)¶
Storage[v]
- Returns
The view to internal data buffer corresponding to View or layer v
- Return type
ndarray
- __setitem__(v, newdata)¶
Storage[v] = newdata
Set internal data buffer to newdata for the region of view v.
- Parameters
v (View) – A View for this storage
newdata (ndarray) – Two-dimensional array that fits the view’s shape
- allreduce(op=None)¶
Performs MPI parallel
allreduce
with a default sum as reduction operation for internal data bufferself.data
. This method does nothing if the storage is distributed across nodes.- Parameters
op – Reduction operation. If
None
uses sum.
- property center¶
Return the position of the origin relative to the upper-left corner of the storage, in pixel coordinates
- copy(owner=None, ID=None, fill=None)¶
Return a copy of this storage object.
Note: the returned copy has the same container as self.
- Parameters
ID (str or int) – A unique ID, managed by the parent
fill (scalar or None) – If float, set the content to this value. If None, copy the current content.
- data¶
Three/four or potentially N-dimensional array as data buffer
- property dtype¶
- fill(fill=None)¶
Fill managed buffer.
- Parameters
fill (scalar, numpy array or None.) – Fill value to use. If fill is a numpy array, it is cast as self.dtype and self.shape is updated to reflect the new buffer shape. If fill is None, use default value (self.fill_value).
- fill_value¶
Default fill value
- formatted_report(table_format=None, offset=8, align='right', separator=' : ', include_header=True)¶
Returns formatted string and a dict with the respective information
- Parameters
table_format (list, optional) –
List of (item,*length*) pairs where item is name of the info to be listed in the report and length is the column width. The following items are allowed:
memory, for memory usage of the storages and total use
shape, for shape of internal storages
dimensions, is
shape \* psize
psize, for pixel size of storages
views, for number of views in each storage
offset (int, optional) – First column width
separator (str, optional) – Column separator.
align (str, optional) – Column alignment, either
'right'
or'left'
.include_header (bool, optional) – Include a header if True.
- Returns
fstring (str) – Formatted string
dct (dict) – Dictionary containing with the respective info to the keys in table_format
- get_view_coverage()¶
Creates an array in the shape of internal buffer where the value of each pixel represents the number of views that cover that pixel
- Returns
view coverage in the shape of internal buffer
- Return type
ndarray
- grids()¶
- Returns
x, y – grids in the shape of internal buffer
- Return type
ndarray
- numID¶
- property origin¶
Return the physical position of the upper-left corner of the storage.
- owner¶
- property psize¶
The pixel size.
- reformat(newID=None, update=True)¶
Crop or pad if required.
- Parameters
newID (str or int) – If None (default) act on self. Otherwise create a copy of self before doing the cropping and padding.
update (bool) – If True, updates all Views before reformatting. Not necessarily needed, if Views have been recently instantiated. Roughly doubles execution time.
- Returns
s – returns new Storage instance in same
Container
if newId is not None.- Return type
- report()¶
- Returns
a formatted string giving a report on this storage.
- Return type
str
- update()¶
Update internal state, including all views on this storage to ensure consistency with the physical coordinate system.
- update_views(v=None)¶
Update the access information for a given view.
- Parameters
v (View or None) – The view object to update. If None, loop through all views. Apart from that, no check is done, not even whether the view is actually on self. Use cautiously.
- property views¶
Return all the views that refer to this storage.
- zoom_to_psize(new_psize, **kwargs)¶
Changes pixel size and zooms the data buffer along last two axis accordingly, updates all attached views and reformats if necessary. untested!!
- Parameters
new_psize (scalar or array_like) – new pixel size
- class ptypy.core.classes.View(container, ID=None, accessrule=None, **kwargs)¶
Bases:
ptypy.core.classes.Base
A ‘window’ on a Container.
A view stores all the slicing information to extract a 2D piece of Container.
Note
The final structure of this class is yet up to debate and the constructor signature may change. Especially since ‘DEFAULT_ACCESSRULE’ is yet so small, its contents could be incorporated in the constructor call.
- Parameters
container (Container) – The Container instance this view applies to.
ID (str or int) – ID for this view. Automatically built from ID if None.
accessrule (dict) – All the information necessary to access the wanted slice. Maybe subject to change as code evolve. See keyword arguments Almost all keys of accessrule will be available as attributes in the constructed View instance.
- Keyword Arguments
storageID (str) – ID of storage, If the Storage does not exist it will be created! (default is
None
)shape (int or tuple of int) – Shape of the view in pixels (default is
None
)coord (2-tuple of float,) – Physical coordinates (meter) of the center of the view.
psize (float or tuple of float) – Pixel size in (meter) . Required for storage initialization.
layer (int) – Index of the third dimension if applicable. (default is
0
)active (bool) – Whether this view is active (default is
True
)
- DEFAULT_ACCESSRULE = {'active': True, 'coord': None, 'layer': 0, 'psize': 1.0, 'shape': None, 'storageID': None}¶
- ID¶
- property active¶
Active state. If False this view will be ignored when resizing the data buffer of the associated
Storage
.
- property coord¶
The View’s physical coordinate (meters)
- copy(ID=None, update=True)¶
- property data¶
The view content in data buffer of associated storage.
- property dcoord¶
Center coordinate (index) in data buffer.
- property dhigh¶
High side of the View’s data range.
- property dlayer¶
The “layer” i.e. first axis index in Storage data buffer
- property dlow¶
Low side of the View’s data range.
- error¶
- property layer¶
- property ndim¶
- numID¶
- owner¶
- property pcoord¶
The physical coordinate in pixel space
- property pod¶
Returns first
POD
in theself.pods
dict. This is a common call in the code and has therefore found its way here. May returnNone
if there is no pod connected.
- property psize¶
Pixel size of the View.
- property shape¶
Two dimensional shape of View.
- property slice¶
Returns a slice-tuple according to
self.layer
,self.dlow
andself.dhigh
. Please note, that this may not always makes sense
- property sp¶
The subpixel difference (meters) between physical coordinate and data coordinate.
ptypy.core.data module¶
data - Diffraction data access.
This module defines a PtyScan, a container to hold the experimental data of a ptychography scan. Instrument-specific reduction routines should inherit PtyScan to prepare data for the Ptycho Instance in a uniform format.
The experiment specific child class only needs to overwrite 2 functions of the base class:
For the moment the module contains two main objects: PtyScan, which holds a single ptychography scan, and DataSource, which holds a collection of datascans and feeds the data as required.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- class ptypy.core.data.MoonFlowerScan(pars=None, **kwargs)¶
Bases:
ptypy.core.data.PtyScan
Test PtyScan class producing a romantic ptychographic data set of a moon illuminating flowers.
Override parent class default:
Parent pars are for the
- DEFAULT = {'add_poisson_noise': True, 'auto_center': None, 'block_wait_count': 0, 'center': 'fftshift', 'chunk_format': '.chunk%02d', 'density': 0.2, 'dfile': None, 'distance': 7.19, 'energy': 7.2, 'experimentID': None, 'label': None, 'load_parallel': 'data', 'min_frames': 1, 'model': 'round', 'name': 'MoonFlowerScan', 'num_frames': 100, 'orientation': None, 'photons': 100000000.0, 'positions_theory': None, 'psf': 0.0, 'psize': 0.000172, 'rebin': None, 'save': None, 'shape': 128, 'version': 0.1}¶
- check(frames=None, start=None)¶
Override in subclass for custom implementation
This method checks how many frames the preparation routine may process, starting from frame start at a request of frames.
This method is supposed to return the number of accessible frames for preparation and should determine if data acquisition for this scan is finished. Its main purpose is to allow for a data acquisition scheme, where the number of frames is not known when
PtyScan
is constructed, i.e. a data stream or an on-the-fly reconstructions.Note
If
num_frames
is set on__init__()
of the subclass, this method can be left as it is.- Parameters
frames (int or None) – Number of frames requested.
start (int or None) – Scanpoint index to start checking from.
- Returns
frames_accessible (int) – Number of frames readable.
end_of_scan (int or None) – is one of the following, - 0, end of the scan is not reached - 1, end of scan will be reached or is - None, can’t say
- load(indices)¶
Override in subclass for custom implementation
Loads data according to node specific scanpoint indices that have been determined by
LoadManager
or otherwise.- Returns
raw, positions, weight – Dictionaries whose keys are the given scan point indices and whose values are the respective frame / position according to the scan point index. weight and positions may be empty
- Return type
dict
Note
This is the most important method to change when subclassing
PtyScan
. Most often it suffices to override the constructor and this method to create a subclass suited for a specific experiment.
- load_positions()¶
Override in subclass for custom implementation
Called in
initialize()
Loads all positions for all diffraction patterns in this scan. The positions loaded here will be available by all processes through the attribute
self.positions
. If you specify position on a per frame basis inload()
, this function has no effect.If theoretical positions
positions_theory
are provided in the initial parameter setDEFAULT
, specifying positions here has NO effect and will be ignored.The purpose of this function is to avoid reloading and parallel reads on files that may require intense parsing to retrieve the information, e.g. long SPEC log files. If parallel reads or log file parsing for each set of frames is not a time critical issue of the subclass, reimplementing this function can be ignored and it is recommended to only reimplement the
load()
method.If load_parallel is set to all or common`, this function is executed by all nodes, otherwise the master node executes this function and broadcasts the results to other nodes.
- Returns
positions – A (N,2)-array where N is the number of positions.
- Return type
ndarray
Note
Be aware that this method sets attribute
num_frames
in the following manner.If
num_frames == None
:num_frames = N
.If
num_frames < N
, no effect.If
num_frames > N
:num_frames = N
.
- load_weight()¶
Override in subclass for custom implementation
Called in
initialize()
Loads a common (2d)-weight for all diffraction patterns. The weight loaded here will be available by all processes through the attribute
self.weight2d
. If a per-frame-weight is specified inload()
, this function has no effect.The purpose of this function is to avoid reloading and parallel reads. If that is not critical to the implementation, reimplementing this function in a subclass can be ignored.
If load_parallel is set to all or common`, this function is executed by all nodes, otherwise the master node executes this function and broadcasts the results to other nodes.
- Returns
weight2d – A two-dimensional array with a shape compatible to the raw diffraction data frames
- Return type
ndarray
Note
For now, weights will be converted to a mask,
mask = weight2d > 0
for use in reconstruction algorithms. It is planned to use a general weight instead of a mask in future releases.
- ptypy.core.data.PTYD = {'chunks': {}, 'info': {}, 'meta': {}}¶
Basic Structure of a .ptyd datafile
- class ptypy.core.data.PtyScan(pars=None, **kwargs)¶
Bases:
object
PtyScan: A single ptychography scan, created on the fly or read from file.
BASECLASS
- Objectives:
Stand alone functionality
Can produce .ptyd data formats
Child instances should be able to prepare from raw data
On-the-fly support in form of chunked data.
mpi capable, child classes should not worry about mpi
Default data parameters. See
scan.data
Class creation with minimum set of parameters, see
PtyScan.DEFAULT
Please note that class creation is not meant to load data.Call
initialize
to begin loading and data file creation.- CODES = {'msg1': 'Scan unfinished. More frames available after a pause', 'msgEOS': 'End of scan reached'}¶
- DEFAULT = {'add_poisson_noise': False, 'auto_center': None, 'center': 'fftshift', 'chunk_format': '.chunk%02d', 'dfile': None, 'distance': 7.19, 'energy': 7.2, 'experimentID': None, 'label': None, 'load_parallel': 'data', 'min_frames': 1, 'name': 'PtyScan', 'num_frames': None, 'orientation': None, 'positions_theory': None, 'psize': 0.000172, 'rebin': None, 'save': None, 'shape': 256, 'version': 0.1}¶
- EOS = 'msgEOS'¶
- METAKEYS = ['version', 'num_frames', 'label', 'shape', 'psize', 'energy', 'center', 'distance']¶
Keys to store in meta param
- WAIT = 'msg1'¶
- property abort¶
- auto(frames)¶
Repeated calls to this function will process the data.
- Parameters
frames (int) – Number of frames to process.
- Returns
- one of the following
WAIT, if scan’s end is not reached, but no data could be prepared yet
EOS, if scan’s end is reached
a data package otherwise
- Return type
variable
- check(frames=None, start=None)¶
Override in subclass for custom implementation
This method checks how many frames the preparation routine may process, starting from frame start at a request of frames.
This method is supposed to return the number of accessible frames for preparation and should determine if data acquisition for this scan is finished. Its main purpose is to allow for a data acquisition scheme, where the number of frames is not known when
PtyScan
is constructed, i.e. a data stream or an on-the-fly reconstructions.Note
If
num_frames
is set on__init__()
of the subclass, this method can be left as it is.- Parameters
frames (int or None) – Number of frames requested.
start (int or None) – Scanpoint index to start checking from.
- Returns
frames_accessible (int) – Number of frames readable.
end_of_scan (int or None) – is one of the following, - 0, end of the scan is not reached - 1, end of scan will be reached or is - None, can’t say
- correct(raw, weights, common)¶
Override in subclass for custom implementation
Place holder for dark and flatfield correction. If
load
already provides data in the form of photon counts, and no frame specific weight is needed, this method may be left as it is.May get merged with
load
in future.- Returns
data, weights – Flat and dark-corrected data dictionaries. These dictionaries must have the same keys as the input raw and contain corrected frames (data) and statistical weights (weights) which are zero for invalid or masked pixel other the number of detector counts that correspond to one photon count
- Return type
dict
- property end_of_scan¶
- property frames_accessible¶
- get_data_chunk(chunksize, start=None)¶
This function prepares a container that is compatible to data package.
This function is called from the auto() function.
- info¶
Param
container that stores all input parameters.
- initialize()¶
Begins the Data preparation and intended as the first method that does read-write access on (large) data. Does the following:
Creates a *.ptyd data file at location specified by
dfile
(master node only)Calls
load_weight()
,load_positions()
load_common()
(master node only forload_parallel==None
orload_parallel=='data'
)Sets
num_frames
if neededCalls
post_initialize()
- load(indices)¶
Override in subclass for custom implementation
Loads data according to node specific scanpoint indices that have been determined by
LoadManager
or otherwise.- Returns
raw, positions, weight – Dictionaries whose keys are the given scan point indices and whose values are the respective frame / position according to the scan point index. weight and positions may be empty
- Return type
dict
Note
This is the most important method to change when subclassing
PtyScan
. Most often it suffices to override the constructor and this method to create a subclass suited for a specific experiment.
- load_common()¶
Override in subclass for custom implementation
Called in
initialize()
Loads anything and stores that in a dict. This dict will be available to all processes after
initialize()
through the attributecommon
The purpose of this method is the same as
load_weight()
andload_positions()
except for that the contents ofcommon
have no built-in effect of the behavior in the processing other than the user specifies it in py:meth:loadIf load_parallel is set to all or common`, this function is executed by all nodes, otherwise the master node executes this function and broadcasts the results to other nodes.
- Returns
common
- Return type
dict
- load_positions()¶
Override in subclass for custom implementation
Called in
initialize()
Loads all positions for all diffraction patterns in this scan. The positions loaded here will be available by all processes through the attribute
self.positions
. If you specify position on a per frame basis inload()
, this function has no effect.If theoretical positions
positions_theory
are provided in the initial parameter setDEFAULT
, specifying positions here has NO effect and will be ignored.The purpose of this function is to avoid reloading and parallel reads on files that may require intense parsing to retrieve the information, e.g. long SPEC log files. If parallel reads or log file parsing for each set of frames is not a time critical issue of the subclass, reimplementing this function can be ignored and it is recommended to only reimplement the
load()
method.If load_parallel is set to all or common`, this function is executed by all nodes, otherwise the master node executes this function and broadcasts the results to other nodes.
- Returns
positions – A (N,2)-array where N is the number of positions.
- Return type
ndarray
Note
Be aware that this method sets attribute
num_frames
in the following manner.If
num_frames == None
:num_frames = N
.If
num_frames < N
, no effect.If
num_frames > N
:num_frames = N
.
- load_weight()¶
Override in subclass for custom implementation
Called in
initialize()
Loads a common (2d)-weight for all diffraction patterns. The weight loaded here will be available by all processes through the attribute
self.weight2d
. If a per-frame-weight is specified inload()
, this function has no effect.The purpose of this function is to avoid reloading and parallel reads. If that is not critical to the implementation, reimplementing this function in a subclass can be ignored.
If load_parallel is set to all or common`, this function is executed by all nodes, otherwise the master node executes this function and broadcasts the results to other nodes.
- Returns
weight2d – A two-dimensional array with a shape compatible to the raw diffraction data frames
- Return type
ndarray
Note
For now, weights will be converted to a mask,
mask = weight2d > 0
for use in reconstruction algorithms. It is planned to use a general weight instead of a mask in future releases.
- num_frames¶
Total number of frames to prepare / load. Set by
num_frames
- post_initialize()¶
Placeholder. Called at the end of
initialize()
by all processes.Use this method to benefit from ‘hard-to-retrieve but now available’ information after initialize.
- report(what=None, shout=True)¶
Make a report on internal structure.
- class ptypy.core.data.PtydScan(pars=None, **kwargs)¶
Bases:
ptypy.core.data.PtyScan
PtyScan provided by native “ptyd” file format.
PtyScan provided by native “ptyd” file format.
- DEFAULT = {'add_poisson_noise': False, 'auto_center': None, 'center': 'fftshift', 'chunk_format': '.chunk%02d', 'dfile': None, 'distance': 7.19, 'energy': 7.2, 'experimentID': None, 'label': None, 'load_parallel': 'data', 'min_frames': 1, 'name': 'PtydScan', 'num_frames': None, 'orientation': None, 'positions_theory': None, 'psize': 0.000172, 'rebin': None, 'save': None, 'shape': 256, 'source': 'file', 'version': 0.1}¶
- check(frames=None, start=None)¶
Implementation of the check routine for a .ptyd file format.
See also
- load(indices)¶
Load from ptyd.
Due to possible chunked data, slicing frames is non-trivial.
- load_positions()¶
Override in subclass for custom implementation
Called in
initialize()
Loads all positions for all diffraction patterns in this scan. The positions loaded here will be available by all processes through the attribute
self.positions
. If you specify position on a per frame basis inload()
, this function has no effect.If theoretical positions
positions_theory
are provided in the initial parameter setDEFAULT
, specifying positions here has NO effect and will be ignored.The purpose of this function is to avoid reloading and parallel reads on files that may require intense parsing to retrieve the information, e.g. long SPEC log files. If parallel reads or log file parsing for each set of frames is not a time critical issue of the subclass, reimplementing this function can be ignored and it is recommended to only reimplement the
load()
method.If load_parallel is set to all or common`, this function is executed by all nodes, otherwise the master node executes this function and broadcasts the results to other nodes.
- Returns
positions – A (N,2)-array where N is the number of positions.
- Return type
ndarray
Note
Be aware that this method sets attribute
num_frames
in the following manner.If
num_frames == None
:num_frames = N
.If
num_frames < N
, no effect.If
num_frames > N
:num_frames = N
.
- load_weight()¶
Override in subclass for custom implementation
Called in
initialize()
Loads a common (2d)-weight for all diffraction patterns. The weight loaded here will be available by all processes through the attribute
self.weight2d
. If a per-frame-weight is specified inload()
, this function has no effect.The purpose of this function is to avoid reloading and parallel reads. If that is not critical to the implementation, reimplementing this function in a subclass can be ignored.
If load_parallel is set to all or common`, this function is executed by all nodes, otherwise the master node executes this function and broadcasts the results to other nodes.
- Returns
weight2d – A two-dimensional array with a shape compatible to the raw diffraction data frames
- Return type
ndarray
Note
For now, weights will be converted to a mask,
mask = weight2d > 0
for use in reconstruction algorithms. It is planned to use a general weight instead of a mask in future releases.
ptypy.core.geometry module¶
Geometry manager.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- class ptypy.core.geometry.BasicFarfieldPropagator(geo_pars=None, ffttype='scipy', **kwargs)¶
Bases:
object
Basic single step Farfield Propagator.
Includes quadratic phase factors and arbitrary origin in array.
Be aware though, that if the origin is not in the center of the frame, coordinates are rolled periodically, just like in the conventional fft case.
- Parameters
geo_pars (Param or dict) – Parameter dictionary as in
DEFAULT
.ffttype (str or tuple) –
Type of FFT implementation. One of:
’fftw’ for pyFFTW
’numpy’ for numpy.fft.fft2
’scipy’ for scipy.fft.fft2
2 or 4-tuple of (forward_fft2(), inverse_fft2(), [scaling, inverse_scaling])
- bw(W)¶
Computes backward propagated wavefront of input wavefront W.
- fw(W)¶
Computes forward propagated wavefront of input wavefront W.
- update(geo_pars=None, **kwargs)¶
Update internal p dictionary. Recompute all internal array buffers.
- class ptypy.core.geometry.BasicNearfieldPropagator(geo_pars=None, ffttype='scipy', **kwargs)¶
Bases:
object
Basic two step (i.e. two ffts) Nearfield Propagator.
- Parameters
geo_pars (Param or dict) – Parameter dictionary as in
DEFAULT
.ffttype (str or tuple) –
Type of FFT implementation. One of:
’fftw’ for pyFFTW
’numpy’ for numpy.fft.fft2
’scipy’ for scipy.fft.fft2
2 or 4-tuple of (forward_fft2(),inverse_fft2(), [scaling,inverse_scaling])
- bw(W)¶
Computes backward propagated wavefront of input wavefront W.
- fw(W)¶
Computes forward propagated wavefront of input wavefront W.
- update(geo_pars=None, **kwargs)¶
Update internal p dictionary. Recompute all internal array buffers.
- class ptypy.core.geometry.Geo(owner=None, ID=None, pars=None, **kwargs)¶
Bases:
ptypy.core.classes.Base
Hold and keep consistent the information about experimental parameters.
Keeps also reference to the Propagator and updates this reference when resolution, pixel size, etc. is changed in Geo. Reference to
io.paths.recons
.- Variables
interact (bool (True)) – If set to True, changes to properties like
energy()
,lam()
,shape()
orpsize()
will cause a call toupdate()
.
Default geometry parameters. See also
scan.geometry
- Parameters
owner (Base or subclass) – Instance of a subclass of
Base
or None. That is usuallyPtycho
for a Geo instance.ID (str or int) – Identifier. Use
ID=None
for automatic ID assignment.pars (dict or Param) – The configuration parameters. See Geo.DEFAULT. Any other kwarg will update internal p dictionary if the key exists in Geo.DEFAULT.
- DEFAULT = {'center': 'fftshift', 'distance': 7.19, 'energy': 6.2, 'ffttype': 'scipy', 'lam': None, 'misfit': 0.0, 'origin': 'fftshift', 'propagation': 'farfield', 'psize': 0.000172, 'resolution': None, 'shape': 256}¶
- ID¶
- property distance¶
Propagation distance in meters (read-only)
- downsample(a)¶
Downsample the array a (float)
- property energy¶
Get or set the energy (in keV). If self.interact is True, recompute dependent quantities accordingly.
- property lam¶
Get or set the wavelength (in meters).
If self.interact is True, recompute dependent quantities accordingly. Changing wavelengths never changes the image extent (self.sh).
- property lz¶
Product of wavelength and propagation distance (read-only)
- numID¶
- owner¶
- property propagator¶
Propagator, created on-the-fly if needed (read-only)
- property psize¶
Get or set the pixel size in the propagated plane (in meters).
If self.interact is True, recompute dependent quantities accordingly.
- property resolution¶
Get or set the pixel size in the image plane (in meters).
If self.interact is True, recompute dependent quantities accordingly.
- property shape¶
Get or set the frame dimensions.
If self.interact is True, recompute dependent quantities accordingly.
- update(update_propagator=True)¶
Update the internal pixel sizes, giving precedence to the sample pixel size (resolution) if self.psize_is_fixed is True.
- upsample(c)¶
Upsample the array c (float or complex).
ptypy.core.illumination module¶
This module generates the probe.
@author: Bjoern Enders
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- ptypy.core.illumination.aperture(A, grids=None, pars=None, **kwargs)¶
Creates an aperture in the shape and dtype of A according to x,y-grids grids. Keyword Arguments may be any of (FIXME link to kwargs)
- Parameters
A (ndarray) – Model array (at least 2-dimensional) to place aperture on top.
pars (dict or Param) – Parameters, FIXME link to parameters
grids (ndarray) – Cartesian coordinate grids, if None, they will be created with
grids = u.grids(sh[-2:], psize=(1.0, 1.0))
- Returns
ap – Aperture array (complex) in shape of A
- Return type
ndarray
- ptypy.core.illumination.init_storage(storage, pars, energy=None, **kwargs)¶
Initializes
Storage
storage with parameters from pars- Parameters
storage (Storage) – A
Storage
instance in the probe container ofPtycho
pars (Param) –
Parameter structure for creating a probe / illumination. See
DEFAULT
Also accepted as argument:string giving the filename of a previous reconstruction to extract storage from.
string giving the name of an available TEMPLATE
FIXME: document other string cases.
numpy array: interpreted as initial illumination.
energy (float, optional) – Energy associated with this storage. If None, tries to retrieve the energy from the already initialized ptypy network.
ptypy.core.manager module¶
Scan management.
The main task of this module is to prepare the data structure for reconstruction, taking a data feed and connecting individual diffraction measurements to the other containers. The way this connection is done as defined by ScanModel and its subclasses. The connections are described by the POD objects.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- class ptypy.core.manager.BlockFull(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager._Full
,ptypy.core.manager.BlockScanModel
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'coherence': {'energies': [1.0], 'num_object_modes': 1, 'num_probe_modes': 1, 'object_dispersion': None, 'probe_dispersion': None, 'spectrum': [1.0]}, 'ffttype': 'scipy', 'illumination': {}, 'name': 'Full', 'propagation': 'farfield', 'resample': 1, 'resolution': None, 'sample': {}, 'tags': ['dummy']}¶
- class ptypy.core.manager.BlockOPRModel(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager._OPRModel
,ptypy.core.manager.BlockFull
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'coherence': {'energies': [1.0], 'num_object_modes': 1, 'num_probe_modes': 1, 'object_dispersion': None, 'probe_dispersion': None, 'spectrum': [1.0]}, 'ffttype': 'scipy', 'illumination': {}, 'name': 'Full', 'propagation': 'farfield', 'resample': 1, 'resolution': None, 'sample': {}, 'tags': ['dummy']}¶
- class ptypy.core.manager.BlockScanModel(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager.ScanModel
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'ffttype': 'scipy', 'illumination': {}, 'propagation': 'farfield', 'resample': 1, 'sample': {}, 'tags': ['dummy']}¶
- new_data(max_frames)¶
Feed data from ptyscan object. :return: None if no data is available, Diffraction storage otherwise.
- class ptypy.core.manager.BlockVanilla(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager._Vanilla
,ptypy.core.manager.BlockScanModel
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'ffttype': 'scipy', 'illumination': {'size': None}, 'name': 'Vanilla', 'propagation': 'farfield', 'resample': 1, 'sample': {'fill': 1}, 'tags': ['dummy']}¶
- class ptypy.core.manager.Bragg3dModel(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager.Vanilla
Model for 3D Bragg ptycho data, where a set of rocking angles are measured for each scanning position. The result is pods carrying 3D diffraction patterns and 3D Views into a 3D object.
Inherits from Vanilla because _create_pods and the object init is identical.
Frames for each position are assembled according to the actual xyz data, so it will not work if two acquisitions are done at the same position.
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'ffttype': 'scipy', 'illumination': {'aperture': {'central_stop': None, 'diffuser': None, 'edge': 2.0, 'form': 'circ', 'offset': 0.0, 'rotate': 0.0, 'size': None}, 'model': None, 'photons': None, 'propagation': {'antialiasing': 1, 'focussed': None, 'parallel': None, 'spot_size': None}, 'recon': {'label': None, 'rfile': '\\*.ptyr'}, 'size': None}, 'name': 'Bragg3dModel', 'propagation': 'farfield', 'resample': 1, 'sample': {'fill': 1}, 'tags': ['dummy']}¶
- class ptypy.core.manager.Full(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager._Full
,ptypy.core.manager.ScanModel
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'coherence': {'energies': [1.0], 'num_object_modes': 1, 'num_probe_modes': 1, 'object_dispersion': None, 'probe_dispersion': None, 'spectrum': [1.0]}, 'ffttype': 'scipy', 'illumination': {'aperture': {'central_stop': None, 'diffuser': None, 'edge': 2.0, 'form': 'circ', 'offset': 0.0, 'rotate': 0.0, 'size': None}, 'diversity': {'noise': (0.5, 1.0), 'power': 0.1, 'shift': None}, 'model': None, 'photons': None, 'propagation': {'antialiasing': 1, 'focussed': None, 'parallel': None, 'spot_size': None}, 'recon': {'label': None, 'rfile': '\\*.ptyr'}}, 'name': 'Full', 'propagation': 'farfield', 'resample': 1, 'resolution': None, 'sample': {'diversity': {'noise': None, 'power': 0.1, 'shift': None}, 'fill': 1, 'model': None, 'process': {'density': 1, 'formula': None, 'offset': (0, 0), 'ref_index': (0.5, 0.0), 'smoothing': 2, 'thickness': 1e-06, 'zoom': None}, 'recon': {'rfile': '\\*.ptyr'}, 'stxm': {'label': None}}, 'tags': ['dummy']}¶
- class ptypy.core.manager.ModelManager(ptycho, pars)¶
Bases:
object
Thin wrapper class which now just interfaces Ptycho with ScanModel. This should probably all be done directly in Ptycho.
- Parameters
- property data_available¶
- property end_of_scan¶
- new_data()¶
Get all new diffraction patterns and create all views and pods accordingly.s
- class ptypy.core.manager.OPRModel(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager._OPRModel
,ptypy.core.manager.Full
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'coherence': {'energies': [1.0], 'num_object_modes': 1, 'num_probe_modes': 1, 'object_dispersion': None, 'probe_dispersion': None, 'spectrum': [1.0]}, 'ffttype': 'scipy', 'illumination': {}, 'name': 'Full', 'propagation': 'farfield', 'resample': 1, 'resolution': None, 'sample': {}, 'tags': ['dummy']}¶
- class ptypy.core.manager.ScanModel(ptycho=None, pars=None, label=None)¶
Bases:
object
Abstract base class for models. Override at least these methods: _create_pods(self) _initialize_geo(self, common) _initialize_probe(self, probe_ids) _initialize_object(self, object_ids)
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'ffttype': 'scipy', 'illumination': {}, 'propagation': 'farfield', 'resample': 1, 'sample': {}, 'tags': ['dummy']}¶
- classmethod makePtyScan(pars)¶
Factory for PtyScan object. Return an instance of the appropriate PtyScan subclass based on the input parameters.
- Parameters
pars (dict or Param) – Input parameters according to
scan.data
.
- new_data(max_frames)¶
Feed data from ptyscan object. :return: None if no data is available, True otherwise.
- class ptypy.core.manager.Vanilla(ptycho=None, pars=None, label=None)¶
Bases:
ptypy.core.manager._Vanilla
,ptypy.core.manager.ScanModel
Create scan model object.
- Parameters
pars (dict or Param) – Input parameter tree.
ptycho (Ptycho instance) – Ptycho instance to which this scan belongs
label (str) – Unique label
- DEFAULT = {'ffttype': 'scipy', 'illumination': {'size': None}, 'name': 'Vanilla', 'propagation': 'farfield', 'resample': 1, 'sample': {'fill': 1}, 'tags': ['dummy']}¶
ptypy.core.paths module¶
Path manager.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- ptypy.core.paths.DEFAULT = {'autoplot': 'plots/%(run)s/%(run)s_%(engine)s_%(iteration)04d.png', 'autosave': 'dumps/%(run)s/%(run)s_%(engine)s_%(iteration)04d.ptyr', 'home': './', 'recon': 'recons/%(run)s/%(run)s_%(engine)s.ptyr'}¶
Default path parameters. See
io.paths
and a short listing below
- class ptypy.core.paths.Paths(io=None)¶
Bases:
object
Path managing class
- DEFAULT = {'autoplot': 'plots/%(run)s/%(run)s_%(engine)s_%(iteration)04d.png', 'autosave': 'dumps/%(run)s/%(run)s_%(engine)s_%(iteration)04d.ptyr', 'home': './', 'recon': 'recons/%(run)s/%(run)s_%(engine)s.ptyr'}¶
- auto_file(runtime=None)¶
File path for autosave file
- get_path(path, runtime)¶
- plot_file(runtime=None)¶
File path for plot file
- recon_file(runtime=None)¶
File path for reconstruction file
- run(run)¶
Determine run name
ptypy.core.ptycho module¶
ptycho - definition of the upper-level class Ptycho.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- class ptypy.core.ptycho.Ptycho(pars=None, level=2, **kwargs)¶
Bases:
ptypy.core.classes.Base
Ptycho : A ptychographic data holder and reconstruction manager.
This is the highest level class. It organizes and contains the data, manages the reconstruction engines, and interacts with the outside world.
If MPI is enabled, this class acts both as a manager (rank = 0) and a worker (any rank), and most information exists on all processes. In its original design, the only part that is divided between processes is the diffraction data.
By default Ptycho is instantiated once per process, but it can also be used as a managed container to load past runs.
- Variables
CType,FType (numpy.dtype) – numpy dtype for arrays. FType is for data, i.e. real-valued arrays, CType is for complex-valued arrays
interactor (ptypy.io.interaction.Server) – ZeroMQ interaction server for communication with e.g. plotting clients
runtime (Param) – Runtime information, e.g. errors, iteration etc.
~Ptycho.model (ModelManager) – THE managing instance for
POD
,View
andGeo
instances~Ptycho.obj,~Ptycho.exit,~Ptycho.diff,~Ptycho.mask (probe,) – Container instances for illuminations, samples, exit waves, diffraction data and detector masks / weights
- Parameters
pars (Param) – Input parameters, subset of the ptypy parameter tree
level (int) –
Determines how much is initialized.
<= 0 : empty ptypy structure
- 1reads parameters, configures interaction server,
- 2also configures Containers, initializes ModelManager
see
init_data()
- 3also initializes ZeroMQ-communication
- 4also initializes reconstruction engines,
see
init_engine()
- >= 4also and starts reconstruction
see
run()
- DEFAULT = {'data_type': 'single', 'dry_run': False, 'engines': {}, 'frames_per_block': 100000, 'io': {'autoplot': {'active': True, 'dump': False, 'imfile': 'plots/%(run)s/%(run)s_%(engine)s_%(iterations)04d.png', 'interval': 1, 'layout': 'default', 'make_movie': False, 'threaded': True}, 'autosave': {'active': True, 'interval': 10, 'rfile': 'dumps/%(run)s/%(run)s_%(engine)s_%(iterations)04d.ptyr'}, 'benchmark': None, 'home': './', 'interaction': {'active': True, 'client': {'address': 'tcp://127.0.0.1', 'connection_timeout': 3600000.0, 'pinginterval': 1, 'poll_timeout': 100.0, 'port': 5560}, 'server': {'active': True, 'address': 'tcp://127.0.0.1', 'connections': 10, 'pinginterval': 2, 'pingtimeout': 10, 'poll_timeout': 10.0, 'port': 5560}}, 'rfile': 'recons/%(run)s/%(run)s_%(engine)s_%(iterations)04d.ptyr', 'rformat': 'minimal'}, 'ipython_kernel': False, 'min_frames_for_recon': 0, 'run': None, 'scans': {}, 'verbose_level': 'ERROR'}¶
- ID¶
- copy_state(name='baseline', overwrite=False)¶
Store a copy of the current state of object/probe and exit
Warning: This feature is under development and syntax might change!
- finalize()¶
Cleanup
- init_communication()¶
Called on __init__ if
level >= 3
.Initializes ZeroMQ communication on the master node and spawns an optional plotting client.
- init_data(print_stats=True)¶
Called on __init__ if
level >= 2
.Call
ModelManager.new_data()
Prints statistics on the ptypy structure ifprint_stats=True
- init_engine(label=None, epars=None)¶
Called on __init__ if
level >= 4
.Initializes engine with label label from parameters and lists it internally in
self.engines
which is an ordered dictionary.- Parameters
label (str) – Label of engine which is to be created from parameter set of the same label in input parameter tree. If
None
, an engine is created for each available parameter set in input parameter tree sorted by label.epars (Param or dict) – Set of engine parameters. The created engine is listed as auto00, auto01 , etc in
self.engines
- init_structures()¶
Called on __init__ if
level >= 1
.Prepare everything for reconstruction. Creates attributes
model
and the containersprobe
for illumination,obj
for the samples,exit
for the exit waves,diff
for diffraction data andPtycho.mask
for detectors masks
- classmethod load_run(runfile, load_data=True)¶
Load a previous run.
- Parameters
runfile (str) – file dump of Ptycho class
load_data (bool) – If True also load data (thus regenerating pods & views for ‘minimal’ dump
- Returns
P – Ptycho instance with
level == 2
- Return type
- numID¶
- owner¶
- plot_overview(fignum=100)¶
plots whole the first four layers of every storage in probe, object % diff
- print_stats(table_format=None, detail='summary')¶
Calculates the memory usage and other info of ptycho instance
- restore_state(name='baseline', reformat_exit=True)¶
Restore object/probe based on a previously saved copy The exit buffer can be reformatted or loaded from the state
Warning: This feature is under development and syntax might change!
- run(label=None, epars=None, engine=None)¶
Called on __init__ if
level >= 5
.Start the reconstruction with at least one engine. As a consequence,
self.runtime
will be filled with content.- Parameters
label (str, optional) – Engine label of engine to run. If
None
all available engines are run in the order they were stored inself.engines
. If the engine is not yet created,init_engine()
is called for that label.epars (dict or Param, optional) – Engine parameter set. An engine is created from this set, using
init_engine()
and run immediately afterwards. For parameters seeengine
engine (BaseEngine, optional) – An engine instance that should be a subclass of
BaseEngine
or have the same methods.
- save_run(alt_file=None, kind='minimal', force_overwrite=True)¶
Save run to file.
As for now, diffraction / mask data is not stored
- Parameters
alt_file (str) – Alternative filepath, will override io.save_file
kind (str) –
Type of saving, one of:
’minimal’, only initial parameters, probe and object storages, positions and runtime information is saved.
’full_flat’, (almost) complete environment
ptypy.core.sample module¶
This module generates a sample.
@author: Bjoern Enders
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- ptypy.core.sample.init_storage(storage, sample_pars=None, energy=None)¶
Initializes a storage as sample transmission.
- Parameters
sample_pars (Param) – Parameter structure that defines how the sample is created. FIXME Link to parameters
energy (float, optional) – Energy associated in the experiment for this sample object. If None, the ptypy structure is searched for the appropriate
Geo
instance:storage.views[0].pod.geometry.energy
ptypy.core.save_load module¶
- ptypy.core.save_load.from_h5(filename)¶
- ptypy.core.save_load.link(pool, replace_objects_only=False, preserve_input_pool=True)¶
Reverse operation to unlink.
- ptypy.core.save_load.to_h5(filename, obj)¶
- ptypy.core.save_load.unlink(obj)¶
Looks into all references of obj. Places references in a pool with string labels resembling their python ID plus an object dependent prefix. Reduces all objects and dicts to dictionaries. Reduces all tuples to list. All references are replaced by the labels in the pool.
Original references in ‘obj’ are preserved
ptypy.core.xy module¶
This module generates the scan patterns.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.
- ptypy.core.xy.from_pars(xypars=None)¶
Creates position array from parameter tree pars. See
DEFAULT
- Parameters
xypars – TreeDict Input parameters
- Returns
ndarray pos A numpy.ndarray of shape
(N,2)
for N positions
- ptypy.core.xy.raster_scan(dy=1.5e-06, dx=1.5e-06, ny=10, nx=10, ang=0.0)¶
Generates a raster scan.
- Parameters
ny (int) – Number of steps in y (vertical) and x (horizontal) direction x is the fast axis
nx (int) – Number of steps in y (vertical) and x (horizontal) direction x is the fast axis
dy (float) – Step size (grid spacing) in y and x
dx (float) – Step size (grid spacing) in y and x
ang (float) – Rotation angle of the raster grid (counterclockwise, in degrees)
- Returns
pos – A (N,2)-array of positions. It is
N = (nx+1)*(nx+1)
- Return type
ndarray
Examples
>>> from ptypy.core import xy >>> from matplotlib import pyplot as plt >>> pos = xy.raster_scan() >>> plt.plot(pos[:, 1], pos[:, 0], 'o-'); plt.show()
- ptypy.core.xy.round_scan(dr=1.5e-06, nr=5, nth=5, bullseye=True)¶
Generates a round scan
- Parameters
nr (int) – Number of radial steps from center,
nr + 1
shells will be madedr (float) – Step size (shell spacing)
nth (int, optional) – Number of points in first shell
bullseye (bool) – If set false, point of origin will be ignored
- Returns
pos – A (N,2)-array of positions.
- Return type
ndarray
Examples
>>> from ptypy.core import xy >>> from matplotlib import pyplot as plt >>> pos = xy.round_scan() >>> plt.plot(pos[:,1], pos[:,0], 'o-'); plt.show()
- ptypy.core.xy.spiral_scan(dr=1.5e-06, r=7.5e-06, maxpts=None)¶
Generates a spiral scan.
- Parameters
r (float) – Number of radial steps from center,
nr + 1
shells will be madedr (float) – Step size (shell spacing)
nth (int, optional) – Number of points in first shell
- Returns
pos – A (N,2)-array of positions. It is
- Return type
ndarray
Examples
>>> from ptypy.core import xy >>> from matplotlib import pyplot as plt >>> pos = xy.spiral_scan() >>> plt.plot(pos[:, 1], pos[:, 0], 'o-'); plt.show()
Module contents¶
Core functionalities of the package.
This file is part of the PTYPY package.
- copyright
Copyright 2014 by the PTYPY team, see AUTHORS.
- license
see LICENSE for details.