Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addon #30

Merged
merged 5 commits into from
Aug 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
.vscode/settings.json
*.pyc
*.Rproj
*.zip
~*.xlsx
paper/paper.html
paper/paper.log
Expand Down
21 changes: 21 additions & 0 deletions blender/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 - 2024, Daniel Antonio Negrón (dnanto/remaindeer)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
29 changes: 29 additions & 0 deletions blender/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# addon

[![Blender 3.0.0](https://img.shields.io/badge/blender-3.0.0-%23f4792b.svg)]()

Calculate meshes for icosahedral virus capsids.

## Installation

1. Download [latest version](https://github.com/dnanto/democapsid) of blendocapsid.
2. From Blender: Edit > Preferences
3. Select the 'Add-ons tab' and click 'Install' in the upper right.
4. Navigate to the zip file and click 'Install Add-on from File'

## Contributing

Have a bug fix or a new feature you'd like to see? Send it on over! Please make sure you create an issue that addresses your fix/feature so we can discuss the contribution.

1. Fork this repo!
2. Create your feature branch: `git checkout -b features/fix-bug`
3. Commit your changes: `git commit -m 'Fixes the following...'`
4. Push the branch: `git push origin features/fix-bug`
5. Submit a pull request.
6. Create an [issue]().

## License

MIT

See the [license](./LICENSE) document for the full text.
45 changes: 45 additions & 0 deletions blender/blendocapsid/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
bl_info = {
'name': 'blendocapsid',
'author': 'Daniel Antonio Negrón',
'version': (0, 0, 1),
'blender': (3, 0, 0),
'location': 'Objects > Add Capsid Mesh',
'description': 'Calculate meshes for icosahedral virus capsids with democapsid.',
'warning': '',
'wiki_url': 'https://github.com/dnanto/democapsid',
'support': 'COMMUNITY',
'category': 'Add Mesh'
}

__version__ = '.'.join(map(str, bl_info['version']))


# Handle Reload Scripts

if 'reload' in locals():
import importlib as il
il.reload(reload)
reload.all()

import blendocapsid.reload as reload


def register():
from . import patch
patch.add_local_modules_to_path()

from blendocapsid import operators, panels

operators.register()
panels.register()


def unregister():
from blendocapsid import operators, panels

operators.unregister()
panels.unregister()


if __name__ == '__main__':
register()
72 changes: 72 additions & 0 deletions blender/blendocapsid/operators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import bpy


class CapsidMesh(bpy.types.Operator):
"""Add icosahedral capsid mesh."""
bl_idname = "object.add_mesh"
bl_label = "Add Capsid Mesh"
bl_options = {"REGISTER", "UNDO"}
axis_items = [
("2", "2", "two-fold axial symmetry", 2),
("3", "3", "three-fold axial symmetry", 3),
("5", "5", "five-fold axial symmetry", 5)
]
tile_items = [
(key, key, f"{key} lattice", idx)
for idx, key in enumerate((pfx + ele for pfx in ("", "dual") for ele in ("hex", "trihex", "snubhex", "rhombitrihex")), start=1)
]
mode_items = [
("ico", "ico", "render icosahedral mesh", 1),
("tri", "tri", "render triangular Caspar-Klug meshes", 2)
]

h: bpy.props.IntProperty(name="h", description="the h Caspar-Klug parameter", default=1, min=0)
k: bpy.props.IntProperty(name="k", description="the k Caspar-Klug parameter", default=0, min=0)
H: bpy.props.IntProperty(name="H", description="the H Caspar-Klug parameter", default=1, min=0)
K: bpy.props.IntProperty(name="K", description="the K Caspar-Klug parameter", default=0, min=0)
a: bpy.props.EnumProperty(name="a", description="the axial symmetry", items=axis_items, default=axis_items[2][3])
R: bpy.props.FloatProperty(name="R", description="the hexagonal lattice unit circumradius", default=1, min=0)
t: bpy.props.EnumProperty(name="t", description="the hexagonal lattice unit tile", items=tile_items, default=tile_items[0][3])
s: bpy.props.FloatProperty(name="s", description="the sphericity value", default=0, min=-1, max=1)
m: bpy.props.EnumProperty(name="mode", description="the render mode", items=mode_items, default=mode_items[0][3])
iter: bpy.props.IntProperty(name="iter", description="the iteration number for numerical methods", default=100, min=1)
tol: bpy.props.FloatProperty(name="tol", description="the machine epsilon for numerical methods", default=1E-15, min=0)

def execute(self, context):
from blendocapsid.modules.democapsid.democapsid import (calc_ckm,
calc_ico,
calc_lattice)

m, a, s = self.m, int(self.a), self.s
ckp = (self.h, self.k, self.H, self.K)
lat = calc_lattice(self.t, self.R)

if m == "ico":
meshes = calc_ico(ckp, lat, a=a, s=s, iter=self.iter, tol=self.tol)
elif m == "tri":
meshes = calc_ckm(ckp, lat)

for i, mesh in enumerate(meshes[1:], start=1):
collection = bpy.data.collections.new(f"face-{i}")
bpy.context.scene.collection.children.link(collection)
for j, polygon in enumerate(mesh, start=1):
mesh = bpy.data.meshes.new(name=f"polygon_msh[{i},{j}]")
mesh.from_pydata(*polygon, [])
mesh.validate(verbose=True)
obj = bpy.data.objects.new(f"polygon_obj-[{i},{j}]", mesh)
collection.objects.link(obj)

return {"FINISHED"}


def menu_func(self, context):
self.layout.operator(CapsidMesh.bl_idname)


def register():
bpy.utils.register_class(CapsidMesh)
bpy.types.VIEW3D_MT_object.append(menu_func)


def unregister():
bpy.utils.unregister_class(CapsidMesh)
9 changes: 9 additions & 0 deletions blender/blendocapsid/panels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import bpy


def register():
"""Register classes, types, etc."""


def unregister():
"""Unregister classes, types, etc."""
12 changes: 12 additions & 0 deletions blender/blendocapsid/patch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os
import sys


def add_local_modules_to_path():
"""Add local modules directory to system path. This is done so the
addon can find it's dependencies."""
modules_dir = os.path.join(os.path.dirname(__file__), 'modules')
modules_dir = os.path.abspath(modules_dir)

if modules_dir not in sys.path:
sys.path.append(modules_dir)
16 changes: 16 additions & 0 deletions blender/blendocapsid/reload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import blendocapsid


def all():
import importlib as il

# Reload package
il.reload(blendocapsid)

# Reload operators subpackage
il.reload(blendocapsid.operators)

# Reload panels subpackage
il.reload(blendocapsid.panels)

print('blendocapsid: Reload finished.')
8 changes: 8 additions & 0 deletions blender/makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.PHONY: dist clean

dist:
python package.py

clean:
rm -rf ./dist
find . -name "*.pyc" -delete
88 changes: 88 additions & 0 deletions blender/package.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""Packages the blendocapsid and dependency"""
import importlib
import os
import re
import zipfile

import blendocapsid

ignored_directories = (
'__pycache__',
'.DS_Store'
)


def gather_files(basedir, arc_prefix=''):
"""Walk the given directory and return a sequence of filepath, archive name
pairs.

Args:
basedir: The directory to start the walk

arc_prefix: A path to join to the front of the relative (to basedir)
file path

Returns:
A sequence of (filepath, archive name) pairs
"""
results = []

for path, subdirectories, files in os.walk(basedir):
if os.path.basename(path) in ignored_directories:
continue

for file in files:
relative_path = os.path.join(path, file)
full_path = os.path.abspath(relative_path)
arcname = os.path.relpath(full_path, os.path.dirname(basedir))
arcname = os.path.join(arc_prefix, arcname)

results.append((full_path, arcname))

return results


def get_required_modules():
"""Parse the requirements.txt file to determine dependencies.

Returns:
A sequence of module names
"""
with open('requirements.txt') as file:
data = file.read()
modules = data.split('\n')
pattern = '([A-Za-z0-9]+)(?:[<=>]+.*\n)?'

def get_module_name(s):
result = re.search(pattern, s)

if result:
return result.group()

modules = [get_module_name(s) for s in modules if s]

return modules


def run():
try:
os.mkdir('dist')

except FileExistsError:
pass

zip_entries = gather_files('blendocapsid')

for module in get_required_modules():
module = importlib.import_module(module)
zip_entries += gather_files(os.path.dirname(module.__file__), os.path.join('blendocapsid', 'modules'))

filename = f'blendocapsid-{blendocapsid.__version__}.zip'
filepath = os.path.abspath(os.path.join('dist', filename))
with zipfile.ZipFile(filepath, 'w') as dist_zip:
for filename, arcname in zip_entries:
dist_zip.write(filename, arcname)


if __name__ == '__main__':
run()
1 change: 1 addition & 0 deletions blender/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
democapsid @ git+https://github.com/dnanto/democapsid.git#egg=democapsid&subdirectory=py
21 changes: 21 additions & 0 deletions js/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 - 2024, Daniel Antonio Negrón (dnanto/remaindeer)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion py/src/democapsid/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys

from .cli import parse_args
from .democapsid import calc_ckm, calc_ckv, calc_ico, calc_lattice, cylinderize
from .democapsid import calc_ckm, calc_ico, calc_lattice

args = parse_args(sys.argv[1:])
h, k, H, K, a, R, t, s, m = (getattr(args, key) for key in "h,k,H,K,a,R,t,s,m".split(","))
Expand Down
11 changes: 5 additions & 6 deletions py/src/democapsid/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@ def parse_args(argv):
description="Calculate meshes for icosahedral virus capsids."
)
for ele in "hkHK":
parser.add_argument(ele, default=1, type=int, help=f"the {ele} Caspar-Klug parameter")
parser.add_argument(ele, type=int, help=f"the {ele} Caspar-Klug parameter")
choices = (5, 3, 2)
parser.add_argument("-a", "-axis", default=choices[0], choices=choices, type=int, help=f"the axial symmetry: {choices}")
parser.add_argument("-a", "-axis", default=choices[0], choices=choices, type=int, help="the axial symmetry")
parser.add_argument("-R", "-radius", default=1, type=int, help="the hexagonal lattice unit circumradius")
choices = ("hex", "trihex", "snubhex", "rhombitrihex")
choices = (*choices, *("dual" + ele for ele in choices))
choices = tuple(pfx + ele for pfx in ("", "dual") for ele in ("hex", "trihex", "snubhex", "rhombitrihex"))
parser.add_argument("-t", "-tile", default=choices[0], choices=choices, help="the hexagonal lattice unit tile")
parser.add_argument("-s", "-sphericity", default=0, type=float, help="the sphericity value")
choices = ("ico", "tri")
parser.add_argument("-m", "-mode", default=choices[0], choices=choices, help="the render mode")
parser.add_argument("-iter", default=100, type=int, help="the number of iterations for numerical methods")
parser.add_argument("-tol", default=1E-15, type=float, help="the machine epsilon")
parser.add_argument("-iter", default=100, type=int, help="the iteration number for numerical methods")
parser.add_argument("-tol", default=1E-15, type=float, help="the machine epsilon for numerical methods")
return parser.parse_args(argv)
Loading
Loading