traits ui variable number of mayavi scenes and visualization of run time traits - enthought

I would like to present the user with a variable number of scenes within the GUI (arranged say horizontally) composing different views of the data, depending on runtime conditions?
I really don't want to redefine the GUI, and a number of scene related traits for every use case. (i.e. bool_scene_1_viewable=Bool(), bool_scene_2_viewable=Bool()... )
It looks like I might be able to define a wildcard trait: scene_=Instance(Scene,()). But, if this is the best way to do it, how would I go about combining n traits into a View?

(A) I did not distinguish between "runtime" dependence, and merely depending on some number of traits that are declared after initialization (but before config_traits is called). As such, I can use default_traits_view to create a view that depends on the current state of the object and its members.
(B) I was also confused about how to turn this list_of_scenes into an object that could be viewed. After all, HGroup and VGroup don't take lists! I was missing that * could be used to unpack the list.
Steps:
1. init class instance
foo=Foo()
add scenes as you like
foo.add_trait(string_scene_name,scene)
foo.scene_name_list.append(string_scene_name)
foo.scene_list.append(scene)
Create group within default_traits_view()
items=[Item(name,style='custom') for name in self. scene_name_list]
scene_group=Group( *items)

Related

Common variables for all subsystems in OpenMDAO

I'm trying build a framework which starts with reading an input file which contains some keys and corresponding values. I then update the variables accordingly:
from Inertia import Inertia
...
d = hf.read_input(fin)
locals().update(d)
Then, I'm defining the group MDA:
class MDA(om.Group):
class ObjCmp(om.ExplicitComponent):
def setup(self):
...
def setup_partials(self):
...
def compute(self, inputs, outputs):
...
def setup(self):
...
which contains two subsystems (for now):
self.add_subsystem('d1', SomeModule(), promotes_inputs=['x1','x2'],
promotes_outputs=['y1','y2'])
self.add_subsystem('obj_cmp', self.ObjCmp(), promotes_inputs=['y1'],
promotes_outputs=['obj'])
For housekeeping reasons, since the framework will eventually contain large number of subsystems, I want to keep the classes defining the particular subsystems in separate scripts, imported the the main script (the one where the Group is defined).
The problem I'm facing is that if I only read the input file once at the level of the script where the Group is defined (before entering the Group() class), the variables retrieved this way are not defined at the lower levels, for instance, I cannot use them inside SomeModule(). I'd normally define an init() method inside SomeModule() to be able to pass some variables:
def __init__(self, d):
self.d = d
but since we instantiate the SomeModule() class within self.add_subsystem(), it does not work.
I would be really grateful for any hints.
In OpenMDAO, we deal with this instantiation timing issue in two ways:
We strongly discourage the use of the __init__ method for components or groups. Instead, we recommend you rely on the initialize and setup methods. initialize is called inside the existing __init__ (i.e. at instantiation time). setup is called much later during the build up of the model hierarchy.
We do provide a means of creating init arguments via an options system. Options allow for some built in validation and also give you the chance to change the values later if you want to.
Delaying as much as possible till setup, if you can. Pass your configuration file (or an object built from it if you prefer) into your component as an option, but don't actually use it till setup.
This goes for both components and groups. You can make the configuration data an option at all levels of your groups. They will each pass the object down to their children inside their own setup methods. This way, you only need to have the object in existence by the time you initialize the top level group. It will then pass it down to all its children.

Pure Data abstraction to take n arguments

