I am working on a bayesian model, where I need to get new data every month to update the model. I am planning to extract the prior distribution from the previously saved model, and use only the new data to update the model. I am following the example here. I noticed, however the pm.Interpolated() method always returns an error now, and it seems to me that the pm.Interpolated() method is not working now, as I tried also just this function with some other data following this example
So now when using the pm.Interpolated() method, it always return this error. Is there a workaround for this function?
TypeError: No <class 'pymc3.model.Model'> on context stack
...
93 )
95 if not isinstance(name, string_types):
96 raise TypeError(f"Name needs to be a string but got: {name}")
TypeError: No model on context stack, which is needed to instantiate distributions. Add variable inside a 'with model:' block, or use the '.dist' syntax for a standalone distribution.
Related
I tried to simulate a diagram and it works for most of the time.
builder = DiagramBuilder()
...
diagram = builder.Build()
simulator = Simulator(diagram)
try:
simulator.Initialize()
simulator.AdvanceTo(float(1.5))
except RuntimeError:
pass
Until at some point, the drake simulation will terminate at 0.2000000s and return a TypeError.
simulator.AdvanceTo(float(1.5))
TypeError: AdvanceTo(): incompatible function arguments. The following argument types are supported:
1. (self: pydrake.systems.analysis.Simulator_[float], boundary_time: float) -> pydrake.systems.analysis.SimulatorStatus
Invoked with: <pydrake.systems.analysis.Simulator_[float] object at 0x7f59bbf169f0>, 1.5
I haven't seen this one before. I have tried many parameters but all simulations stop at 0.200000 second.
Am I missing anything, or what method should I try to debug?
*Edit
I figured out why the Simulator is unhappy with my setup. The parameter is correctly passed to Simulator but there is something wrong with one LeafSystem in my diagram.
In my diagram, there are discrete ports connected to each other. When a value is passed to a discrete LeafSystem, the system needs to call a function to update values (set_value() ) and return those values by a pointer. However, the function do need to return a status by which indicate the diagram the value update has been done. Therefore, EventStatus.Succeeded() is required to be returned if the update is successful.
Nevertheless, I have no idea why lack of status return will result into a TypeError. I'm to be honest, fairly new to drake so I might have a bad explanation. Willing to receive any professional comments.
In Python OOP is it possible to restrict the input when creating an object.
For e.g. if I only wanted int objects for a class. So if a string was entered it would return an error.
My initial thought was to write an if statement in the init method that would return an error msg if the conditions were not met.
The only problem with the above is that it seems that returning a statement in an init method is far from ideal.
Any guidance would be much appreciated
You can use type suggestions in the method header. This is considered better practices than forcing.
def __init__(name: str) -> str:
return "Hello, " + name
If you did need to force you can add isinstance(variable, type) like this.
if not isinstance(name, str):
raise TypeError
The basic way you would implement this is to add a check to your __init__ method that raises an error (usually a TypeError) if an incorrect type is passed into the method. You would also want to hint to your readers about the parameters expected type using function annotations. In practice though, it is generally better to try and convert whatever was passed into the __init__ method into the type that you expect. Python is flexible, and using that flexibility to your advantage is beneficial for you in designing and building your application, as well as for anyone who potentially may want to utilize your code down the line.
An example:
class Test:
def __init__(self, param: int):
self.my_param = int(param)
In the above example, if you were to wrap your param with an exception, the entire application would crash if the exception was left unhandled. If you add the int() conversion, it will instead try to convert whatever is passed into an int, thereby saving your application from a crash as long as the passed item can be converted. There are cases where you would absolutely want to specify an exact type to be passed, but flexibility is usually more important.
Background
I am new to python and I am writing a simple function but I am also interested in learning to do things the correct / pythonic way as I progress in my journey.
Lets consider the function below
def test_func(nested_lists,val):
return
I am expecting two arguments. One argument would be a list containing more lists. Something like this [[1,2,3,],[4,5,6,]...]. The second argument could be a value like 1.
If someone say for instance passes in a single value as the first argument and an array as the second argument. My code as it is currently returning the correct output which is 0 , However is there another way that i should be handle this?
For example should I be doing something like this
if(type(value) == list):
return 0
Or do i not need to do anything because my function is returning 0 anyway.
I know this maybe a very basic question so please forgive me but coming from a java background I am new to python so i am not sure how to handle such scenarios in python.
The other answer illustrates the proper way to check in advance for problems you can foresee. I'll provide a different approach.
The idiomatic solution in python is to "ask forgiveness, not permission". There are a lot of things that can go wrong, and where other languages might ask you to foresee all those problems and address them manually, python encourages just handling them as they happen. I would recommend doing:
def test_func(nested_lists, val):
try:
...
except TypeError:
# do whatever error-handling behavior you need to
# either throw a custom exception or return a specific value or whatever
return 0
and then designing your code in such a way that, if nested_lists and values are not compatible types, then they throw a TypeError (e.g. trying to iterate through nested_lists should fail if nested_lists is not a list. You can experiment with this behavior in a python console, but in general trying to do something to a variable that doesn't work because it's not the right type will produce a TypeError).
If your current code is working correctly, there is no pressing need to change anything. However, there are some reasons you might want to code more defensively;
If the code will seem to work correctly when you pass in bogus values, it would be better if it raised an exception instead of return a bogus value. The responsibility to call it correctly lies squarely with the caller, but enforcing it can help make sure the code is correct.
if not isinstance(nested_lists,list):
raise ValueError('Need a list, got {0!r}'.format(nested_lists))
This has the drawback that it hardcodes list as the type for the first argument; properly reusable code should work with any type, as long as it has the required methods and behaviors to remain compatible with your implementation. Perhaps instead check for a behavior:
try:
something involving nested_lists[0][0]
except (IndexError, AttributeError):
raise ValueError('Expected nested list but got {0!r}'.format(nested_lists))
(The try is not strictly necessary here; but see below.)
If you get a traceback when you call the code incorrectly, but it is opaque or misleading, it is more helpful to catch and explicitly point out the error earlier. #or example, the snippet above (without the try wrapper) would produce
Traceback (most recent call last):
module __main__ line 141
traceback.print_exc()
module <module> line 1
test_func(1,1)
module <module> line 2
AttributeError: 'int' object has no attribute '__getitem__'
which is somewhat unobvious to debug.
If the code will be used by third parties, both of the above considerations will be more important from a support point of view, too.
Notice how the code raises an exception when called incorrectly. This is generally better than silently returning some garbage value, and the caller can similarly trap the error with a try/except if this is well-defined (i.e. documented!) behavior.
Finally, since Python 3.5, you have the option to use type annotations:
def test_func(nested_lists: list, val: int) -> int:
...
As noted in the documentation, the core language does not (yet?) enforce these type checks, but they can help static code analysis tools point out possible errors.
So I'm in the process of making a class in Python that creates a network (with pybrain) using solely the numeric input it's given {just a little process to get my feet wet in Pybrain's API}.
My problem is, I'm rather unfamiliar with how scopes work in classes, and while I basically have the program set up properly, it keeps returning a keyerror.
All the variables needed to be acted upon are created in the init function; the method I'm working on for the class is trying to call upon one of the variables, declared in the init function using the vars()[] method in Python. (you can actually see a portion of the code's...rough draft here:
Matching Binary operators in Tuples to Dictionary Items
Anyways, the method is:
def constructnetwork(self):
"""constructs network using gathered data in __init__"""
if self.recurrent:
self.network = pybrain.RecurrentNetwork
#add modules/connections here
elif self.forward:
self.network = pybrain.FeedForwardNetwork
else:
self.network = pybrain.network
print vars()[self.CONNECT+str(1)]
print vars()[self.CONNECT+str(2)]
print self.network
(pardon the bad spacing, it didn't copy and paste over well.) The part that's raising the KeyError is the "print vars()[self.CONNECT+str(1)], which should retreive the value of the variable "Connection1" (self.CONNECT = 'Connection'), but calls a keyerror.
How do I get the variables to transfer over? If you need more information to help just ask, I'm trying to keep the quesiton as short as possible.
vars() returns a reference to the dictionary of local variables. If you used vars() in your __init__ (as the code in the post you linked to suggests), then you just created a local variable in that method, which isn't accessible from anywhere outside that method.
What is it that you think vars() does, and what are you trying to do? I have a hunch that what you want is getattr and setattr, or just a dictionary, and not vars.
Edit: Based on your comment, it sounds like, indeed, you shouldn't use vars. You would be better off, in __init__, doing something like:
self.connections = {}
self.connections[1] = "This is connection 1"
then in your method, do:
self.connections[1]
This is just a vague guess based on your code, though. I can't really tell what you are intending for this "connection". Do you want it to be some data associated with your object?
I have noticed a particular feature in Visual Studio and I am wondering if this feature is also available in Eclipse + PyDev.
In Visual Studio, if one were to type a function call and that particular function does not already exist, VS would show a code error and give an option to generate a new empty function matching the signature provided in the function call.
In other words, same I am working in a particular Python function or class and I realize I need a new function to process some string. In my current function I type processString(myString), which returns an error because the processString function does not currently exist. Is there some way to then click on the processString function call and create a new block in my module:
def processString(myString):
pass
Thanks in advance for your help.
Thank you #Eric Wilson.
If I type the function call processString(myString) then hit 'CTRL+1' the code completion/template window appears offering me the option to create a new class, method, assign to a field, or assign to a variable.
This was exactly what I was looking for.