cellpack.autopack package

Subpackages

Submodules

cellpack.autopack.AWSHandler module

class cellpack.autopack.AWSHandler.AWSHandler(bucket_name, sub_folder_name=None, region_name=None)[source]

Bases: object

Handles all the AWS S3 operations

create_presigned_url(object_name, expiration=3600)[source]

Generate a presigned URL to share an S3 object :param object_name: string :param expiration: Time in seconds for the presigned URL to remain valid :return: Presigned URL as string. If error, returns None.

download_file(key, local_file_path)[source]

Download a file from S3 :param key: S3 object key :param local_file_path: Local file path to save the downloaded file

get_aws_object_key(object_name)[source]
is_url_valid(url)[source]

Validate the url’s scheme, bucket name, and query parameters, etc.

save_file_and_get_url(file_path)[source]

Uploads a file to S3 and returns the base url

upload_file(file_path)[source]

Upload a file to an S3 bucket :param file_path: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_path is used :return: True if file was uploaded, else False

cellpack.autopack.Analysis module

Created on Mon May 6 22:58:44 2013

@author: ludo

class cellpack.autopack.Analysis.Analysis(env=None, packing_results_path=None, output_path=None)[source]

Bases: object

add_ingredient_positions_to_plot(ax, ingr, color, seed_index, ingredient_position_dict, width)[source]

Adds 2D images of ingredient positions to axis

build_grid()[source]
static cartesian_to_sph(xyz, center=None)[source]

Converts cartesian to spherical coordinates

combine_results_from_ingredients(input_dict)[source]

Combines results from multiple ingredients into one list

combine_results_from_seeds(input_dict)[source]

Combines results from multiple seeds into one dictionary Dictionary keys are ingredient names

create_report(recipe_data, ingredient_keys=None, report_output_path=None, output_image_location=None, run_distance_analysis=True, run_partner_analysis=True)[source]

Creates a markdown file with various analyses included

Parameters:
  • self (AnalyseAP) – instance of AnalyseAP class

  • recipe_data (dict) – dictionary containing recipe data for the packing being analyzed

  • ingredient_keys (List[str]) – list of ingredient keys to analyze

  • output_image_location (Path) – this is the path to look for output images for the markdown file

  • run_*_analysis (bool) – whether to run specific analysis

doloop(recipe_data, packing_config_data, bounding_box, get_distance_distribution=True)[source]

Runs multiple packings of the same recipe in a loop. This workflow also runs various analyses and saves the output figures and data at the location set by the environment. The output data is also stored as an attribute on the environment object and on the Analysis class instance.

Parameters:
  • recipe_data (dict) – Dictionary containing recipe data

  • packing_config_data (dict) – Dictionary containing packing configuration data

  • bounding_box (list) – List of two lists containing the minimum and maximum coordinates of the bounding box

  • get_distance_distribution (bool) – Whether to calculate and store distance and angle distributions

  • seed_list (list) – List of seeds to use for packings

  • Outputs

  • ——-

  • {}_distance_dict (dict) – Dictionaries with various ingredient distances stored

  • images (png) – packing image, histograms of distance, angle, and occurence distributions as applicable for each seed, and a combined image across seeds

getHaltonUnique(n)[source]
get_ingredient_key_from_object_or_comp_name(search_name, ingredient_key_dict)[source]

Returns the ingredient key if object or composition name is given

get_ingredient_radii(recipe_data)[source]

Returns the radii of ingredients packed

Parameters:

ingredient_key (str) – ingredient key in self.all_pos_list

static get_list_of_dims()[source]
get_minimum_expected_distance_from_recipe(recipe_data)[source]

Returns 2x the smallest radius of objects in the recipe

get_number_of_ingredients_packed(ingredient_keys=None)[source]

Returns the number of ingredients packed

Parameters:

ingredient_key (str) – ingredient key in self.all_pos_list

get_obj_dict(packing_results_path)[source]

Returns the object dictionary from the input path folder.

Args:

packing_results_path (str): The path to the folder containing the packing results.

Returns:

tuple: A tuple containing the object dictionary and the list of all positions.

get_packed_minimum_distance(pairwise_distance_dict)[source]

Returns the minimum distance between packed objects

get_partner_pair_dict(recipe_data, combined_pairwise_distance_dict, ingredient_radii, avg_num_packed)[source]

Creates a partner pair dictionary as follows: {

key_from_pairwise_distance_dict: {

“binding_probability”: value, “touching_radius”: value,

}

histogram(distances, filename, title_str='', x_label='', y_label='', add_to_result=True, save_png=False)[source]
loadJSON(filename)[source]
pack(seed=20, show_plotly_plot=True, **kwargs)[source]
pack_one_seed(seed_index, seed_list, bounding_box, center_distance_dict=None, pairwise_distance_dict=None, ingredient_position_dict=None, ingredient_angle_dict=None, ingredient_occurence_dict=None, ingredient_key_dict=None, get_distance_distribution=False, image_export_options=None, show_grid=False, plot_figures=False, save_gradient_data_as_image=False, clean_grid_cache=False)[source]

Packs one seed of a recipe and returns the recipe object

plot(rdf, radii, file_name)[source]
plot_distance_distribution(all_ingredient_distances)[source]

Plots the distribution of distances for ingredient and pairs of ingredients

plot_occurence_distribution(ingr)[source]
plot_position_distribution(ingr)[source]
plot_position_distribution_total(all_positions)[source]
process_ingredients_in_recipe(recipe, center_distance_dict, pairwise_distance_dict, ingredient_position_dict, ingredient_angle_dict, ingredient_occurence_dict, ingredient_key_dict, seed_index, center, ax, plot_figures, two_d, width)[source]

Updates distance/angle dictionaries and creates plots for ingredients in recipe

read_dict_from_glob_file(glob_str)[source]
run_analysis_workflow(analysis_config: dict, recipe_data: dict)[source]
run_distance_analysis(md_object: MarkdownWriter, recipe_data, pairwise_distance_dict, figure_path, output_image_location)[source]

Runs distance analysis on the given packing and adds it to the analysis report

run_partner_analysis(md_object: MarkdownWriter, recipe_data, combined_pairwise_distance_dict, ingredient_radii, avg_num_packed)[source]

runs an analysis of partner packings

set_ingredient_color(ingr)[source]

Sets the color of an ingredient

simpleplot(X, Y, filename, w=3, title_str='', x_label='', y_label='')[source]
update_distance_distribution_dictionaries(ingr, center_distance_dict, pairwise_distance_dict, ingredient_position_dict, ingredient_angle_dict, ingredient_occurence_dict, seed_index, center)[source]

Update dictionaries that store distance and angle information

update_pairwise_distances(ingr, recipe, pairwise_distance_dict, seed_index)[source]

Adds cross-ingredient distances for pairwise distance dictionary

writeJSON(filename, data)[source]

cellpack.autopack.BaseGrid module

# autoPACK Authors: Graham T. Johnson, Mostafa Al-Alusi, Ludovic Autin, Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # BaseGrid.py Authors: Graham Johnson & Michel Sanner with editing/enhancement from Ludovic Autin # # Translation to Python initiated March 1, 2010 by Michel Sanner with Graham Johnson # # Class restructuring and organization: Michel Sanner # # Copyright: Graham Johnson ©2010 # # This file “BaseGrid.py” is part of autoPACK, cellPACK. # # autoPACK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # autoPACK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autoPACK (See “CopyingGNUGPL” in the installation. # If not, see <http://www.gnu.org/licenses/>. # # ############################################################################### @author: Ludovic Autin, Graham Johnson, & Michel Sanner

class cellpack.autopack.BaseGrid.BaseGrid(boundingBox=([0, 0, 0], [0.1, 0.1, 0.1]), spacing=20, setup=True)[source]

Bases: object

The Grid class

This class handle the use of grid to control the packing. The grid keep information of 3d positions, distances, free_points and inside/surface points from organelles. NOTE : thi class could be completely replace if openvdb is wrapped to python.

cartesian(arrays, out=None)[source]

#http://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays Generate a cartesian product of input arrays.

Parameters:
  • arrays (list of array-like) – 1-D arrays to form the cartesian product of.

  • out (ndarray) – Array to place the cartesian product in.

Returns:

out – 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays.

Return type:

ndarray

Examples

>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
       [1, 4, 7],
       [1, 5, 6],
       [1, 5, 7],
       [2, 4, 6],
       [2, 4, 7],
       [2, 5, 6],
       [2, 5, 7],
       [3, 4, 6],
       [3, 4, 7],
       [3, 5, 6],
       [3, 5, 7]])
computeExteriorVolume(compartments=None, space=None, fbox_bb=None)[source]
computeGridNumberOfPoint(boundingBox, space)[source]

Return the grid size : total number of point and number of point per axes

computeVolume(space=None, fbox_bb=None)[source]
create_grid_point_positions(boundingBox=None)[source]

Fill the orthogonal bounding box described by two global corners with an array of points spaces pGridSpacing apart. Optimized version using numpy broadcasting

getCenter()[source]

Get the center of the grid

getClosestFreeGridPoint(pt3d, compId=None, updateTree=True, ball=0.0, distance=0.0)[source]
getClosestGridPoint(pt3d)[source]
getDiagonal(boundingBox=None)[source]
getIJK(ptInd)[source]

get i,j,k (3d) indices from u (1d) only work for grid point, not compartments points

getPointFrom3D(pt3d)[source]

get point number from 3d coordinates

getPointsInCube(bb, pt, radius, addSP=True, info=False)[source]

Return all grid points indicesinside the given bounding box.

getPointsInCubeFillBB(bb, pt, radius, addSP=True, info=False)[source]

Return all grid points indices inside the given bounding box. NOTE : need to fix with grid build with numpy arrange

getPointsInSphere(pt, radius)[source]
getPositionPeridocity(pt3d, jitter, cutoff)[source]
getRadius()[source]

Get the radius the grid

is_point_inside_bb(pt3d, dist=None, jitter=[1, 1, 1], bb=None)[source]

Check if the given 3d points is inside the grid

removeFreePoint(pti)[source]
static reorder_free_points(pt, free_points, nbFreePoints)[source]
reset()[source]
restore()[source]
save()[source]
set_surfPtsBht(verts)[source]
set_surfPtscht(verts)[source]
setup(boundingBox)[source]
setupBoundaryPeriodicity()[source]
slow_box_fill(boundingBox=None)[source]

Fill the orthogonal bounding box described by two global corners with an array of points spaces pGridSpacing apart.:

test_points_in_bb(bb, pt)[source]
static updateDistances(insidePoints, newDistPoints, free_points, nbFreePoints, distance)[source]
class cellpack.autopack.BaseGrid.HaltonGrid(boundingBox=([0, 0, 0], [0.1, 0.1, 0.1]), space=1, setup=False)[source]

