In wurst, how to delete an exchange in an activity and add a new exchange - brightway

I created a new activity "alu_in_no" as the following code:
alu_in_eu = w.get_one(data, w.equals('location','IAI Area, EU27 & EFTA'), w.contains("name", "aluminium production, primary, liquid, prebake"))
alu_in_no = w.transformations.geo.copy_to_new_location(alu_in_eu, 'NO')
data.append(alu_in_no)
w.transformations.geo.relink_technosphere_exchanges(
alu_in_no,
data,
contained=False
)
The new activity has the following exchange:
{'amount': 14.65,
'loc': 14.65,
'location': 'IAI Area, EU27 & EFTA',
'name': 'market for electricity, medium voltage, aluminium industry',
'pedigree': {'completeness': 1,
'further technological correlation': 1,
'geographical correlation': 1,
'reliability': 1,
'temporal correlation': 3}
I want to delete this exchange in this activity and replace a new one, for example:
{'amount': 1.0,
'loc': 1.0,
'location': 'NO',
'name': 'market for electricity, medium voltage',
'product': 'electricity, medium voltage',
'production volume': 131798608305.945,
'type': 'production',
'uncertainty type': 0,
'unit': 'kilowatt hour'}
In other word, I want to unlink the previous activity and link another activity? I believe there must be some functions in wurst can do it but I cannot find.
Thanks in advance!

The list of exchanges is a normal list, so you can delete the exchange the same way you would delete from any other list, e.g. del my_list[some_index or my_list = [x for x in my_list if some_condition_on_x(x)].
You would need to relink your new exchange, but you already know how to do this: relink_technosphere_exchanges. You can run it more than once, it won't change exchanges which are linked already.

Related

With the Gemini Python API, how do I figure out fees for a completed transaction?

I'm using the Python private client for Gemini -- https://github.com/mtusman/gemini-python . I place my limit orders like so ...
order=private_client.new_order(symbol=formatted_name,
side=order_type,
price=str(fiat_price),
amount=str(amount)
)
This returns a hash with an "Id" key, which I can later use to query the status of an order ...
status = private_client.status_of_order(order_id=check)
which returns a hash that looks like the below
{'order_id': '1277897568', 'id': '1277897568', 'symbol': 'ethusd', 'exchange': 'gemini', 'avg_execution_price': '4347.51', 'side': 'buy', 'type': 'exchange limit', 'timestamp': '1638845825', 'timestampms': 1638845825850, 'is_live': False, 'is_cancelled': False, 'is_hidden': False, 'was_forced': False, 'executed_amount': '0.23', 'options': ['immediate-or-cancel'], 'price': '4347.51', 'original_amount': '0.23', 'remaining_amount': '0'}
How can I figure out what fees I was charged for the completed transaction? It doesn't appear I can figure it out from the status above, but I also don't see an API call that would provide this information.
https://docs.gemini.com/rest-api/#get-trade-volume; this might be helpful.
Otherwise, you might be able to implement a function that calculates your fee based on amount traded * the fee that corresponds to your volume, with the fees being laid out here: https://www.gemini.com/fees/api-fee-schedule#section-api-fee-schedule

Error creating invoice from custom module (Odoo 13)

I am trying to create an invoice from a custom object but I am getting errors from on validation .When I post, i get the following error: "
ValueError: Wrong value for account.move.line_ids: {'display_type': 'line_section', 'name': 'Phone Bill', 'product_id': 11783, 'product_uom_id': 19, 'current_reading': 66.0, 'current_date': datetime.date(2020, 11, 3), 'quantity': 17.0, 'price_unit': 565.0, 'account_id': 19, 'debit': 9605.0, 'credit': 0.0}
current_date and current_reading are custom fields i created. I am aware that Odoo automatically creates values for line_ids from invoice_line_ids if line_ids is not provided, so I am really stuck about this error.
Here's my code for creating the invoice:
class ReadingCorrection(models.TransientModel):
_name = 'reading.upload.wizard'
_description = 'Validate reading uploads'
def validate_entry(self):
active_ids = self._context.get('active_ids', []) or []
company = self.env.user.company_id
journal = self.env['account.move'].with_context(force_company=company.id, type='out_invoice')._get_default_journal()
for reads in self.env['reading.upload'].browse(active_ids):
if reads.reading >= reads.previous_reading: # and reads.state == 'draft':
account = reads.product_id.product_tmpl_id._get_product_accounts()['income']
if not account:
raise UserError(_('No account defined for product "%s".') % reads.product_id.name)
invoice = {
'type': 'out_invoice',
'invoice_date':reads.read_date,
'narration': reads.remark,
'invoice_user_id': reads.current_user.id,
'partner_id': reads.meter_id.customer_id.id,
'journal_id': 1,#journal.id,
'currency_id': reads.meter_id.customer_id.currency_id.id,
'doc_type': 'bill',
'invoice_line_ids':[(0,0, {
'name': reads.product_id.name,
'product_id': reads.product_id.id,
'product_uom_id': reads.product_id.uom_id.id,
'current_reading': reads.reading,
'previous_reading': reads.previous_reading,
'current_date': reads.read_date,
'quantity': reads.reading - reads.previous_reading,
'price_unit': reads.product_id.product_tmpl_id.lst_price,
'account_id': account.id,
})]
}
moves = self.env['account.move'].with_context(default_type='out_invoice').create(invoice)
#invoice = self.env['account.move'].sudo().create(invoice)
reads.write({'state':'uploaded'})
Any help given will be appreciated. Thanks
If you want to create invoices, in the lines you should not use the debit and credit fields since these are calculated, as it is a product line, you should not use display_type, since the line_section type is treated as an annotation and not as a price calculation line.
In the invoice data, when linking the lines 'invoice_line_ids': inv_line_ids an instruction must be specified to process the lines in your case it would be as follows 'invoice_line_ids': (0, 0, inv_line_ids) for greater information visit this page.

prices with different trial days in stripe

I have a checkout session like bellow with three different product-prices, and 3 different trial days:
session = stripe.checkout.Session.create(
customer="cus_ILmp6P6s1AfFWf",
payment_method_types=['card'],
line_items=[
{
'price': "price_1HjynjHdAaIdH7ntShQwSUAK",
'quantity': 1,
'tax_rates': ["txr_1Hk0zDHdAaIdH7ntg4yXtzmX", ],
},
{
'price': "price_1HkaSlHdAaIdH7ntd8cbQJbG",
'quantity': 1,
},
{
'price': "price_1Hjyj5HdAaIdH7nt0YQPLd60",
'quantity': 1,
}, ],
mode='subscription',
billing_address_collection='required',
subscription_data={'trial_period_days': 5},
allow_promotion_codes=True,
success_url=request.build_absolute_uri(reverse('thanks')) + '?session_id={CHECKOUT_SESSION_ID}',
cancel_url=request.build_absolute_uri(reverse('index_payment')),
)
however by using subscription_data={'trial_period_days': 5}, apparantely I have no choice but to assigne same trial period ( 5 days) to all of the items.
I was wondering if there is any way to set separate trial days for separate product/prices in checkout session. for instance what if only one of the products has trial?
Thanks,
You are creating a singular Subscription here with 3 different Prices. It doesn't make sense to have multiple trial periods since there's only one Subscription. Having a single Subscription with multiple billing anchors and trial periods would be a nightmare to maintain and audit later.
If you want to have separate trial periods for each Price, then you'd have to create a new Subscription for each.

Get dictionary value from a List inside a dictionary

I am looking to get the value of the description field inside the weather.
{'coord': {'lon': 73.85, 'lat': 18.52}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01d'}], 'base': 'stations', 'main': {'temp': 305.381, 'pressure': 949.7, 'humidity': 31, 'temp_min': 305.381, 'temp_max': 305.381, 'sea_level': 1023.73, 'grnd_level': 949.7}
i have seen many posts and i am trying to do the below:
r1 = requests.get('http://api.openweathermap.org/data/2.5/weather?q=Pune,in&APPID=5ad6ec2537bfb0d574363e115c2d0041')
print(r1.status_code)
json_data = json.loads(r1.text)
print(json_data)
print("Weather is" ,json_data["weather"][0])
But the above is fetching me all the values inside the dictionary.
What's the best way to achieve that?
Thanks.
Use json_data["weather"][0]['description'] to access the description field.

how to use the transverse_tagged_databases function in brightway2

I would like to know how to use the transverse_tagged_database method in brightway2. From the documentation is not entirely clear to me. Can we use for, example, to aggregate impacts by the isic code of the activities in the product system model?
The short answer is yes, aggregating impacts by ISIC code in your foreground product system model is exactly the kind of thing you can do using traverse_tagged_databases.
The traverse_tagged_databases function takes advantage of the fact that you can add arbitrary key:value pairs to activities in brightway to let you classify your the activities in your foreground model however you like.
For example, say your activities look like this:
('example_database', 'code_for_bread'):{
'name': 'Bread',
'code': 'code_for_bread',
'categories':[],
'exchanges':[...],
'location':'GLO'
'unit':'kg',
'database':'example_database',
'isic_code':'1071'
'isic_classifier':'Manufacture of bakery products'
},
You can tell traverse_tagged_databases to go through your database looking for a given key (tag), for example 'isic_code', or 'isic_classifier' and aggregate the impact based on these tags.
Say you were modelling a cheese sandwich, you could have the following ISIC codes in your model:
Sandwich: 1079 (Manufacture of other food products n.e.c.)
Bread: 1071 (Manufacture of bakery products)
Cheese: 1050 (Manufacture of dairy products)
Butter: 1050 (Manufacture of dairy products)
You can use traverse_tagged_databases to see the total impact of dairy (cheese and butter) vs bakery (bread).
You use it in a similar way to the LCA function, by specifying a functional unit as a dict and the method as a tuple, with an additional tag argument. Like this:
fu = {('example_database', 'code_for_sandwich'):1}
m = ('IPCC 2013', 'climate change', 'GWP 100a')
result, tree = traverse_tagged_databases(fu, m, 'isic_classifier')
The function returns two objects (designated result and tree in the line above)
For this analysis, your result will look something like this:
defaultdict(int,
{'Manufacture of other food products n.e.c.': 0,
'Manufacture of bakery products': 0.1875,
'Manufacture of dairy products': 0.55})
This is saying that dairy products in the foreground model have an aggregated impact of 0.55 kg CO2-eq, and bakery products have an aggregated impact of 0.1875 kg CO2-eq.
With a bit of post-processing you can turn this data into pie charts, stacked bar charts etc.
You also get a tree, which looks like this:
[{'activity': 'Sandwich' (kg, GLO, []),
'amount': 1,
'tag': 'Manufacture of other food products n.e.c.',
'impact': 0,
'biosphere': [],
'technosphere': [{'activity': 'Bread' (kg, GLO, []),
'amount': 0.75,
'tag': 'Manufacture of bakery products',
'impact': 0,
'biosphere': [{'amount': 0.1875,
'impact': 0.1875,
'tag': 'Manufacture of bakery products'}],
'technosphere': []},
{'activity': 'Butter' (kg, GLO, []),
'amount': 0.05,
'tag': 'Manufacture of dairy products',
'impact': 0,
'biosphere': [{'amount': 0.05,
'impact': 0.05,
'tag': 'Manufacture of dairy products'}],
'technosphere': []},
{'activity': 'Cheese' (kg, GLO, []),
'amount': 0.25,
'tag': 'Manufacture of dairy products',
'impact': 0,
'biosphere': [{'amount': 0.5,
'impact': 0.5,
'tag': 'Manufacture of dairy products'}],
'technosphere': []}]}]
This can look a bit difficult to parse at first, but is essentially a set of nested dictionaries, starting with the root activity (the functional unit = Sandwich), showing techosphere exchanges to other activities, and biosphere exchanges to emissions.
The tree here looks like this (with the amounts of each product in brackets)
Bread +----(0.75 kg)----------+
|
|
|
|
Cheese +----(0.20 kg)----------+------(1.00 kg)--------> Sandwich
|
|
|
|
Butter +----(0.05 kg)----------+
Again, with a bit of post-processing, you can turn this data into stuff like sankey diagrams, or the kind of impact tree diagram you get in SimaPro.

Resources