I've created a Pure Data abstraction which takes 5 MIDI controller IDs as arguments, and has two inlets (velocity and MIDI controller). I use spigot to output the input velocity at outlet i if the MIDI controller ID matches the i th argument to the abstraction.
I use this to control 5 sliders (volume, attack, decay, sustain, release) from my MIDI controller, which look like this:
As you can see, the abstraction is very repetitive, and ideally it would be able to take n arguments, outputting the slider value of the given MIDI slider at the i th outlet. Alternatively I could just use a single argument and use the abstraction anew for each slider, but that's a bit repetitive too.
Is there a way to take n arguments in my abstraction? Or, is there any other more elegant solution to control sliders from MIDI that I'm missing?
For core vanilla objects or externals it is a common feature to take a variable amount of arguments. Many objects like [trigger], [select], [pack] or [unpack] behave this way and create a number of xlets according to how many arguments they are given.
For abstractions however, there is no simple way to have a variable number of outputs depending on the number of arguments given. It's possible, but it's rather a hack.
Let's first look at some techniques to make the patches easier.
As you can see in the following screenshot the [expr] object in your patch can easily be substituted by a simple Pd object: [==]
Let's look at the MIDI messages. MIDI objects output the elements of the hierarchical tree: channel, controller, value in this order but from right to left (true for all objects in Pd, the rightmost outlet fires first). What you want is routing them according to the controller number, ignoring the channel number. For this you need to flip the order of the two first outlets so you can use the controller number as a selector in a list. One way to do this is to pack the numbers and then reorder them in a message using the dollar symbols (careful, dollar symbols in message objects operate on local messages, they have nothing to do with what dollar symbols do in object boxes). Another method would be to use the object [swap] (using [swap] in this case would reduce the number of objects by one in the patch, but the [pack] and [message( is more versatile, that's why I show it here).
Regarding the actual question of taking n arguments to change the number of outlets: This challenge are two separate problems:
How to detect the number of arguments
How to change the number of outlets dynamically
Until recently there hasn't been a way proper way to detect the existence of arguments. Since Pd 0.50 there is [pdcontrol] which allows exactly this.
Using [initbang] here because [loadbang] would fire too late for creating the outlets.
The second part of the challenge may be solved either through a technique called 'dynamic patching' or by outputting a list instead of creating additional outlets. However with a list output you'd need to route it afterwards and then you'll arrive quickly at the patch pictured above.

Anylogic: Declare parameter of type ArrayList

I'm building a class (sorry - Agent) that will work with a set of Tank objects (Fluid Library) - doing things like monitoring individual levels or total level of all tanks, reporting on levels and initiating actions based on levels - things of that nature. For argument's sake let's call it a "TankMonitor" agent.
Ideally I'd like to be able to define a Parameter in my "TankMonitor" agent that allows me to define the tanks of interest when I place a TankMonitor in main. I have tried to define the type of the parameter as Other - ArrayList<Tank> however I don't know how to set up the next step to allow me to populate the ArrayList of Tanks when I put an instance of this agent in main. My preference would be to have a list type control to populate the ArrayList - much like the way the AnyLogic Seize block allows you to specify multiple resource pools to choose from.
Has anyone attempted this before and been successful?
This is possible as follows:
Change the type to "Other" and then 'Tank[]' , i.e. an Array of Tanks
Change the control type to "one-dimensional array"
Example below. Now you have the same UI to pre-define tanks at design time for your agent instance.
In addition to Benjamin's perfect answer, I'd just add the manual workaround, which is not needed here but can be useful when the parameter in question has a more complicated structure than covered by the pre-made controls, say a list of lists, a map, or similar.
In such a case, the Control Type is still Text, and populating it in an instance happens by pointing it to a new object of the parameter's type. E.g. for an ArrayList<Tank> parameter, you might instantiate a new ArrayList object, which you fill with a list of objects like so:
new ArrayList<Tank>(Arrays.asList(tankA, tankB))
In the Java code, whatever is written into that text box will end up on the right side of a parameter assignment statement in the embedded Agent instance's auto-generated parameter setup function. Therefore, multi-statement code won't work in this spot. Instead, if the process of building the parameter value doesn't fit neatly into a single expression, you can hide the code in a function which returns the desired object, and call that from the parameter's text box.

Is it OK to Move Common ViewController Presentation Logic into Presentation Helper Classes

I'm trying to use layers to make sure I separate everything into it's correct areas in my Swift / iOS / Xcode 6 project. The question, ultimately, is: is it OK / a common practice to move commonly used presentation-level logic to a separate presentation helper class instead of writing it over and over in multiple view controllers with little or no difference?
Here is an example to tie this in and give context:
One of the things I am aiming to do is use a UITableView to display report data. This UITableView will contain 7-10 rows, depending upon the user's preferences (nsuserdefaults). Each row contains a localized string for a label, and some decimal value.
As an example one row could be "Sales made this week: $500.00"
I have a reporting service class that's responsible for talking to the database and getting back / instantiating a report object. This report object contains the raw data for the report, i.e. how much you made this week, this month, this year, etc. Whether the user wants to show all these values or not is irrelevant to the service - it simply gets everything.
So since I have 3 view models that use this same report, I thought it would be wrong to rewrite the same code each time that checks the user's preferences, then creates/binds an array to the UITable and matches the labels with the report values from the object returned by the service.
A better way, I thought, was to create a presentation-level helper class whose job would be to take a report object (the thing I mentioned before that contains the report values), take a user's preferences, and then more generically combine them to create a list of localized strings matched with their respective report values, agnostic to what the view controller wants. Maybe if that requirement changes later (where different view controllers need more customization) I could use flags or different function names within that class.
This way all I have to do is something like
var report = ReportHelper.GenerateReport(reportData, userSettings)
and now report would be an object that could look like this (mock JSON data):
{"Amount made this week":"$100", "Amount made this month":"$500", "Amount made this year": "$10,000"}
And I can use this in any view controller.
The alternate is to just hard code those above values (obviously still pulling localized strings) but I don't know if I adding all those strings + checks based on user preferences + formatting. Seems more elegant to move it away.
Thanks!
I know too little about your problem to provide the definite answer, but basically you have 2 options:
- inheritance
- composition
I personally like inheritance although it is often stated you should choose composition over inheritance.
Your helper sounds somewhat like composition, so that would be the preferred setup. With your specific problem as I understand it, inheritance would lead to a duplication of data, so that is one more argument to choose composition.
So all in all you seem to be about right
Edit:
Inheritance is an "is" relationship, whereas composition is a "has" relationship.
See http://en.wikipedia.org/wiki/Object_composition for more details about composition.
And see http://en.wikipedia.org/wiki/Composition_over_inheritance for more info why and when to choose composition