Bases: BaseGrid

create3DPointLookup(boundingBox=None)[source]
getNBgridPoints()[source]
getPointFrom3D(pt3d)[source]

get point number from 3d coordinates

getScale(boundingBox=None)[source]
class cellpack.autopack.BaseGrid.gridPoint(i, globalC, isPolyhedron)[source]

Bases: object

cellpack.autopack.Compartment module

class cellpack.autopack.Compartment.Compartment(name, object_info)[source]

Bases: CompartmentList

The Compartment class

This class represents a sub volume delimited by a polyhedral surface. Compartment can be nested

BuildGrid(env, mesh_store=None)[source]
BuildGridEnviroOnly(env, location=None)[source]

Build the compartment grid ie surface and inside only environment

BuildGrid_bhtree(env, ctree, grdPos, new_distances, diag, vSurfaceArea, srfPts, idarray, distances)[source]

Build the compartment grid ie surface and inside point

BuildGrid_binvox(env, grdPos, vSurfaceArea, srfPts, idarray, ray=1)[source]
BuildGrid_box(env, vSurfaceArea)[source]
BuildGrid_kevin(env, superFine=False)[source]

Build the compartment grid ie surface and inside point using flood filling algo from kevin

BuildGrid_multisdf(histoVol)[source]

Build the compartment grid ie surface and inside point using multisdf

BuildGrid_pyray(env, ctree, distances, grdPos, diag, vSurfaceArea, srfPts, idarray, ray=1)[source]
BuildGrid_ray(env, grdPos, vSurfaceArea, vertex_points, idarray, mesh_store)[source]

Build the compartment grid using pyembree raycast to find inside points, and then a cKDTree to find “missing” surface points, ie surface points that are in between vertex points

BuildGrid_scanline(env, grdPos, new_distances, vSurfaceArea, diag, srfPts, idarray, mesh_store)[source]

Build the compartment grid ie surface and inside point using scanline

BuildGrid_trimesh(env, master_grid_positions, vSurfaceArea, off_grid_surface_points, compartment_ids, mesh_store)[source]

Build the compartment grid ie surface and inside points

BuildGrid_utsdf(env)[source]

Build the compartment grid ie surface and inside point using signed distance fields from the UT package

buildMesh(data, mesh_store)[source]

Create a polygon mesh object from a dictionary verts,faces,normals

buildSphere(mesh_store)[source]
build_grid_sphere(env)[source]
checkPointInsideBB(pt3d, dist=None)[source]

check if the given 3d coordinate is inside the compartment bounding box

compute_volume_and_set_count(env, surfacePoints, insidePoints, areas=None)[source]

Compute volume of surface and interior set ‘count’ in each ingredient of both recipes

create3DPointLookup(nbGridPoints, gridSpacing, dim, boundingBox=None)[source]
Fill the orthogonal bounding box described by two global corners

with an array of points spaces pGridSpacing apart. Duplicate from grid class

createSurfacePoints(maxl=20)[source]

create points inside edges and faces with max distance between then maxl creates self.surfacePoints and self.surfacePointsNormals

create_rbnode()[source]
create_voxelization(image_data, bounding_box, voxel_size, image_size, position, **kwargs)[source]

Creates a voxelization mask at the position of the compartment

create_voxelized_mask(x_width, y_width, z_width, center, voxel_size, mesh_store, hollow=False)[source]

Creates a mask of the compartment voxelization

Parameters:
  • x_width – number of voxels in the x direction

  • y_width – number of voxels in the y direction

  • z_width – number of voxels in the z direction

  • center – center of the voxelization

  • voxel_size – size of the voxels

  • mesh_store – mesh store

  • hollow – if True, the mask will be hollow otherwise it will fill in the segmentation

extendGridArrays(nbGridPoints, off_grid_surface_pts, surfPtsBBNorms, env, surfacePointsNormals, extended=True)[source]

Extend the environment grd using the compartment point

filter_surface_pts_to_fill_box(off_grid_pos, env)[source]

get the bounding box from the environment grid that encapsulated the mesh

find_nearest(array, value)[source]

find nearest point indice of value in array using numpy

getBoundingBox()[source]

get the bounding box

getCenter()[source]

get the center of the mesh (vertices barycenter)

getFaceNormals(vertices, faces, fillBB=None)[source]

compute the face normal of the compartment mesh

getFacesNfromV(vindice, ext=0)[source]

Retrieve the face normal from the indice of a vertice

getInterpolatedNormal(pt, tri)[source]

compute an interpolated normal for te given triangle at the given point

getMesh(mesh_store)[source]

Retrieve the compartment 3d representation from the given filename

@type filename: string @param filename: the name of the input file @type rep: string @param rep: the name of the input file for the representation

getMinMaxProteinSize()[source]

retrieve minimum and maximum ingredient size for inner and surface recipe ingredients

getRadius()[source]

get the radius as the distance between vertices center and bottom left bounding box

getSizeXYZ()[source]

get the size per axe

getSurfaceInnerPoints(boundingBox, spacing, display=False, useFix=False)[source]

Only compute the inner point. No grid. This is independant from the packing. Help build ingredient sphere tree and representation

getSurfaceInnerPoints_kevin(boundingBox, spacing, display=False, superFine=False)[source]
Takes a polyhedron, and builds a grid. In this grid:
  • Projects the polyhedron to the grid.

  • Determines which points are inside/outside the polyhedron

  • Determines point’s distance to the polyhedron.

superFine provides the option doing a super leakproof test when determining which points are inside or outside. Instead of raycasting to nearby faces to determine inside/outside, setting this setting to true will foce the algorithm to raycast to the entire polyhedron. This usually not necessary, because the built-in algorithm has no known leakage cases, even in extreme edge cases. It is simply there as a safeguard.

getSurfaceInnerPoints_sdf(boundingBox, spacing, display=False, useFix=False)[source]

Only compute the inner point. No grid. This is independant from the packing. Help build ingredient sphere tree and representation

getSurfaceInnerPoints_sdf_interpolate(boundingBox, spacing, display=False, useFix=False)[source]

Only compute the inner point. No grid. This is independant from the packing. Help build ingredient sphere tree and representation

getSurfacePoint(p1, p2, w1, w2)[source]

compute point between p1 and p2 with weight w1 and w2

getVNfromF(i)[source]

Retrieve the vertice normal from the indice of a vertice

getVertexNormals(vertices, faces)[source]
get_bbox(vert_list, BB_SCALE=0.0)[source]

get bounding box for the given list of vertices

get_normal_for_point(pt, pos, mesh_store)[source]
get_rb_model()[source]
inBox(box, spacing)[source]

check if bounding box of this compartment fits inside the give box returns true or false and the extended bounding box if this compartment did not fit

inGrid(point, fillBB)[source]

check if bounding box of this compartment fits inside the give box returns true or false and the extended bounding box if this compartment did not fit

initialize_shape(mesh_store)[source]
is_point_inside_mesh(point, diag, mesh_store, ray=1)[source]
prepare_buildgrid_box(env)[source]
printFillInfo()[source]

print some info about the compartment and its recipe

readGridFromFile(f)[source]

read insidePoints and surfacePoints from file

reset()[source]

reset the inner compartment data, surface and inner points

saveGridToFile(f)[source]

Save insidePoints and surfacePoints to file

setCount()[source]
setGeomFaces(tris, face)[source]
setInnerRecipe(recipe)[source]

set the inner recipe that define the ingredient to pack inside

setMesh(filename=None, vertices=None, faces=None, vnormals=None, **kw)[source]

Set the 3d mesh from the given filename or the given mesh data (v,f,n)

@type filename: string @param filename: the name of the input file @type vertices: array @param vertices: mesh vertices or None @type faces: array @param faces: mesh faces or None @type vnormals: array @param vnormals: mesh vnormals or None

setNumber(num)[source]

set compartment uniq id

setSurfaceRecipe(recipe)[source]

set the inner recipe that define the ingredient to pack at the surface

set_surface_distances(env, master_grid_positions, calc_distance_between_surfaces=False)[source]
store_packed_object(env)[source]
transformMesh(pos, rotation)[source]
class cellpack.autopack.Compartment.CompartmentList[source]

Bases: object

The CompartmentList class

Handle a list of compartments.

static add_compartment(parent, compartment)[source]

add a new compartment to the list

cellpack.autopack.DBRecipeHandler module

class cellpack.autopack.DBRecipeHandler.CompositionDoc(name, object_key=None, count=None, regions=None, molarity=None, object=None)[source]

Bases: DataDoc

Declares required attributes for comps in the constructor, set default values. Handles the logic for comparing the local and db data to determine the uploading process.

DEFAULT_VALUES = {'count': None, 'molarity': None, 'object': None, 'regions': {}}
KEY_TO_DICT_MAPPING = {'gradient': 'gradients', 'inherit': 'objects'}
SHALLOW_MATCH = ['object', 'count', 'molarity']
as_dict()[source]
check_and_replace_references(objects_to_path_map, references_to_update, db)[source]

Within one recipe upload, we store the references for uploaded comps and objs. Checks if the object or comp is a reference in the nesting regions, and replaces it with the referenced db path.

static get_reference_data(key_or_dict, db)[source]

Returns the db data for a reference, and the key if it exists. Key –> the name of a composition Dict –> the object data

static get_reference_in_obj(downloaded_data, db)[source]
static gradient_list_to_dict(prep_recipe_data)[source]

Convert gradient list to dict for resolve_local_regions

static resolve_combined_gradient(key, obj_data, prep_data)[source]

When the gradients are combined, fetch and replace gradient data in a list. key –> the key in the object data that we want to modify its value obj_data –> the object data that contains the gradient list prep_data –> the data that contains the gradients (raw data or path) we want to fetch

resolve_db_regions(db_data, db)[source]

Recursively resolves the regions of a composition from db.

resolve_local_regions(local_data, recipe_data, db)[source]

Recursively resolves the regions of a composition from local data. Restructure the local data to match the db data.

resolve_object_data(object_data, prep_recipe_data)[source]

Resolve the object data from the local data.

should_write(db, recipe_data)[source]

Compares the resolved local composition to the resolved db composition. To determine whether the composition data already exists or if it needs to be written to the database.

static update_reference(db, composition_id, referring_comp_id, index, remove_comp_name, update_in_array=False)[source]

Update comp references in the recipe

class cellpack.autopack.DBRecipeHandler.DBMaintenance(db_handler)[source]

Bases: object

Handles the maintenance of the database.

cleanup_results()[source]

Check if the results in the database are expired and delete them if the linked object expired.

readme_url()[source]

Return the URL to the README file for the database setup section.

class cellpack.autopack.DBRecipeHandler.DBRecipeLoader(db_handler)[source]

Bases: object

