I'm currently working on a model, where I want to use an Array of Integers in order to redeclare the shown components:
Image of the blocks and redeclaration-window
My goal is to have i.e. the blank at the top left corner redeclared to a pump if the integervalue in my reference array is 1. My question would be, if it is even possible to accomplish my goal this way, or if I have to go with the dropdown-menus/manual implementation?
I already tried to use an if-clause or an Array filled with strings, but Modelica/Dymola is only allowing records to be used in the fields for redeclaration. I also tried using "redeclare model extends", to vary the extends which didn't work because of errors in the syntax.
[Possible(?) workaround]
If this is truly impossible, could it be done by piling all the components/parameters up into one model and activate/deactivate the needed parts with a parameter as shown below?
small scale of the described "workaround"
Unfortunately I'm lacking a lot of knowledge when it comes to scripting. I hope my problem is understandable.
You cannot base a redeclare on the value of an Integer parameter.
Having all of the components in one model and disabling the unneeded parts simply doesn't work for parameters (it may possibly work in some cases for components, but it will be complicated, and I wouldn't recommend it) because you aren't allowed to use the conditional parameter.
I think you should present the original goal so that we can find a better solution.
Added: In case was just to redeclare all of the blocks in the same way you could use a "class parameter", i.e. replaceable model M=... and use that for all of the components.
But it seems the intent is to have them different which makes it trickier.
Related
I have seen the use of set keyword in tcl often. This cannot be used to create constant. How does one create constant in tcl which can then be used by other procedures?
Generally speaking, most of the uses of constants fall into several categories:
enumeration values
magical numbers
looping control factors
scaling factors
In Tcl, for the first case you'd usually just use the name instead of mapping it to an integer, with integer mappings only being applied in the cases that need them. Even bit sets can be handled that way, substituting a list of names for the set of bits (and the name being present in the list is equivalent to the bit being set). Tcl's C API has relevant functions for helping with this, specifically Tcl_GetIndexFromObj().
Magical values are usually best locked away close to the code that handles them. If I was interfacing to hardware, I'd not let the magic values appear at all at the script level (since I'd have the binding code written in C).
Looping control factors are often best represented as default values for procedure arguments, as they are things that you want to sometimes override. But they're often not as needed once custom control structures are available, and they fit a lot more into the Tcl style of working.
Scaling factors are the case where constants might be useful. I tend to simulate those by just using a global or namespace variable and plain old not assigning to it from elsewhere. I'd be quite interested in having code to allow constants (specifically variables that can't be assigned to) as a standard feature, but we don't have that right now.
Once those cases are covered, what remain tend to be unimportant constants. After all, there's almost no need to calculate the sizes of things for allocation and stuff like that, and things like positional binding in SQL statements are discouraged within TDBC in favour of binding by name (an awful lot easier to get right).
A simple way of making a constant is to put a write trace on a variable so that whenever it is written to, it is reset back to its constant value.
set CONSTANT 123
trace add variable CONSTANT write {apply {args {
global CONSTANT
# Reset to the constant value; write traces are after the fact
set CONSTANT 123
# Make the write give an error
error "may not change constant"
}}}
Let's say we have the following model:
Collector:
model Collector
Real collect_here;
annotation(defaultComponentPrefixes="inner");
end Collector;
and the following model potentially multiple times:
model Calculator
outer Collector collector;
Real calculatedVariable = 2*time;
equation
calculatedVariable = collector.collect_here;
end Calculator;
The code above works if calcModel is present only once in the system to be simulated. If the model exists more than once I get a singular system. This is demonstrated by the Example below. Changing the parameter works either gives a working or failing system.
model Example
parameter Boolean works = true;
inner Collector collector;
Calculator calculator1;
Calculator calculator2 if not works;
end Example;
Using an array inside the collector to pass multiple variables in it doesn't solve it.
Another possible way to solve this is possible by use of connectors, but I only made it work with one calcModel.
Using multiple instances of Calculator does brake the model, as the single variable calculatedVariable will have multiple equations trying to compute its value. Therefore Dymola complains that the system is structurally singular, in this case meaning that there are more equations than variables in the resulting system of equations.
To give a bit more of an insight: Actually checking Collector will fail, as since Modelica 3.0 every component has to be balanced (meaning it has to have as many unknowns as states), which is not the case for Collector as it does have one unknown but no equation. This strongly limits the possible applications for the inner/outer construct as basically every variable has to be computed where it is defined.
In the given example this is compensated in the overall system if exactly one Calculator is used. So this single combination will work. Although this works, it is something that should not be done - for the obvious reason of being very error-prone (and all sub-models should pass the check).
Your question on how to solve this issue actually misses a description of what the issue actually is. There are some cases in my mind that your approach could be useful for:
You want to plot multiple variables from a single point, which would be collector. For this purpose "variable selections" should be the most straight-forward way to go: see Dymola Manual Vol. 1, Section "4.3.11 Matching and variable selections" on how to apply them.
You want to carry out some mathematical operation on that variables. Then it could be useful to have a vectorized input of variable size. This enables an arbitrary number of connections to this input. For an example of this take a look at: Modelica.Blocks.Math.MultiSum
You want to route multiple signals between different models (which is unlikely judging from your description, but still): Then expandable connectors would be a good possibility. To get an impression of what that does take a look at Modelica.Blocks.Examples.BusUsage.
Hope this helps, otherwise please specify more clearly what you actually want to achieve with your code.
I prepared a demonstrative library for such scenario some days ago. You can access it at https://gist.github.com/beutlich/e630b2bf6cdf3efe96e5e9a637124fe1. If you read the documentation on Example2 you can see the link to an article from H. Elmqvis et. al., which is the clue to your problem. That is, you need a connector, and inherited connects from every Calculator to the one Collector.
I'm struggling with the size of output files for large Modelica models. Off course, I can protect some objects in order to remove them completely from the result file. However, that gives rise to two problems:
it's not possible to redeclare protected objects
if i want to test my model in detail (eg for a short time period), i need to declare those objects publicly again in order to see their variables
I wonder if there's a trick to set the 'verbosity' of a Modelica model. Maybe what I would like is a third keyword next to public, protected, eg. transparent. Then, when setting up a simulation, I want be able to set the verbosity level to 1, or 2 with the following effect:
1--> consider all transparentelements as protected
2--> consider all transparentelements as public
This effect would propagate to all models and submodels.
I don't think this already exists. But is there an easy workaround?
Thanks,
Roel
As Michael Tiller wrote above, this is not handled the same way in all Modelica tools and there is no definite answer. To give an OpenModelica-specific answer, it's possible to use simulate(ModelName,outputFilter="regex"), to store only the variables that fully match the given regex (default is .*, matching any variable).
Roel,
I know several people wrestling with this issue. At the moment, all of this depends on the tool being used. I don't know how other tools handle filtering of results, but in Dymola you control it (as you point out) by giving the signals special qualifiers (e.g. protected).
One thing I've done in the past is to extend from a model and then add a bunch of output signals for things I'm interested in. Then you can select "Outputs" in Dymola to make sure those get in the results file. This is far from perfect because a) listing everything you want can get tedious and b) referencing protected variables is not strictly allowed (although Dymola lets you get away with it but issues a warning).
At Dassault, we are actively discussing this idea and hope to provide some better functionality along these lines. It isn't clear whether such functionality will be strictly tool specific or whether it will involve the language somehow. But if it is language related, we will (of course) work with the design group to formulate a specification that other tool vendors can support as well.
In SystemModeler, you go to the Settings tab in the Experiment Browswer in Simulation Center. Click on Output on the bottom and select which variables to store.
(The options are state variables, derivatives, algebraic variables, parameters, protected variables and if you mark the Store simulation log-option, you'll get some interesting statistics on events over time and function evaluations, opening another possibility to track down parts of the simulation and model that creates more evaluations)
I am not sure if this helps you, but in Dymola you can go to Simulation->Setup->Output and mark a checkbox saying "Store Protected variables". That way it is possible to declare most variables as protected: during normal simulation they are not stored, but when debugging your model, you just mark that checkbox and they are stored.
Of course that is not the same as your suggested keyword transparent, but maybe it helps a little...
A bit late, but in Dymola 2013 FD01 and later you can select which variables to store based on names (and model names) using the annotation __Dymola_selections, and even filter on user-defined tags - so you could create a tag name "transparent" in the model. See "Matching and variable selections" in the manual.
As the iPad app I am making has been growing its size, it is hard for me to keep track of UI design values. Here, I am talking about values such as a table's width, background colors, and a title's font.
I would like to organize all UI design-related values and objects more efficiently.
How do you organize these?
Do you #define values in a header file?
Do you declare them as global variables or not?
Do you put your values one static class?
Or do you think not-organizing these values is rather better?
I would like to hear your advice.
Thank you :)
Yes it depends, therefore just some rules of thumb...
Do you #define values in a header file?
...in cases where I might want to change this locally only, eg for constants, colors, alignments, button images, ... the main reason why I do this however is the documentation it allows by giving the local defines a long explaining name
Do you declare them as global variables or not?
...an all my apps I have a MainDataManager Class, that holds all the variables I need globally - for the UI part often I have my own globally used object. This is extremely useful, simplifies the code, and probably one of the most important things I learned early on. might also see here Using Variable of AppDelegate as a Global Variable - question regarding release/retain
Do you put your values one static class?
...static classes exist kind of conceptually. Static variables are quite useful when you want to give a method some kind of memory of its own. However, none plays an important role in my UI.
In general, I like to use IB to layout the screens but set all the button names, labels, texts in the code. Why? Because when I have to localize the app maintaining multiple XIB files (for each language there will be one isolated XIB file to maintain) becomes a real burden even if there is only one single change in the layout.
All the global constant settings are always kept in GloblDefinitions.h while at the same time I have in my .pch file this entry #import "GlobalDefinitions.h"
So the combintation of a delegate variable provided globally + GlobalDefinitions.h for constants is my solution.
Its a good question. When combining use of interface builder with hand-coded UI tweaks and/or custom components you also have the problem of duplicated values between IB and code.
In some situations, for readability and for easy adjustment by a third party its easier if values are just hard coded in-place - so in trival cases (e.g. cases where the value is not repeated anywhere else or is unlikely to change) this might be a valid option.
In general, if the constants are specific to the layout of a particular UI component then it seems to make sense to #define them in the header file for the UI component that uses them - I think putting them all in one global file breaks the decoupling that you'd like to have between user interface components, and also for readability it can be easier for another dev to find them in the header file.
On the other hand if there are values that are used consistently across multiple UI components within the one application, then these can be defined in a global include file. Similarly if there are 'base' values that are used to derive other lengths etc. that are used commonly across multiple UI components these also can be stored in a global include.
Also whereever possible make use of the layout manager margin flexibility settings and width/height flexibility settings to minimise the need to hard code values. And when relevant, derive values from a base value or a system value (e.g. screen width).
At the end of the day if the value is there in code in front of you sometimes that much easier to figure out and tweak than changing a #define off in some other file - on the other hand - if the same value is repeated in multiple places and a #define is not used, then it can be very confusing for another coder to come in and change one of these repeated values only and try to understand and sift through the resultant side effects and which other places the value should be changed.
Well Ryan that depends upon you..
You can either use pre processor directives..
declaring in .pch file.
or you can either make an object class taking all the constants....
Hope that will help you..
Thanks
This is what I have learnt from few of my previous projects.
1] Naming conventions - use appropriate and standardized prefix. ex tblRecordLis, viewControlPanel etc.
2] Keep Constants together - keeping all constants at one place reduces the pain of searching entire project to find/fix/replace constants and their values.
3] Grouping relevant Classes together according to utility and their functionality.
4] UI constants like size, offsets , frame values (Which you need to hard code) can be kept in constants
a few which I used are
#define MenuPopoverFrame CGSizeMake(278, 550);
#define LandscapeContentSize #"{{0,0},{719,734}}"
#define PortraitContentSize #"{{2,0},{765,980}}"
5] Using IB as much as possible as it gives us more flexibility.
6] PROPER commenting and documentation proves to be a life saver when dealing with debugging.
I find it easy to declare keys as constants as using them at multiple places also increases the chances of error if used as such. eq key named #"method" can be better declared as
#define kMethodKey #"method"
This very simple thing saves my time while debugging when the project size grows larger.
** Taking hints from Apple's samples also gives you a great help in keeping your code standardized.
This is a general design question not relating to any language. I'm a bit torn between going for minimum code or optimum organization.
I'll use my current project as an example. I have a bunch of tabs on a form that perform different functions. Lets say Tab 1 reads in a file with a specific layout, tab 2 exports a file to a specific location, etc. The problem I'm running into now is that I need these tabs to do something slightly different based on the contents of a variable. If it contains a 1 I may need to use Layout A and perform some extra concatenation, if it contains a 2 I may need to use Layout B and do no concatenation but add two integer fields, etc. There could be 10+ codes that I will be looking at.
Is it more preferable to create an individual path for each code early on, or attempt to create a single path that branches out only when absolutely required.
Creating an individual path for each code would allow my code to be extremely easy to follow at a glance, which in turn will help me out later on down the road when debugging or making changes. The downside to this is that I will increase the amount of code written by calling some of the same functions in multiple places (for example, steps 3, 5, and 9 for every single code may be exactly the same.
Creating a single path that would branch out only when required will be a bit messier and more difficult to follow at a glance, but I would create less code by placing conditionals only at steps that are unique.
I realize that this may be a case-by-case decision, but in general, if you were handed a previously built program to work on, which would you prefer?
Edit: I've drawn some simple images to help express it. Codes 1/2/3 are the variables and the lines under them represent the paths they would take. All of these steps need to be performed in a linear chronological fashion, so there would be a function to essentially just call other functions in the proper order.
Different Paths
Single Path
Creating a single path that would
branch out only when required will be
a bit messier and more difficult to
follow at a glance, but I would create
less code by placing conditionals only
at steps that are unique.
Im not buying this statement. There is a level of finesse when deciding when to write new functions. Functions should be as simple and reusable as possible (but no simpler). The correct answer is almost never 'one big file that does a lot of branching'.
Less LOC (lines of code) should not be the goal. Readability and maintainability should be the goal. When you create functions, the names should be self documenting. If you have a large block of code, it is good to do something like
function doSomethingComplicated() {
stepOne();
stepTwo();
// and so on
}
where the function names are self documenting. Not only will the code be more readable, you will make it easier to unit test each segment of the code in isolation.
For the case where you will have a lot of methods that call the same exact methods, you can use good OO design and design patterns to minimize the number of functions that do the same thing. This is in reference to your statement "The downside to this is that I will increase the amount of code written by calling some of the same functions in multiple places (for example, steps 3, 5, and 9 for every single code may be exactly the same."
The biggest danger in starting with one big block of code is that it will never actually get refactored into smaller units. Just start down the right path to begin with....
EDIT --
for your picture, I would create a base-class with all of the common methods that are used. The base class would be abstract, with an abstract method. Subclasses would implement the abstract method and use the common functions they need. Of course, replace 'abstract' with whatever your language of choice provides.
You should always err on the side of generalization, with the only exception being early prototyping (where throughput of generating working stuff is majorly impacted by designing correct abstractions/generalizations). having said that, you should NEVER leave that mess of non-generalized cloned branches past the early prototype stage, as it leads to messy hard to maintain code (if you are doing almost the same thing 3 different times, and need to change that thing, you're almost sure to forget to change 1 out of 3).
Again it's hard to specifically answer such an open ended question, but I believe you don't have to sacrifice one for the other.
OOP techniques solves this issue by allowing you to encapsulate the reusable portions of your code and generate child classes to handle object specific behaviors.
Personally I think you might (if possible by your API) create inherited forms, create them on fly on master form (with tabs), pass agruments and embed in tab container.
When to inherit form and when to decide to use arguments (code) to show/hide/add/remove functionality is up to you, yet master form should contain only decisions and argument passing and embeddable forms just plain functionality - this way you can separate organisation from implementation.