Game: General Structure and Game Item Structure

I am making a graphically simple 3D game in C++ using DirectX. The main problem I am having is with how to structure some things efficiently. Right now I know my goal for certain areas but not how to ideally perform them.
For instance, right now I am storing all meshes and textures in an Asset class with enumerated definitions pointing to each asset. All meshes and textures are loaded when the game starts by creating an Asset object and initializing it. From there I load meshes and textures to objects by assigning the pointer given by the Asset object. Is this the best way to go about this?
A harder topic is that of items. For the sake of argument I am going to say we are dealing with scenery. Right now my scenery needs the following:
A name
A mesh
Textures (optional)
Flags (such as Destructible, Flammable, etc.)
Status (such as Burning, Locked, Cursed, etc.)
Abilities (things the object actually does, such as becoming damaged when burning)
The first 5 things on this list are simply variables. But abilities are bothering me. The first 5 can all exist in one item class. But what I do not know how to do is somehow attach abilities to the object.
For example; I want the object to have the "Fire Nova" ability. At the start of each turn, the object damages anything near it.
For me, this means each object would need a "Trigger_Phase_TurnStart()" or some similarly named method and would then need a new "Fire Nova" class with its own unique action for that trigger and its own extra variables (Damage, Range, etc). So now I have the base object class and a new Fire Nova class that inherits from it.
But now what if I needed an object that has Fire Nova and Frost Nova and also Slowing Aura and other such abilities. Basically I need a way to add triggered effects to an object without needing a new object class for each of them.
So by the end I would be able to have say:
(pseudo code of the object's components)
name = Elemental Orb
mesh = "Mesh_Sphere"
textures[] = "Tex_Ice", "Tex_Fire"
flags = OF_Destructible
status = SF_Cursed | SF_Burning
abilities[] = Fire_Nova, Frost_Nova, Slowing_Aura
And this orb would simply be the object class with all these attributes. The object would then activate each stored ability's trigger at the appropriate turn phase for any actions to perform.
Right now I am thinking I might need to make a class for each ability possessing every turn-phase or action trigger (inherited from a base ability class) and have them perform the appropriate action when the object calls them from it's array of abilities. Would this be the best way to do this?
As a separate issue. Some flags would require additional variables that would otherwise be unnecessary. For example, Destructible would mean the object would have health whereas without the flag it wouldn't need it, or an Openable item would need an array of contents. What would be a good way to ration these variables to when they are needed? I do not need every wall to have health and an empty contents array for example.
Finally. Assuming the bullet-listed attributes above are all an item needs, how might you suggest I best store them? To clarify, I would like to be able to write:
CreateItem(ITEM_CHAIR);
and have this return the created object with name, mesh, textures, flags, status and abilities. What structure might be suitable for achieving such an end effect?
To summarise:
Does my current Asset storage seem feasible?
What is the best way to create abilities to attach to the object class without making numerous separate object classes?
Is there a way to limit the variables (or at least memory usage) when the associated flag is not present?
What structure or format would be best for storing fixed item definitions?
Sorry if this is a little long winded. If you cannot answer all the questions then an answer to one would still be appreciated. Question two is probably the largest priority for me right now.
Thanks for your time :)
I want only answer question 2 and it looks like you need a decorator pattern. In OOP a decorator pattern is useful when you have many ingredients and wants to decorate an object, for example a pizza. Unfortunately you need to create for each ingredient a separate class hence I think you have the right approach. The good thing is that with the decorator pattern you can wrap the object over and over with abilites classes and call only one method at the end to do all the stuff.