Handles the logic for downloading and parsing the recipe data from the database.

static collect_and_sort_data(comp_data)[source]

Collect all object and gradient info from the downloaded composition data Return autopack object data dict and gradient data dict with name as key Return restructured composition dict with “composition” as key

collect_docs_by_id(collection, id)[source]
static compile_db_recipe_data(db_recipe_data, obj_dict, grad_dict, comp_dict)[source]

Compile recipe data from db recipe data into a ready-to-pack structure

prep_db_doc_for_download(db_doc)[source]

convert data from db and resolve references.

validate_input_recipe_path(path)[source]

Validates if the input path corresponds to a recipe path in the database. Format of a recipe path: firebase:recipes/[RECIPE-ID]

class cellpack.autopack.DBRecipeHandler.DBUploader(db_handler)[source]

Bases: object

Handles the uploading of data to the database.

static prep_data_for_db(data)[source]

Recursively convert data to a format that can be written to the database.

upload_collections(recipe_meta_data, recipe_data)[source]

Separate collections from recipe data and upload them to db

upload_compositions(compositions, recipe_to_save, recipe_data)[source]
upload_data(collection, data, id=None)[source]

If should_write is true, upload the data to the database

upload_gradients(gradients)[source]
upload_objects(objects)[source]
upload_recipe(recipe_meta_data, recipe_data)[source]

After all other collections are checked or uploaded, upload the recipe with references into db

upload_result_metadata(file_name, url)[source]

Upload the metadata of the result file to the database.

upload_single_object(obj_name, obj_data)[source]
class cellpack.autopack.DBRecipeHandler.DataDoc[source]

Bases: object

as_dict()[source]
static is_db_dict(item)[source]
static is_key(string_or_dict)[source]
static is_nested_list(item)[source]
static is_obj(comp_or_obj)[source]
should_write()[source]
class cellpack.autopack.DBRecipeHandler.GradientDoc(settings)[source]

Bases: DataDoc

should_write(db, grad_name)[source]
class cellpack.autopack.DBRecipeHandler.ObjectDoc(name, settings)[source]

Bases: DataDoc

as_dict()[source]
static convert_positions_in_representation(data)[source]
static convert_representation(doc, db)[source]

Get object doc from database, convert it back to the original text i.e. in object, convert lists back to tuples in representations/packing/positions

should_write(db)[source]
class cellpack.autopack.DBRecipeHandler.ResultDoc(db)[source]

Bases: object

handle_expired_results()[source]

Check if the results in the database are expired and delete them if the linked object expired.

validate_existence(url)[source]

Validate the existence of an S3 object by checking if the URL is accessible. Returns True if the URL is accessible.

cellpack.autopack.Environment module

# autoPACK Authors: Graham T. Johnson, Mostafa Al-Alusi, Ludovic Autin, Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # Environment.py Authors: Graham Johnson & Michel Sanner with editing/enhancement # from Ludovic Autin # HistoVol.py became Environment.py in the Spring of 2013 to generalize the terminology # away from biology # # Translation to Python initiated March 1, 2010 by Michel Sanner with Graham Johnson # # Class restructuring and organization: Michel Sanner # # Copyright: Graham Johnson ©2010 # # This file “Environment.py” is part of autoPACK, cellPACK. # # autoPACK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # autoPACK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autoPACK (See “CopyingGNUGPL” in the installation. # If not, see <http://www.gnu.org/licenses/>. # # ############################################################################### @author: Graham Johnson, Ludovic Autin, & Michel Sanner

# Hybrid version merged from Graham’s Sept 2011 and Ludo’s April 2012 # version on May 16, 2012 # Updated with final thesis HistoVol.py file from Sept 25, 2012 on July 5, 2012 # with correct analysis tools

# TODO: fix the save/restore grid

class cellpack.autopack.Environment.Environment(config=None, recipe=None)[source]

Bases: CompartmentList

The Environment class

This class is main class in autopack. The class handle all the setup, initialization and process of the packing. We use xml or python for the setup. A environments is made of :

a grid and the gradients if any a list of compartment and their recipes (surface and interior) a exterior recipe each recipe are made of a list of ingredients

BuildCompartmentsGrids()[source]

Build the compartments grid (interior and surface points) to be merged with the main grid

SetRBOptions(obj='moving', **kw)[source]

Change the rigid body options

SetSpringOptions(**kw)[source]

Change the spring options, mainly used by C4D.

addMeshRBOrganelle(o)[source]
addRB(ingr, trans, rotMat, rtype='single_sphere', static=False)[source]
add_seed_number_to_base_name(seed_number)[source]
applyStep(step)[source]
buildGrid(rebuild=True)[source]

The main build grid function. Setup the main grid and merge the compartment grid. The setup is de novo or using previously built grid or restored using given file.

build_compartment_grids()[source]
calc_pairwise_distances(ingr1name, ingr2name)[source]

Returns pairwise distances between ingredients of different types

callFunction(function, args=[], kw={})[source]

helper function to callback another function with the given arguments and keywords. Optionally time stamp it.

check_new_placement(new_position)[source]
clean_grid_cache(grid_file_name)[source]

Clean the grid cache

clear()[source]
clearRBingredient(ingr)[source]
collectResultPerIngredient()[source]
compartment_id_for_nearest_grid_point(point)[source]
classmethod convertPickleToText(resultfilename=None, norga=0)[source]
create_compartment(compartment_key, parent)[source]
create_ingredient(recipe, arguments)[source]
create_objects()[source]

Instantiate compartments and ingredients contained within the recipe data.

create_voxelization(image_writer)[source]

Update the image data for all molecules in the recipe by creating voxelized representations.

Parameters:

image_writer (ImageWriter) – The image writer to use for writing the voxelized representations.

Returns:

image_data – The updated image data.

Return type:

numpy.ndarray

delRB(node)[source]
distance_check_failed()[source]
classmethod dropOneIngr(pos, rot, ingrname, ingrcompNum, ptInd, rad=1.0)[source]
dropOneIngrJson(ingr, rdic)[source]
exportToBD_BOX(res_filename=None, output=None, bd_type='flex')[source]
exportToReaDDy()[source]
exportToTEM()[source]
exportToTEM_SIM(res_filename=None, output=None)[source]
extend_bounding_box_for_compartments(spacing)[source]
extractMeshComponent(obj)[source]

Require host helper. Return the v,f,n of the given object

finishWithWater(free_points=None, nbFreePoints=None)[source]
getActiveIng()[source]

Return all remaining active ingredients

getIngrFromNameInRecipe(name, r)[source]

Given an ingredient name and a recipe, retrieve the ingredient object instance

classmethod getOneIngr(line)[source]
getOneIngrJson(ingr, ingrdic)[source]
getPointToDrop(ingr, free_points, nbFreePoints, distance, spacing, compId, vRangeStart, vThreshStart)[source]

Decide next point to use for dropping a given ingredent. The picking can be random, based on closest distance, based on gradients, ordered. This function also update the available free point except when hack is on.

getRotTransRB(node)[source]
getSortedActiveIngredients(allIngredients)[source]

Sort the active ingredient according their pirority and radius. # first get the ones with a packing priority # Graham- This now works in concert with ingredient picking

# Graham here- In the new setup, priority is infinite with abs[priority] increasing (+) # An ingredients with (-) priority will pack from greatest abs[-priority] one at a time # to lease abs[-priority]… each ingredient will attempt to reach its molarity # before moving on to the next ingredient, and all (-) ingredients will try to # deposit before other ingredients are tested. # An ingredient with (+) priority will recieve a weighted value based on its abs[priority] # e.g. an ingredient with a priority=10 will be 10x more likely to be picked than # an ingredient with a priority=1. # An ingredient with the default priority=0 will recieve a weighted value based on its # complexity. (currently complexity = min_radius), thus a more ‘complex’ ingredient # will more likely try to pack before a less ‘complex’ ingredient. # IMPORTANT: the +priority list does not fully mix with the priority=0 list, but this # should be an option… currently, the priority=0 list is normalized against a range # up to the smallest +priority ingredient and appended to the (+) list # TODO: Add an option to allow + ingredients to be weighted by assigned priority AND complexity # Add an option to allow priority=0 ingredients to fit into the (+) ingredient list # rather than appending to the end. # Even better, add an option to set the max priority for the 0list and then plug the results # into the (+) ingredient list. # Get rid of the (-), 0, (+) system and recreate this as a new flag and a class function # so we can add multiple styles of sorting and weighting systems. # Make normalizedPriorities and thresholdPriorities members of Ingredient class to avoid # building these arrays.

getTotalNbObject(allIngredients, update_partner=False)[source]
get_all_distances(position=None)[source]
static get_attributes_to_update()[source]
get_bounding_box_limits()[source]

Returns the min and max limits for the bounding box

get_closest_ingredients(point, cutoff=10.0)[source]
get_compartment_object_by_name(compartment_name)[source]

Returns compartment object by name

get_distances(ingredient_name, center)[source]
get_distances_and_angles(ingredient_name, center, get_angles=False)[source]
get_dpad(compartment_id)[source]

Return the largest encapsulating_radius and use it for padding

get_ingredient_angles(ingredient_name, center, ingredient_positions)[source]
get_ingredient_by_name(name, compartment_id=None)[source]

Given an ingredient name and optionally the compartment number, retrieve the ingredient object instance

get_ingredients_in_tree(closest_ingredients)[source]
get_size_of_bounding_box()[source]
includeIngrRecipe(ingrname, include, rs)[source]

Include or Exclude the given ingredient from the given recipe. (similar to an active state toggle)

includeIngrRecipes(ingrname, include)[source]

Include or Exclude the given ingredient from the recipe. (similar to an active state toggle)

includeIngredientRecipe(ingr, include)[source]

lue Include or Exclude the given ingredient from the recipe. (similar to an active state toggle)

is_two_d()[source]
linkTraj()[source]
loadFreePoint(resultfilename)[source]
loadResult(resultfilename=None, restore_grid=True, backward=False, transpose=True)[source]
load_asJson(resultfilename=None)[source]
load_asTxt(resultfilename=None)[source]
loopThroughIngr(cb_function, kwargs=None)[source]

Helper function that loops through all ingredients of all recipes and applies the given callback function on each ingredients.

moveRBnode(node, trans, rotMat)[source]
onePrevIngredient(i, mingrs, distance, nbFreePoints, marray)[source]

Unused

pack_grid(seedNum=0, name=None, vTestid=3, **kw)[source]

## Fill the grid by picking an ingredient first and then ## find a suitable point using the ingredient’s placer object

pickIngredient(vThreshStart, verbose=0)[source]

Main function that decide the next ingredient the packing will try to drop. The picking is weighted or random

prep_molecules_for_save(distances, free_points, nbFreePoints)[source]
printFillInfo()[source]
readArraysFromFile(f)[source]

write self.compartment_ids and self.distToClosestSurf to file. (pickle)

removeOnePoint(pt, free_points, nbFreePoints)[source]
reportprogress(label=None, progress=None)[source]
reset()[source]

Reset everything to empty and not done

resetIngrRecip(recip)[source]

Reset all ingredient of the given recipe

resolve_gradient_data_objects(gradient_data)[source]

Resolves gradient data objects for some modes

restore(result, orgaresult, freePoint, tree=False)[source]
restoreFreePoints(freePoint)[source]
restoreGridFromFile(gridFileName)[source]

Read and setup the grid from the given filename. (pickle)

restore_grids_from_pickle(grid_file_path)[source]

Read and setup the grid from the given filename. (pickle)

restore_molecules_array(ingr)[source]
runBullet(ingr, simulationTimes, runTimeDisplay)[source]
saveGridLogsAsJson(gridFileOut)[source]

Save the current grid and the compartment grid information in a file. (pickle)

saveGridToFile(gridFileOut)[source]

Save the current grid and the compartment grid information in a file. (pickle)

save_grids_to_pickle(grid_file_path)[source]

Save the current grid and compartment grids to file. (pickle)

save_result(free_points, distances, all_objects, save_grid_logs=False, save_result_as_file=False)[source]
setExteriorRecipe(recipe)[source]

Set the exterior recipe with the given one. Create the weakref.

setGeomFaces(tris, face)[source]
setSeed(seedNum)[source]
set_gradient(gradient_data)[source]

create a grdaient assign weight to point listorganelle influenced listingredient influenced

set_partners_ingredient(ingr)[source]
set_result_file_name(seed_basename)[source]

Sets the result file name using the output folder path and a given seed basename

setupOctree()[source]
setupRBOptions()[source]

Set default value for rigid body options

sortIngredient(reset=False)[source]
store(resultfilename=None)[source]
store_asJson(resultfilename=None, indent=True)[source]
timeFunction(function, args, kw)[source]

Mesure the time for performing the provided function.

@type function: function @param function: the function to execute @type args: liste @param args: the liste of arguments for the function

@rtype: list/array @return: the center of mass of the coordinates

unlinkTraj()[source]
update_after_place(grid_point_index)[source]
update_largest_smallest_size(ingr)[source]
update_variable_ingredient_attributes(allIngredients)[source]

updates variable attributes for all ingredients based on input options

writeArraysToFile(f)[source]

write self.compartment_ids and self.distToClosestSurf to file. (pickle)

cellpack.autopack.Environment.random() x in the interval [0, 1).

cellpack.autopack.FirebaseHandler module

class cellpack.autopack.FirebaseHandler.FirebaseHandler(default_db=None)[source]

Bases: object

Retrieve data and perform common tasks when working with firebase.

static create_path(collection, doc_id)[source]
static create_timestamp()[source]
db_name()[source]
delete_doc(collection, id)[source]
static doc_id(doc)[source]
static doc_to_dict(doc)[source]
get_all_docs(collection)[source]
static get_collection_id_from_path(path)[source]
static get_creds(db_choice)[source]
static get_dev_creds()[source]
get_doc_by_id(collection, id)[source]
get_doc_by_name(collection, name)[source]
get_doc_by_ref(path)[source]
static get_path_from_ref(doc)[source]
static get_staging_creds()[source]
static get_username()[source]
get_value(collection, id, field)[source]
static is_firebase_obj(obj)[source]
static is_reference(path)[source]
set_doc(collection, id, data)[source]
update_doc(collection, id, data)[source]
static update_elements_in_array(doc_ref, index, new_item_ref, remove_item)[source]
update_or_create(collection, id, data)[source]

If the input id exists, update the doc. If not, create a new file.

static update_reference_on_doc(doc_ref, index, new_item_ref)[source]
upload_doc(collection, data)[source]
static which_db(default_db=None)[source]
static write_creds_path()[source]

cellpack.autopack.GeometryTools module

Created on Mon Jun 24 15:27:52 2013

@author: ludovic Autin

2D integration of circle rectangle intersection area from http://www.eex-dev.net/index.php?id=100 Copyright © Emanuel Jöbstl, 18.06.2011 reative Commons Attribution-ShareAlike

3D integration sphee cube intersection volume from http://crowsandcats.blogspot.com/2013/04/cube-sphere-intersection-volume.html Copyright © Andrew White

class cellpack.autopack.GeometryTools.GeometryTools[source]

Bases: object

GetDistance(p1, p2)[source]
LowerCircleFunction(m, r, x)[source]
LowerRectangleFunction(rect, x)[source]
Resolution = 0.01
UpperCircleFunction(m, r, x)[source]
UpperRectangleFunction(rect, x)[source]
calc_volume(rho, d)[source]
check_rectangle_oustide(rect, m, r)[source]
check_sphere_inside(rect, m, r)[source]

check if sphere completly inside rect check if the four corner are more than radius away from circle center

getBoundary(rect, m, r)[source]
get_rectangle_cercle_area(rect, m, r, leftBound, rightBound)[source]
region_1(rho, d)[source]
region_1_2_theta(rho, d)[source]
region_2(rho, d)[source]
region_2_integrand(theta, rho, d)[source]
region_3(rho, d)[source]
region_3_integrand(theta, rho, d)[source]
class cellpack.autopack.GeometryTools.Rectangle(top, bottom, right, left)[source]

Bases: object

cellpack.autopack.Gradient module

# autoPACK Authors: Graham T. Johnson, Mostafa Al-Alusi, Ludovic Autin, Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # Environment.py Authors: Graham Johnson & Michel Sanner with editing/enhancement # from Ludovic Autin # HistoVol.py became Environment.py in the Spring of 2013 to generalize the terminology # away from biology # # Translation to Python initiated March 1, 2010 by Michel Sanner with Graham Johnson # # Class restructuring and organization: Michel Sanner # # Copyright: Graham Johnson ©2010 # # This file “Environment.py” is part of autoPACK, cellPACK. # # autoPACK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # autoPACK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autoPACK (See “CopyingGNUGPL” in the installation. # If not, see <http://www.gnu.org/licenses/>. # # ############################################################################### @author: Graham Johnson, Ludovic Autin, & Michel Sanner

# Hybrid version merged from Graham’s Sept 2011 and Ludo’s April 2012 # version on May 16, 2012 # Updated with final thesis HistoVol.py file from Sept 25, 2012 on July 5, 2012 # with correct analysis tools

# TODO: fix the save/restore grid

class cellpack.autopack.Gradient.Gradient(gradient_data)[source]

Bases: object

The Gradient class

This class handle the use of gradient to control the packing. The class define different and setup type of gradient, as well as the sampling function

build_axis_weight_map(bb, master_grid_positions)[source]

from a given axe (X,Y,Z) build a linear weight according the chosen mode (linear, gauss, etc…)

build_directional_weight_map(bb, master_grid_positions)[source]

from a given direction build a linear weight according the chosen mode (linear, gauss, etc…)

build_radial_weight_map(bb, master_grid_positions)[source]
build_surface_distance_weight_map()[source]

build a map of weights based on the distance from a surface assumes self.distances include surface distances

build_weight_map(bb, master_grid_positions)[source]

build the actual gradient value according the gradient mode

create_voxelization(image_writer)[source]

Creates a voxelized representation of the gradient distances and weights

defaultFunction(xyz, direction)[source]

#linear function 0->0.1 #project xyz on direction

getBinaryWeighted(listPts)[source]

From http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/ Note that the loop in the end of the function is simply looking for a place to insert rnd in a sorted list. Therefore, it can be speed up by employing binary search. Python comes with one built-in, just use the bisect module.

getForwWeight(listPts)[source]
getLinearWeighted(listPts)[source]

From: http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/ The following is a simple function to implement weighted random selection in Python. Given a list of weights, it returns an index randomly, according to these weights [2]. For example, given [2, 3, 5] it returns 0 (the index of the first element) with probability 0.2, 1 with probability 0.3 and 2 with probability 0.5. The weights need not sum up to anything in particular, and can actually be arbitrary Python floating point numbers.

getMaxWeight(listPts)[source]

from the given list of grid point indice, get the point with the maximum weight

getMinWeight(listPts)[source]

from the given list of grid point indice, get the point with the minimum weight

getRndWeighted(list_of_pts)[source]

From http://glowingpython.blogspot.com/2012/09/weighted-random-choice.html Weighted random selection returns n_picks random indexes. the chance to pick the index i is give by the weight weights[i].

getSubWeighted(listPts)[source]

From http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/ This method is about twice as fast as the binary-search technique, although it has the same complexity overall. Building the temporary list of totals turns out to be a major part of the functions runtime. This approach has another interesting property. If we manage to sort the weights in descending order before passing them to weighted_choice_sub, it will run even faster since the random call returns a uniformly distributed value and larger chunks of the total weight will be skipped in the beginning.

get_center()[source]

get the center of the gradient grid

static get_combined_gradient_weight(gradient_list, gradient_weights=None)[source]

Combine the gradient weights

Parameters:

gradient_list (list) – list of gradient objects

Returns:

the combined gradient weight

Return type:

numpy.ndarray

get_gauss_weights(number_of_points, degree=5)[source]

given a number of points compute the gaussian weight for each

normalize_vector(vector)[source]

Normalize to unit vector

pickPoint(listPts)[source]

pick next random point according to the chosen function

static pick_point_for_ingredient(ingr, allIngrPts, all_gradients)[source]

Picks a point for an ingredient according to the gradient

Parameters:
  • ingr (Ingredient) – the ingredient object

  • allIngrPts (numpy.ndarray) – list of grid point indices

  • all_gradients (dict) – dictionary of all gradient objects

Returns:

the index of the picked point

Return type:

int

static pick_point_from_weight(weight, points)[source]

Picks a point from a list of points according to the given weight

Parameters:
  • weight (numpy.ndarray) – the weight of each point

  • points (numpy.ndarray) – list of grid point indices

Returns:

the index of the picked point

Return type:

int

static scale_between_0_and_1(values)[source]

Scale values between 0 and 1

set_weights_by_mode()[source]
static update_ingredient_gradient(ingr, arguments)[source]

Update the ingredient gradient

cellpack.autopack.Gradient.random() x in the interval [0, 1).

cellpack.autopack.Graphics module

class cellpack.autopack.Graphics.AutopackViewer(helper=None, ViewerType='dejavu')[source]

Bases: object

the base class for viewing/displaying autopack result in a specified viewer ie DejaVu, Cinema4D, Maya or Blender (which are supported hostApp by ePMV)

Constructor of the AFViewer. Define the needed function for constructing the geometry representing the different compartment and recipe that have been used for the filling.

@type ViewerType: string @param ViewerType: name of the viewer / host application

SetHistoVol(histo, pad, display=True)[source]

Define the current histo volume.

@type histo: autopack.HistoVol @param histo: the current histo-volume @type pad: float @param pad: the pading value to extend the histo volume bounding box @type display: boolean @param display: if a geometry is created to represent the envume box

addCompartmentFromGeom(name, obj, **kw)[source]
addIngredientFromGeom(name, ingrobj, recipe=None, **kw)[source]
addMasterIngr(ingr, parent=None)[source]

Create a empty master/parent geometry for a ingredient

@type ingr: autopack.Ingredient @param ingr: the ingredient @type parent: hostObject @param parent: specify a parent to insert under

appendIngrInstance(ingr, sel=None, bb=None)[source]
buildIngrPrimitive(ingr, visible=1)[source]
callFunction(function, *args, **kw)[source]
checkCreateEmpty(name, parent=None)[source]
checkIngrPartnerProperties(ingr)[source]
checkIngrSpheres(ingr)[source]
clearAll(recipe)[source]
clearFill(recipe)[source]
clearIngr(*args)[source]

will clear all ingredients instances but leave base parent hierarchie intact

clearRecipe(recipe, *args)[source]

will clear everything related to self.recipe

collectResult(ingr, pos, rot)[source]
color(mode='distance', target=None, parents=None, data=None, objects=None, colors=[(1.0, 0.0, 0.0), (0.0, 0.0, 0.0)], **options)[source]
colorByDistanceFrom(target, parents=None, distances=None, objects=None, ramp=None, colors=[(1.0, 0.0, 0.0), (0.0, 0.0, 0.0)], **options)[source]

target : name or host object target Deprecated, need to use new name rule

colorByOrder(parents=None, orders=None, objects=None, ramp=None, colors=[(1.0, 0.0, 0.0), (0.0, 0.0, 0.0)], **options)[source]

target : name or host object target

colorPT(name, values)[source]
createIngrMesh(ingr)[source]
createOrganelMesh(orga)[source]
createTemplate(**kw)[source]
createTemplateCompartment(organame, **kw)[source]
delIngr(ingr)[source]
delIngredientGrow(ingr)[source]
displayCompartment(orga)[source]

Create and display geometry for an compartment.

@type orga: autopack.Compartment @param orga: the compartment

displayCompartmentPoints(orga)[source]

Use this function to display grid pointCloud for an compartment

@type orga: autopack.Compartment @param orga: the compartment

displayCompartments()[source]

Create and display geometry for all compartments defined for the envume.

displayCompartmentsIngredients()[source]
displayCompartmentsPoints()[source]

Create and display grid points for all compartments defined for the envume.

displayCytoplasmIngredients()[source]
displayDistance(ramp_color1=[1, 0, 0], ramp_color2=[0, 0, 1], ramp_color3=None, cutoff=60.0)[source]
displayEnv()[source]

display histo volume bounding box

displayFill()[source]

Use this function once a Box have been filled. displayFill will display all placed ingredients in the Box, and affiliated them according if they are on surface, in cytoplasm or in the compartment. displayFill also display optionally the different point grid.

displayFillBox(bb)[source]

display the box used for compute the grid and fill

displayFreePoints(vDebug=0)[source]
displayFreePointsAsPS()[source]
displayGradient(gradient, positions)[source]

Display the given gradient as sphere at each grid position with radius = weight

displayIngrCylinders(ingr, verts, radii, visible=0)[source]
displayIngrGrow(ingr, visible=1)[source]
displayIngrGrows()[source]
displayIngrMesh(matrices, ingr)[source]
displayIngrResults(ingredient, doSphere=False, doMesh=True)[source]

Display the result for the given ingr after filling

displayIngrSpheres(ingr, verts, radii, visible=1)[source]
displayIngredients(recipes)[source]
displayInstancesIngredient(ingredient, matrices)[source]
displayLeafOctree(name, node, ind, parent)[source]
displayOctree()[source]
displayOctreeLeaf()[source]
displayOneNodeOctree(name, node, ind, parent)[source]
displayParticleVolumeDistance(distance, env)[source]
displayPoints(name, points, parent, colors=[[1, 1, 0]])[source]

Use this function to display a pointCloud. By default, theses points are not visible in the viewport.

@type name: string @param name: the name of the point cloud object @type points: list @param points: list of point indice or list point array @type parent: hostObject @param parent: the parent of the point cloud @type colors: list @param colors: point color array [r,g,b]

displayPreFill()[source]

Use this function once a env and his compartments are defined. displayPreFill will prepare all master, and will create the geometry for the histovolume bounding box, and the different compartments defined.

displayRoot(root)[source]
displaysubnode(parentnode, i)[source]
dspMesh(geom)[source]
dspSph(geom)[source]
exportAsIndexedMeshs()[source]
exportIngredient(ingr)[source]
exportRecipeIngredients(recipe)[source]
hideIngrPrimitive(ingr)[source]
prepareDynamic()[source]
prepareIngredient()[source]
prepareMaster()[source]

Create all empty master/parent geometry for the cytoplasm and all ingredient. If not in DejaVu prepare the meshes use for instanced geometry such as spheres and cylinders

printIngredients()[source]
printOneIngr(ingr)[source]
replaceIngrMesh(ingredient, newMesh)[source]
showHide(func)[source]
showIngrPrimitive(ingr)[source]
timeFunction(function, args, kw)[source]

Measure the time for performing the provided function.

@type function: function @param function: the function to execute @type args: list @param args: the list of arguments for the function

@rtype: list/array @return: the center of mass of the coordinates

toggleOrganelMatr(organame, display)[source]
toggleOrganelMesh(organame, display)[source]
toggleOrganelSurf(organame, display)[source]
undspMesh(geom)[source]
undspSph(geom)[source]
class cellpack.autopack.Graphics.ColladaExporter(env)[source]

Bases: object

cellpack.autopack.Grid module

class cellpack.autopack.Grid.Grid(boundingBox=([0, 0, 0], [0.1, 0.1, 0.1]), space=10.0)[source]

Bases: BaseGrid

The Grid class

This class handle the use of grid to control the packing. The grid keep information of 3d positions, distances, free_points and inside/surface points from organelles. NOTE : this class could be completely replaced if openvdb is wrapped to python.

create3DPointLookup(boundingBox=None)[source]

Fill the orthogonal bounding box described by two global corners with an array of points spaces pGridSpacing apart.:

getIJK(ptInd)[source]

get i,j,k (3d) indices from u (1d)

reset()[source]
restore()[source]
save()[source]

cellpack.autopack.IOutils module

Created on Sun Jan 27 09:04:10 2013

@author: Ludovic Autin

class cellpack.autopack.IOutils.ExportCollada(env)[source]

Bases: object

class cellpack.autopack.IOutils.GrabResult(env)[source]

Bases: object

Class for callbacks

grab(value)[source]

the callback function

reset()[source]
class cellpack.autopack.IOutils.IOingredientTool(env=None)[source]

Bases: object

static clean_arguments(arguments_to_include, **arguments)[source]
ingrJsonNode(ingr, result=False, kwds=None, transpose=False)[source]
ingrPythonNode(ingr, recipe='recipe')[source]
makeIngredient(env, **kw)[source]
makeIngredientFromJson(env, inode=None, filename=None, recipe='Generic')[source]
read(filename)[source]
set_recipe_ingredient(xmlnode, recipe)[source]
cellpack.autopack.IOutils.addCompartments(env, compdic, i, io_ingr)[source]
cellpack.autopack.IOutils.checkRotFormat(rotation, transpose)[source]
cellpack.autopack.IOutils.gatherResult(ingr_result, transpose, use_quaternion, type=0.0, lefthand=False)[source]
cellpack.autopack.IOutils.getAllPosRot(env, transpose, use_quaternion, lefthand=False)[source]
cellpack.autopack.IOutils.getStringValueOptions(value, attrname)[source]

Helper function to return the given environment option as a string to be write in the xml file.

cellpack.autopack.IOutils.load_Json(env, setupfile)[source]

Setup the environment according the given json file.

cellpack.autopack.IOutils.load_JsonString(env, astring)[source]

Setup the environment according the given json file.

cellpack.autopack.IOutils.load_MixedasJson(env, resultfilename=None, transpose=True)[source]
cellpack.autopack.IOutils.saveResultBinary(env, filename, transpose, use_quaternion, lefthand=False)[source]
cellpack.autopack.IOutils.saveResultBinaryDic(env, filename, transpose, use_quaternion, lefthand=False)[source]
cellpack.autopack.IOutils.save_asPython(env, setupfile, useXref=True)[source]

Save the current environment setup as a python script file.

cellpack.autopack.IOutils.serializedFromResult(env, transpose, use_quaternion, result=False, lefthand=False)[source]
cellpack.autopack.IOutils.serializedRecipe(env, transpose, use_quaternion, result=False, lefthand=False)[source]
cellpack.autopack.IOutils.serializedRecipe_group(env, transpose, use_quaternion, lefthand=False)[source]
cellpack.autopack.IOutils.serializedRecipe_group_dic(env, transpose, use_quaternion, lefthand=False)[source]
cellpack.autopack.IOutils.setValueToPythonStr(value, attrname)[source]
cellpack.autopack.IOutils.setupFromJsonDic(env)[source]
cellpack.autopack.IOutils.toBinary(all_pos, all_rot, filename)[source]
cellpack.autopack.IOutils.updatePositionsRadii(ingr)[source]

cellpack.autopack.MeshStore module

class cellpack.autopack.MeshStore.MeshStore[source]

Bases: object

add_mesh_to_scene(mesh, name)[source]
build_mesh(data, geomname)[source]

Create a polygon mesh object from a dictionary verts,faces,normals

static calc_scaled_distances_for_positions(position_list, inner_mesh, outer_mesh)[source]
contains_point(geomname, point)[source]
contains_points_mesh(geomname, points)[source]
create_mesh(name, vertices, vnormals, faces)[source]

This is the main function that create a polygonal mesh.

@type name: string @param name: name of the pointCloud @type vertices: array @param vertices: list of x,y,z vertices points @type vnormals: array @param vnormals: list of x,y,z vertex normals vector @type faces: array @param faces: list of i,j,k indice of vertex by face @return: the polygon object

create_sphere(name, iterations, radius)[source]

Create the mesh data and the mesh object of a Sphere of a given radius

@type name: string @param name: name for the sphere @type iterations: int @param iterations: resolution @type radius: float @param radius: radius of the sphere

@rtype: Mesh @return: Mesh

create_sphere_data(iterations)[source]

from http://paulbourke.net/geometry/circlesphere/csource2.c

decompose_mesh(poly, edit=True, copy=True, tri=True, transform=True)[source]
get_centroid(geomname)[source]
static get_collada_material(geom, col)[source]
get_mesh(mesh_name, file_path=None)[source]
static get_mesh_filepath_and_extension(filename)[source]
static get_midpoint(p1, p2)[source]
get_normal(geomname, point_pos)[source]
get_nsphere(geomname)[source]
get_object(geomname)[source]
get_scaled_distances_between_surfaces(position_list, inner_mesh_name, outer_mesh_name)[source]

Calculate scaled distances from inner mesh for position_list Inner mesh surface is 0 Outer mesh surface is 1

get_smallest_radius(geomname, center)[source]
static norm(a, b, c)[source]

return the norm of the vector [a,b,c]

>>> result = helper.norm(a,b,c) #a,b,c being double

@type a: float @param a: first value of the vector @type b: float @param b: second value of the vector @type c: float @param c: third value of the vector

@rtype: float @return: the norm of the vector

static normal_array(vertices, faces)[source]
static normalize(A)[source]

return the normalized vector A [x,y,z]

>>> a = [1.0,3.0,5.0]
>>> a_normalized = helper.normalize(a)

@type A: vector @param A: the 3d vector @rtype: vector @return: the normalized 3d vecor

static normalize_v3(arr)[source]

Normalize a numpy array of 3 component vectors shape=(n,3)

read_mesh_file(filename)[source]

cellpack.autopack.OutputSimularium module

cellpack.autopack.Recipe module

# autoPACK Authors: Graham T. Johnson, Mostafa Al-Alusi, Ludovic Autin, # and Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # Recipe.py Authors: Graham Johnson & Michel Sanner with editing/ # enhancement from Ludovic Autin # # Translation to Python initiated March 1, 2010 by Michel Sanner # with Graham Johnson # # Class restructuring and organization: Michel Sanner # # This file “Recipe.py” is part of autoPACK, cellPACK. # # autoPACK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # autoPACK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autoPACK (See “CopyingGNUGPL” in the installation. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################ @author: Graham Johnson, Ludovic Autin, & Michel Sanner

# Hybrid version merged from Graham’s Sept 6, 2011 and Ludo’s April 2012 #version on May 16, 2012, re-merged on July 5, 2012 with thesis versions

class cellpack.autopack.Recipe.Recipe(name='ext')[source]

Bases: object

a recipe provides ingredients that are each defining a protein identity along with radius and molarity for this protein.

addIngredient(ingr)[source]

add the given ingredient from the recipe

delIngredient(ingr)[source]

remove the given ingredient from the recipe

getMinMaxProteinSize()[source]

get the mini and maxi radius from all recipe ingredients

static is_key(key_or_dict, composition_dict)[source]

Helper function to find if data in composition list is a key or an object

printFillInfo(indent='')[source]

print the states of all recipe ingredients

resetIngrs()[source]

reset the states of all recipe ingredients

static resolve_composition(recipe_data)[source]
setCount(volume, reset=True, **kw)[source]

set the count of n of molecule for every ingredients in the recipe, and push them in te activeIngredient list David and Graham independently worked out and corrected the molarity calculation for Å as shown in the following lines M = moles/L 6.022e23 ingredients/mole

uPy works in Å by default (not ideal for mesoscale, but works with all molecular viewers that way), so given a volume in Å^3 1L = (10cm)^3 1cm = 10^(-2)m 1Å = 10^(-10)m 1cm = 10^(8)Å 10cm = 10^(9)Å 1L = (10cm)^3 = (10^(9)Å)^3 = 10^(27)Å^3

M = 6.022x10^23/L = [6.022x10^23] / [10^(27)Å^3] = 6.022x10(-4)ing/Å^3 numberIngredientsToPack = [0.0006022 ing/Å^3] * [volume Å^3]

volume / ingredient in 1M = 1ing / 0.0006022 ing/Å^3 = 1660Å^3 * 1nm^3/1000Å^3 = 1.6nm^3

Average distance between molecules is cubic root 3√(1.6nm^3) = 11.8Å = 1.18nm Thus the nbr should simply be nbr = densityInMolarity*[0.0006022 ing/Å^3] * [volume Å^3] see http://molbiol.edu.ru/eng/scripts/01_04.html http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3910158/ http://book.bionumbers.org/

sort()[source]

sort the ingredients using the min Radius

cellpack.autopack.Recipe.random() x in the interval [0, 1).

cellpack.autopack.Serializable module

Created on Tue Jan 19 15:55:27 2016

@author: ludo

class cellpack.autopack.Serializable.sCompartment(name, **kwds)[source]

Bases: object

addCompartment(compartment)[source]
addIngredientGroup(ingrgroup)[source]
static_id = 0
to_JSON()[source]
class cellpack.autopack.Serializable.sIngredient(name, groupType, **kwds)[source]

Bases: object

static_id = [0, 0, 0]
to_JSON()[source]
class cellpack.autopack.Serializable.sIngredientFiber(name, **kwds)[source]

Bases: object

static_id = 0
to_JSON()[source]
class cellpack.autopack.Serializable.sIngredientGroup(name, groupType, **kwds)[source]

Bases: object

addIngredient(ingredient)[source]
static_id = 0
to_JSON()[source]

cellpack.autopack.binvox_rw module

Binvox to Numpy and back.

binvox argument Usage: binvox [-d <voxel dimension>] [-t <voxel file type>] [-c] [-v] <model filespec>

-license: show software license -d: specify voxel grid size (default 256, max 1024)(no max when using -e) -t: specify voxel file type (default binvox, also supported: hips, mira, vtk, raw, schematic, msh) -c: z-buffer based carving method only -dc: dilated carving, stop carving 1 voxel before intersection -v: z-buffer based parity voting method only (default is both -c and -v) -e: exact voxelization (any voxel with part of a triangle gets set)(does not use graphics card)

Additional parameters:

-bb <minx> <miny> <minz> <maxx> <maxy> <maxz>: force a different input model bounding box -ri: remove internal voxels -cb: center model inside unit cube -rotx: rotate object 90 degrees ccw around x-axis before voxelizing -rotz: rotate object 90 degrees cw around z-axis before voxelizing

both -rotx and -rotz can be used multiple times

-aw: _also_ render the model in wireframe (helps with thin parts) -fit: only write the voxels in the voxel bounding box -bi <id>: when converting to schematic, use block ID <id> -mb: when converting using -e from .obj to schematic, parse block ID from material spec ‘usemtl blockid_<id>’ (ids 1-255 only) -down: downsample voxels by a factor of 2 in each dimension (can be used multiple times) -dmin <nr>: when downsampling, destination voxel is on if >= <nr> source voxels are (default 4)

Supported 3D model file formats:

VRML V2.0: almost fully supported UG, OBJ, OFF, DXF, XGL, POV, BREP, PLY, JOT: only polygons supported

Example: binvox -c -d 200 -t mira plane.wrl

>>> import numpy as np
>>> import binvox_rw
>>> with open('chair.binvox', 'rb') as f:
...     m1 = binvox_rw.read_as_3d_array(f)
...
>>> m1.dims
[32, 32, 32]
>>> m1.scale
41.133000000000003
>>> m1.translate
[0.0, 0.0, 0.0]
>>> with open('chair_out.binvox', 'wb') as f:
...     m1.write(f)
...
>>> with open('chair_out.binvox', 'rb') as f:
...     m2 = binvox_rw.read_as_3d_array(f)
...
>>> m1.dims==m2.dims
True
>>> m1.scale==m2.scale
True
>>> m1.translate==m2.translate
True
>>> np.all(m1.data==m2.data)
True
>>> with open('chair.binvox', 'rb') as f:
...     md = binvox_rw.read_as_3d_array(f)
...
>>> with open('chair.binvox', 'rb') as f:
...     ms = binvox_rw.read_as_coord_array(f)
...
>>> data_ds = binvox_rw.dense_to_sparse(md.data)
>>> data_sd = binvox_rw.sparse_to_dense(ms.data, 32)
>>> np.all(data_sd==md.data)
True
>>> # the ordering of elements returned by numpy.nonzero changes with axis
>>> # ordering, so to compare for equality we first lexically sort the voxels.
>>> np.all(ms.data[:, np.lexsort(ms.data)] == data_ds[:, np.lexsort(data_ds)])
True
class cellpack.autopack.binvox_rw.Voxels(data, dims, translate, scale, axis_order)[source]

Bases: object

Holds a binvox model. data is either a three-dimensional numpy boolean array (dense representation) or a two-dimensional numpy float array (coordinate representation).

dims, translate and scale are the model metadata.

dims are the voxel dimensions, e.g. [32, 32, 32] for a 32x32x32 model.

scale and translate relate the voxels to the original model coordinates.

To translate voxel coordinates i, j, k to original coordinates x, y, z:

x_n = (i+.5)/dims[0] y_n = (j+.5)/dims[1] z_n = (k+.5)/dims[2] x = scale*x_n + translate[0] y = scale*y_n + translate[1] z = scale*z_n + translate[2]

cartesian(arrays, out=None)[source]

#http://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays Generate a cartesian product of input arrays.

Parameters:
  • arrays (list of array-like) – 1-D arrays to form the cartesian product of.

  • out (ndarray) – Array to place the cartesian product in.

Returns:

out – 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays.

Return type:

ndarray

Examples

>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
       [1, 4, 7],
       [1, 5, 6],
       [1, 5, 7],
       [2, 4, 6],
       [2, 4, 7],
       [2, 5, 6],
       [2, 5, 7],
       [3, 4, 6],
       [3, 4, 7],
       [3, 5, 6],
       [3, 5, 7]])
clone()[source]
getIndex(ijk)[source]
getIndexData(ijk)[source]
ijkToIndex(ijk)[source]
ijkToxyz()[source]
write(fp)[source]
xyzToijk(xyz)[source]
cellpack.autopack.binvox_rw.dense_to_sparse(voxel_data, dtype=<class 'int'>)[source]

From dense representation to sparse (coordinate) representation. No coordinate reordering.

cellpack.autopack.binvox_rw.read(fp)[source]

Read binary binvox format as array.

Returns the model with accompanying metadata.

Voxels are stored in a three-dimensional numpy array, which is simple and direct, but may use a lot of memory for large models. (Storage requirements are 8*(d^3) bytes, where d is the dimensions of the binvox model. Numpy boolean arrays use a byte per element).

Doesn’t do any checks on input except for the ‘#binvox’ line.

cellpack.autopack.binvox_rw.read_as_3d_array(fp, fix_coords=True)[source]

Read binary binvox format as array.

Returns the model with accompanying metadata.

Voxels are stored in a three-dimensional numpy array, which is simple and direct, but may use a lot of memory for large models. (Storage requirements are 8*(d^3) bytes, where d is the dimensions of the binvox model. Numpy boolean arrays use a byte per element).

Doesn’t do any checks on input except for the ‘#binvox’ line.

cellpack.autopack.binvox_rw.read_as_coord_array(fp, fix_coords=True)[source]

Read binary binvox format as coordinates.

Returns binvox model with voxels in a “coordinate” representation, i.e. an 3 x N array where N is the number of nonzero voxels. Each column corresponds to a nonzero voxel and the 3 rows are the (x, z, y) coordinates of the voxel. (The odd ordering is due to the way binvox format lays out data). Note that coordinates refer to the binvox voxels, without any scaling or translation.

Use this to save memory if your model is very sparse (mostly empty).

Doesn’t do any checks on input except for the ‘#binvox’ line.

cellpack.autopack.binvox_rw.read_header(fp)[source]

Read binvox header. Mostly meant for internal use.

cellpack.autopack.binvox_rw.sparse_to_dense(voxel_data, dims, dtype=<class 'bool'>)[source]
cellpack.autopack.binvox_rw.write(voxel_model, fp)[source]

Write binary binvox format.

Note that when saving a model in sparse (coordinate) format, it is first converted to dense format.

Doesn’t check if the model is ‘sane’.

cellpack.autopack.ldSequence module

# autoPACK Authors: Graham T. Johnson, Mostafa Al-Alusi, Ludovic Autin, Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # ldSequence.py Authors: Ludovic Autin ############################################################################### @author: Ludovic Autin, Graham Johnson, & Michel Sanner

class cellpack.autopack.ldSequence.HaltonSequence(dim, atmost=10000)[source]

Bases: object

Another algorithm to compute a d-dimensional Halton Sequence. This one gives the same results as the other.

cellpack.autopack.ldSequence.SphereHalton(n, p2, marge=0.7853981633974483)[source]
class cellpack.autopack.ldSequence.cHaltonSequence3[source]

Bases: object

inc()[source]
reset()[source]
cellpack.autopack.ldSequence.halton(terms, base=2)[source]
cellpack.autopack.ldSequence.halton2(terms, base1=2, base2=3)[source]
cellpack.autopack.ldSequence.halton3(terms, base1=2, base2=3, base3=5)[source]
cellpack.autopack.ldSequence.halton_sequence(n, b)[source]
cellpack.autopack.ldSequence.haltonterm(i, base=2)[source]

cellpack.autopack.octree module

class cellpack.autopack.octree.OctNode(position, size, data)[source]

Bases: object

class cellpack.autopack.octree.Octree(center, worldSize)[source]

Bases: object

addNode(position, size, objects)[source]
findBranch(root, position)[source]
findPosition(root, position)[source]
insertNode(root, size, parent, objData)[source]

cellpack.autopack.plotly_result module

class cellpack.autopack.plotly_result.PlotlyAnalysis(title='')[source]

Bases: object

add_circle(radius, pos, color, opacity=1)[source]
add_ingredient_positions(env)[source]
add_square(side_length, pos, rotMat, color, opacity=1)[source]
static format_color(color)[source]
make_and_show_heatmap(env)[source]
make_grid_heatmap(env)[source]
show()[source]
transformPoints2D(trans, rot, points)[source]
update_title(title)[source]

cellpack.autopack.randomRot module

Created 2012

# autoPACK Authors: Graham T. Johnson, Ludovic Autin, Mostafa Al-Alusi, Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # AFGui.py Authors: Ludovic Autin with minor editing/enhancement from Graham Johnson # # Copyright: Graham Johnson ©2010 # # This file is part of autoPACK, cellPACK, and AutoFill. # # autoPACK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # autoPACK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autoPACK (See “CopyingGNUGPL” in the installation. # If not, see <http://www.gnu.org/licenses/>. # ###############################################################################

Name: ‘randomRot’ @author: Modified from uniform random rotation matrix from http://www.lfd.uci.edu/~gohlke/code/transformations.py.html which is copyrighted as follows:

# # -- coding: utf-8 -- # # transformations.py # # # Copyright (c) 2006-2012, Christoph Gohlke # # Copyright (c) 2006-2012, The Regents of the University of California # # Produced at the Laboratory for Fluorescence Dynamics # # All rights reserved. # # # # Redistribution and use in source and binary forms, with or without # # modification, are permitted provided that the following conditions are met: # # # # * Redistributions of source code must retain the above copyright # # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # # notice, this list of conditions and the following disclaimer in the # # documentation and/or other materials provided with the distribution. # # * Neither the name of the copyright holders nor the names of any # # contributors may be used to endorse or promote products derived # # from this software without specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” # # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # # Homogeneous Transformation Matrices and Quaternions. # # A library for calculating 4x4 matrices for translating, rotating, reflecting, # scaling, shearing, projecting, orthogonalizing, and superimposing arrays of # 3D homogeneous coordinates as well as for converting between rotation matrices, # Euler angles, and quaternions. Also includes an Arcball control object and # functions to decompose transformation matrices. # # :Authors: # Christoph Gohlke, # Laboratory for Fluorescence Dynamics, University of California, Irvine # # :Version: 2012.10.18

class cellpack.autopack.randomRot.RandomRot(seed=16)[source]

Bases: object

get()[source]
getOld()[source]
quaternion_matrix(quaternion)[source]

Return homogeneous rotation matrix from quaternion.

>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> numpy.allclose(M, numpy.identity(4))
True
>>> M = quaternion_matrix([0, 1, 0, 0])
>>> numpy.allclose(M, numpy.diag([1, -1, -1, 1]))
True
random_quaternion(rand=None)[source]

Return uniform random unit quaternion.

rand: array like or None

Three independent random variables that are uniformly distributed between 0 and 1.

>>> q = random_quaternion()
>>> numpy.allclose(1, vector_norm(q))
True
>>> q = random_quaternion(numpy.random.random(3))
>>> len(q.shape), q.shape[0]==4
(1, True)
random_rotation_matrix(rand=None)[source]

Return uniform random rotation matrix.

rand: array like

Three independent random variables that are uniformly distributed between 0 and 1 for each returned quaternion.

>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True
setSeed(seed=16)[source]

cellpack.autopack.ray module

Created on Saturday September 1 1:50:00 2012

# # autoPACK Authors: Graham T. Johnson, Ludovic Autin, Mostafa Al-Alusi, Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # AFGui.py Authors: Ludovic Autin with minor editing/enhancement from Graham Johnson # # Copyright: Graham Johnson ©2010 # # This file “fillBoxPseudoCode.py” is part of autoPACK, cellPACK, and AutoFill. # # autoPACK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # autoPACK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autoPACK (See “CopyingGNUGPL” in the installation. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################### Name: - @author: Graham Johnson, Michel Sanner, Ludovic Autin, Kevin Wu

cellpack.autopack.ray.dot(v1, v2)[source]
cellpack.autopack.ray.f_dot_product(vector1, vector2)[source]

Return the dot product of two 3D vectors.

cellpack.autopack.ray.f_ray_intersect_polyhedron(pRayStartPos, pRayEndPos, faces, vertices, pTruncateToSegment)[source]

This function returns TRUE if a ray intersects a triangle. It also calculates and returns the UV coordinates of said colision as part of the intersection test, Makes sure that we are working with arrays

  • TAKES IN pRayStartPos as LEFT-HANDED COORDINATE (Z,Y,X)

  • TAKES IN pRayEndPos AS LEFT-HANDED COORDINATE (Z,Y,X)

  • faces is a list of vertex indices that defines the polyhedron

  • vertices is the list of global coordinates that faces refers to

  • pTruncateToSegment decides whether or not the segment terminates at the end position, or keeps on going forever

cellpack.autopack.ray.findPointsCenter(*args)[source]
cellpack.autopack.ray.makeMarchingCube(gridSpacing, r)[source]

Create a numpy array that represents the precomputed distances to each point for the cube of points surrounding our center point.

cellpack.autopack.ray.ray_intersect_polygon(pRayStartPos, pRayEndPos, pQuadranglePointPositions, pQuadranglePointList, pTruncateToSegment)[source]
cellpack.autopack.ray.ray_intersect_polyhedron(pRayStartPos, pRayEndPos, vertices, faces, pTruncateToSegment)[source]
cellpack.autopack.ray.vcross(v1, v2)[source]
cellpack.autopack.ray.vdiff(p1, p2)[source]
cellpack.autopack.ray.vlen(v1)[source]
cellpack.autopack.ray.vnorm(v1)[source]

cellpack.autopack.trajectory module

Created on Wed Mar 19 11:50:35 2014

@author: ludo

class cellpack.autopack.trajectory.Trajectory(filename, nbIngredients)[source]

Bases: object

applyState(h, frame)[source]
applyState_cb(h, frame, cb)[source]
applyState_name(h, frame)[source]
applyState_primitive_name(h, frame)[source]
completeMapping(h)[source]
generalApply(obj, obj_id, frame)[source]
getIngredientInstancePos(name, instance_id, frame)[source]
makeIngrMapping(name, nbInstance)[source]
reg = '[-+]?[0-9]*\\.?[0-9]+'
traj_type = ''
class cellpack.autopack.trajectory.dcdTrajectory(filename, nbIngredients)[source]

Bases: Trajectory

dcd = None
getPosAt(indice, frame)[source]
parse(filename=None, **kwds)[source]
traj_type = 'dcd'
class cellpack.autopack.trajectory.molbTrajectory(filename, nbIngredients)[source]

Bases: Trajectory

applyState_name(h, frame)[source]
applyState_primitive_name(h, frame)[source]
getPosAt(indice, frame)[source]
parse(filename=None, count=0, log=False)[source]
parse_one_mol(filename, instance_id, ftype='double', log=False)[source]
traj_type = 'molb'
class cellpack.autopack.trajectory.xyzTrajectory(filename, nbIngredients)[source]

Bases: Trajectory

getPosAt(indice, frame)[source]
getPosLine(line)[source]
parse(filename=None, **kwds)[source]
traj_type = 'xyz'

cellpack.autopack.transformation module

Homogeneous Transformation Matrices and Quaternions.

A library for calculating 4x4 matrices for translating, rotating, reflecting, scaling, shearing, projecting, orthogonalizing, and superimposing arrays of 3D homogeneous coordinates as well as for converting between rotation matrices, Euler angles, and quaternions. Also includes an Arcball control object and functions to decompose transformation matrices.

Author:

Christoph Gohlke

Organization:

Laboratory for Fluorescence Dynamics, University of California, Irvine

Version:

2013.06.29

Requirements

Notes

The API is not stable yet and is expected to change between revisions.

This Python code is not optimized for speed. Refer to the transformations.c module for a faster implementation of some functions.

Documentation in HTML format can be generated with epydoc.

Matrices (M) can be inverted using numpy.linalg.inv(M), be concatenated using numpy.dot(M0, M1), or transform homogeneous coordinate arrays (v) using numpy.dot(M, v) for shape (4, /) column vectors, respectively numpy.dot(v, M.T) for shape (/, 4) row vectors (“array of points”).

This module follows the “column vectors on the right” and “row major storage” (C contiguous) conventions. The translation components are in the right column of the transformation matrix, i.e. M[:3, 3]. The transpose of the transformation matrices may have to be used to interface with other graphics systems, e.g. with OpenGL’s glMultMatrixd(). See also [16].

Calculations are carried out with numpy.float64 precision.

Vector, point, quaternion, and matrix function arguments are expected to be “array like”, i.e. tuple, list, or numpy arrays.

Return types are numpy arrays unless specified otherwise.

Angles are in radians unless specified otherwise.

Quaternions w+ix+jy+kz are represented as [w, x, y, z].

A triple of Euler angles can be applied/interpreted in 24 ways, which can be specified using a 4 character string or encoded 4-tuple:

Axes 4-string: e.g. ‘sxyz’ or ‘ryxy’

  • first character : rotations are applied to ‘s’tatic or ‘r’otating frame

  • remaining characters : successive rotation axis ‘x’, ‘y’, or ‘z’

Axes 4-tuple: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)

  • inner axis: code of axis (‘x’:0, ‘y’:1, ‘z’:2) of rightmost matrix.

  • parity : even (0) if inner axis ‘x’ is followed by ‘y’, ‘y’ is followed by ‘z’, or ‘z’ is followed by ‘x’. Otherwise odd (1).

  • repetition : first and last axis are same (1) or different (0).

  • frame : rotations are applied to static (0) or rotating (1) frame.

References

  1. Matrices and transformations. Ronald Goldman. In “Graphics Gems I”, pp 472-475. Morgan Kaufmann, 1990.

  2. More matrices and transformations: shear and pseudo-perspective. Ronald Goldman. In “Graphics Gems II”, pp 320-323. Morgan Kaufmann, 1991.

  3. Decomposing a matrix into simple transformations. Spencer Thomas. In “Graphics Gems II”, pp 320-323. Morgan Kaufmann, 1991.

  4. Recovering the data from the transformation matrix. Ronald Goldman. In “Graphics Gems II”, pp 324-331. Morgan Kaufmann, 1991.

  5. Euler angle conversion. Ken Shoemake. In “Graphics Gems IV”, pp 222-229. Morgan Kaufmann, 1994.

  6. Arcball rotation control. Ken Shoemake. In “Graphics Gems IV”, pp 175-192. Morgan Kaufmann, 1994.

  7. Representing attitude: Euler angles, unit quaternions, and rotation vectors. James Diebel. 2006.

  8. A discussion of the solution for the best rotation to relate two sets of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828.

  9. Closed-form solution of absolute orientation using unit quaternions. BKP Horn. J Opt Soc Am A. 1987. 4(4):629-642.

  10. Quaternions. Ken Shoemake. http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf

  11. From quaternion to matrix and back. JMP van Waveren. 2005. http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm

  12. Uniform random rotations. Ken Shoemake. In “Graphics Gems III”, pp 124-132. Morgan Kaufmann, 1992.

  13. Quaternion in molecular modeling. CFF Karney. J Mol Graph Mod, 25(5):595-604

  14. New method for extracting the quaternion from a rotation matrix. Itzhack Y Bar-Itzhack, J Guid Contr Dynam. 2000. 23(6): 1085-1087.

  15. Multiple View Geometry in Computer Vision. Hartley and Zissermann. Cambridge University Press; 2nd Ed. 2004. Chapter 4, Algorithm 4.7, p 130.

  16. Column Vectors vs. Row Vectors. http://steve.hollasch.net/cgindex/math/matrix/column-vec.html

Examples

>>> alpha, beta, gamma = 0.123, -1.234, 2.345
>>> origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]
>>> I = identity_matrix()
>>> Rx = rotation_matrix(alpha, xaxis)
>>> Ry = rotation_matrix(beta, yaxis)
>>> Rz = rotation_matrix(gamma, zaxis)
>>> R = concatenate_matrices(Rx, Ry, Rz)
>>> euler = euler_from_matrix(R, 'rxyz')
>>> numpy.allclose([alpha, beta, gamma], euler)
True
>>> Re = euler_matrix(alpha, beta, gamma, 'rxyz')
>>> is_same_transform(R, Re)
True
>>> al, be, ga = euler_from_matrix(Re, 'rxyz')
>>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz'))
True
>>> qx = quaternion_about_axis(alpha, xaxis)
>>> qy = quaternion_about_axis(beta, yaxis)
>>> qz = quaternion_about_axis(gamma, zaxis)
>>> q = quaternion_multiply(qx, qy)
>>> q = quaternion_multiply(q, qz)
>>> Rq = quaternion_matrix(q)
>>> is_same_transform(R, Rq)
True
>>> S = scale_matrix(1.23, origin)
>>> T = translation_matrix([1, 2, 3])
>>> Z = shear_matrix(beta, xaxis, origin, zaxis)
>>> R = random_rotation_matrix(numpy.random.rand(3))
>>> M = concatenate_matrices(T, R, Z, S)
>>> scale, shear, angles, trans, persp = decompose_matrix(M)
>>> numpy.allclose(scale, 1.23)
True
>>> numpy.allclose(trans, [1, 2, 3])
True
>>> numpy.allclose(shear, [0, math.tan(beta), 0])
True
>>> is_same_transform(R, euler_matrix(axes='sxyz', *angles))
True
>>> M1 = compose_matrix(scale, shear, angles, trans, persp)
>>> is_same_transform(M, M1)
True
>>> v0, v1 = random_vector(3), random_vector(3)
>>> M = rotation_matrix(angle_between_vectors(v0, v1), vector_product(v0, v1))
>>> v2 = numpy.dot(v0, M[:3,:3].T)
>>> numpy.allclose(unit_vector(v1), unit_vector(v2))
True

cellpack.autopack.utils module

cellpack.autopack.utils.check_paired_key(val_dict, key1=None, key2=None)[source]

Checks if the key pair exists in dict

cellpack.autopack.utils.cmp_to_key(mycmp)[source]

Convert a cmp= function into a key= function

cellpack.autopack.utils.deep_merge(dct, merge_dct)[source]

Recursive dict merge

This mutates dct - the contents of merge_dct are added to dct (which is also returned). If you want to keep dct you could call it like deep_merge(copy.deepcopy(dct), merge_dct)

cellpack.autopack.utils.expand_object_using_key(current_object, expand_on, lookup_dict)[source]
cellpack.autopack.utils.get_distance(pt1, pt2)[source]
cellpack.autopack.utils.get_distances_from_point(np_array_of_pts, pt)[source]
cellpack.autopack.utils.get_max_value_from_distribution(distribution_options, return_int=False)[source]

Returns a high bound on the value from a distribution

cellpack.autopack.utils.get_min_value_from_distribution(distribution_options, return_int=False)[source]

Returns a low bound on the value from a distribution

cellpack.autopack.utils.get_paired_key(val_dict, key1=None, key2=None)[source]

Get the combined key from dict

cellpack.autopack.utils.get_seed_list(packing_config_data, recipe_data)[source]
cellpack.autopack.utils.get_value_from_distribution(distribution_options, return_int=False)[source]

Returns a value from the distribution options

cellpack.autopack.utils.ingredient_compare0(x, y)[source]

sort ingredients using decreasing priority and decreasing radii for priority ties and decreasing completion for radii ties for priority < 0

cellpack.autopack.utils.ingredient_compare1(x, y)[source]

sort ingredients using decreasing priority and decreasing radii for priority ties and decreasing completion for radii ties for priority > 0

cellpack.autopack.utils.ingredient_compare2(x, y)[source]

sort ingredients using decreasing radii and decresing completion for radii matches: priority = 0

cellpack.autopack.utils.load_object_from_pickle(pickle_file_object)[source]

Update an object from a pickle file

Module contents

Created on Fri Jul 20 23:53:00 2012

# # autoPACK Authors: Graham T. Johnson, Mostafa Al-Alusi, Ludovic Autin, Michel Sanner # Based on COFFEE Script developed by Graham Johnson between 2005 and 2010 # with assistance from Mostafa Al-Alusi in 2009 and periodic input # from Arthur Olson’s Molecular Graphics Lab # # __init__.py Authors: Ludovic Autin with minor editing/enhancement from Graham Johnson # # Copyright: Graham Johnson ©2010 # # This file “__init__.py” is part of autoPACK. # # autoPACK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # autoPACK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autoPACK (See “CopyingGNUGPL” in the installation. # If not, see <http://www.gnu.org/licenses/>. # ############################################################################### Name: ‘autoPACK’ Define here some usefull variable and setup filename path that facilitate AF @author: Ludovic Autin with editing by Graham Johnson

cellpack.autopack.checkErrorInPath(p, toreplace)[source]
cellpack.autopack.checkPath()[source]
cellpack.autopack.checkRecipeAvailable()[source]
cellpack.autopack.clearCaches(*args)[source]
cellpack.autopack.convert_db_shortname_to_url(file_location)[source]

@param file_path: str

cellpack.autopack.download_file(url, local_file_path, reporthook, database_name='aws')[source]
cellpack.autopack.fixOnePath(path)[source]
cellpack.autopack.fixPath(adict)[source]
cellpack.autopack.get_cache_location(name, cache, destination)[source]

name: str destination: str

cellpack.autopack.get_local_file_location(input_file_location, destination='', cache='geometries', force=False)[source]

Options: 1. Find file locally, return the file path 2. Download file to local cache, return path (might involve replacing short-code in url) 3. Force download even though you have a local copy

Returns location of file (either already there or newly downloaded)

cellpack.autopack.is_full_url(file_path)[source]
cellpack.autopack.is_remote_path(file_path)[source]

@param file_path: str

cellpack.autopack.is_s3_url(file_path)[source]
cellpack.autopack.load_file(filename, destination='', cache='geometries', force=None)[source]
cellpack.autopack.make_directory_if_needed(directory)[source]
cellpack.autopack.parse_s3_uri(s3_uri)[source]
cellpack.autopack.read_text_file(filename, destination='', cache='collisionTrees', force=None)[source]
cellpack.autopack.resetDefault()[source]
cellpack.autopack.saveRecipeAvailable(recipe_dictionary, recipefile)[source]
cellpack.autopack.saveRecipeAvailableJSON(recipe_dictionary, filename)[source]
cellpack.autopack.updatePath()[source]
cellpack.autopack.updatePathJSON()[source]
cellpack.autopack.updateRecipAvailableXML(recipesfile)[source]
cellpack.autopack.updateReplacePath(newPaths)[source]
cellpack.autopack.url_exists(url)[source]
cellpack.autopack.write_username_to_creds()[source]