Maya Python Mash - How can I add a selection set using Maya Mash API (in python) - maya

Adding the cmds.connectAttr at the end does connect the selection set in Maya in the UI, but that's all it does. It acts as it its not registering.
import maya.cmds as cmds
import MASH.api as mapi
sel = cmds.ls(sl=1, l=1, fl=1)
new_set = cmds.sets(sel, n="custom_set")
obj_name = sel[0].split(".")[0]
shape = cmds.listRelatives(obj_name, s=True, f=1)
print(shape)
shape = "pCylinderShape1" #distribute mesh
cmds.select("|pCylinder2") #main mesh MASH
#create a new MASH network
mashNetwork = mapi.Network()
mashNetwork.createNetwork(name="Custom_placement", geometry="Repro")
shape = "pCylinderShape1"
mashNetwork.meshDistribute(shape, 4)
cmds.connectAttr(new_set+".message", mashNetwork.distribute+".selectionSetMessage")
Closest answer I found was here but I am not a programmer to know what that means.
If anyone can help, I'd much appreciate it.

After a lot of investigation I did manage to find the answer from the provided link.
The code I wrote was only the first part of the solution.
hasMASHFlag = cmds.objExists('%s.mashOutFilter' % (new_set))
if not hasMASHFlag:
cmds.addAttr( new_set, longName='mashOutFilter', attributeType='bool' )
cmds.setAttr( '%s.arrangement' % (mashNetwork.distribute), 4 )
cmds.setAttr( '%s.meshType' % (mashNetwork.distribute), 7 )
Note sure is needed but I noticed when you connect a selection set by default it has an extra attribute called mashOutFilter.
The part that is needed is the .meshType that makes it work.

Related

How to assign multiple variables in a loop for graphs in Python 3

I am relatively new to coding and I have a few issues I don't quite understand how to solve, yet. I'm trying to build code that will make graphs that will produce from a ticker list, with the data downloading from yahoo finance. Taking out of account manually assigning stock1 (and so forth) a ticker for a moment...
I want to figure out how to loop the data going into running the graph, so TSLA and MSFT in my code. So far I have the code below, which I already changed dfs and stocks. I just don't understand how to make the loop. If anyone has some good resources for loops, as well, let me know.
Later, I would like to save the graphs as a png with file names corresponding to the stock being pulled from yahoo, so extra points if someone knows how to change this code (savefig = dict(fname="tsla.png", bbox_inches= "tight") which goes after style = 'default'. Thanks for the help!
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
import mplfinance as mpf
import yfinance as yf
#yahoo info
start = "2020-01-01"
end = dt.datetime.now()
stock1 = 'TSLA'
stock2 = 'MSFT'
df1 = yf.download(stock1, start, end)
df2 = yf.download(stock2, start, end)
stocks = [[stock1],[stock2]]
dfs = [[df1],[df2]]
changingvars = [[stocks],[dfs]]
#graph1
short_sma = 20
long_sma = 50
SMAs = [short_sma, long_sma]
for i in SMAs:
dfs["SMA_"+ str(i)] = dfs.iloc[:,4].rolling(window=i).mean()
graph1 = mpf.plot(dfs, type = 'candlestick',figratio=(16,6),
mav=(short_sma,long_sma),
volume=True, title= str(stocks),
style='default')
plt.show()
Not sure why you are calculating your own SMA's, and grouping your stocks and dataframes, if your goal is only to create multiple plots (one for each stock). Also, if you are using mplfinance, then there is no need to import and/or use matplotlib.pyplot (nor to call plt.show(); mplfinance does that for you).
That said, here is a suggestion for your code. I've added tickers for Apple and Alphabet (Google), just to demonstrate how this can be extended.
stocklist = ['TSLA','MSFT','AAPL','GOOGL']
start = "2020-01-01"
end = dt.datetime.now()
short_sma = 20
long_sma = 50
for stock in stocklist:
df = yf.download(stock, start, end)
filename = stock.lower() + '.png'
mpf.plot(df,type='candlestick',figratio=(16,6),
mav=(short_sma,long_sma),
volume=True, title=stock,style='default',
savefig=dict(fname=filename,bbox_inches="tight")
)
The above code will not display the plots for each stock, but will save each one in its own .png file locally (where you run the script) for you to view afterwards.
Note also that it does not save the actual data; only plots the data and then moves on to the next stock, reassigning the dataframe variable (which automatically deletes the previous stock's data). If you want to save the data for each stock in a separate csv file, that is easy to do as well with Pandas' .to_csv() method.
Also, I am assuming you are calling yf.download() correctly. I am not familiar with that API so I just left that part of the code as you had it.
HTH. Let me know. --Daniel

TF 2 - Keras - Merging two seperately trained models to a new ensemble model

Newbie here ;)
I need your help ;)
I have following problem:
I want to merge two TF 2.0 - Keras Models into a new Model.
Expect for example a ResNet50V2 without the head, and retrained on new data - saved weights are provided and loaded:
resnet50v2 = ResNet50V2(weights='imagenet', include_top=False)
#model.summary()
last_layer = resnet50v2.output
x = GlobalAveragePooling2D()(last_layer)
x = Dense(768, activation='relu', name='img_dense_768')(x)
out = Dense(NUM_CLASS, activation='softmax', name='img_output_layer')(x)
resnet50v2 = Model(inputs=resnet50v2.input, outputs=out)
resnet50v2.load_weights(pathToImageModel)
Expect for example a Bert Network retrained on new data - saved weights are provided, in the same way as shown before.
Now I want to skip the last softmax layer from the two models and "merge" them into a new Model.
So I took the layer before the last layer, which names I know:
model_image_output = model_image.get_layer('img_dense_768').output
model_bert_output = model_bert.get_layer('bert_output_layer_768').output
I built two new models with these informations:
model_img = Model(model_image.inputs, model_image_output)
model_bert = Model(model_bert.inputs, model_bert_output)
So now I want to concatenate the outputs of the two models into a new one and add a new "head"
concatenate = Concatenate()([model_img.output,model_bert.output])
x = Dense(512, activation = 'relu')(concatenate)
x = Dropout(0.4)(x)
output = Dense(NUM_CLASS, activation='softmax', name='final_multimodal_output')(x)
model_concat = Model([model_image.input, model_bert.input])
So far so good, model code seemed to be valid but then my knowledge ends.
The main questions are:
Also if the last softmax layers are skipped, the loaded weights should be still available or ?
The new concatened model wants to be build, ok but this ends in this error message, which I only partially understand:
NotImplementedError: When subclassing the Model class, you should implement a call method.
Is there another way to create for example the whole ensemble network and load only the pretrained parts of it and leave the rest beeing trainable?
Am I missing something? I never did subclassing the model class? If so, it was not intended XD
May I ask kindly for some hints ?
Thanks in advance!!
Kind regards ragitagha
UPDATE:
So to find my mistake more quickly and provide the solution in a more precise way:
I had to change the lines
concatenate = Concatenate()([model_img.output,model_bert.output])
x = Dense(512, activation = 'relu')(concatenate)
x = Dropout(0.4)(x)
output = Dense(NUM_CLASS, activation='softmax', name='final_multimodal_output')(x)
model_concat = Model([model_image.input, model_bert.input])
to:
concatenate = Concatenate()([model_img.output,model_bert.output])
x = Dense(512, activation = 'relu')(concatenate)
x = Dropout(0.4)(x)
output = Dense(NUM_CLASS, activation='softmax', name='final_multimodal_output')(x)
model_concat = Model([model_image.input, model_bert.input], output)

Repeating Processes on python but with mixed variables

Currently im trying to finish a script to pass links from a youtube playlist trough youtube_dl to be able to stream the audio from them on to a player on my raspberry pi, but I don't know how to repeat a process but changing the variable automatically without changing every single number on the array like so:
import os
import pafy
import youtube_dl as yt
from youtube_dl import YoutubeDL
links = ["http://www.youtube.com/watch?v=JaSfjAIcGpQ",
"http://www.youtube.com/watch?v=pzAo3Hj15R4",
"http://www.youtube.com/watch?v=hWdovALEen0",
"http://www.youtube.com/watch?v=JVpTp8IHdEg",
"http://www.youtube.com/watch?v=Pw-0pbY9JeU",
"http://www.youtube.com/watch?v=lrfhf1Gv4Tw",
"http://www.youtube.com/watch?v=ilw-qmqZ5zY",
"http://www.youtube.com/watch?v=UwsY_foobEw",
"http://www.youtube.com/watch?v=RSNmgE6L8AU",
"http://www.youtube.com/watch?v=d020hcWA_Wg",
"http://www.youtube.com/watch?v=O4irXQhgMqg",
"http://www.youtube.com/watch?v=9P16xvwMQ5A",
"http://www.youtube.com/watch?v=fregObNcHC8",
"http://www.youtube.com/watch?v=fLN6ec7-43s",
"http://www.youtube.com/watch?v=DcHKOC64KnE",
"http://www.youtube.com/watch?v=UYwF-jdcVjY",
"http://www.youtube.com/watch?v=jQcBwE6j09U",
"http://www.youtube.com/watch?v=lXgkuM2NhYI",
"http://www.youtube.com/watch?v=vabnZ9-ex7o",
"http://www.youtube.com/watch?v=neNJvLIKaOk",
"http://www.youtube.com/watch?v=k4V3Mo61fJM",
"http://www.youtube.com/watch?v=pstVCGyaUBM",
"http://www.youtube.com/watch?v=D8Ymd-OCucs",
"http://www.youtube.com/watch?v=SeRJb3U1v3A",
"http://www.youtube.com/watch?v=J0DjcsK_-HY",
"http://www.youtube.com/watch?v=f2JuxM-snGc",
"http://www.youtube.com/watch?v=Eyjj8BgsBGU",
"http://www.youtube.com/watch?v=dX3k_QDnzHE",
"http://www.youtube.com/watch?v=luM6oeCM7Yw",
"https://www.youtube.com/watch?v=5iC0YXspJRM",
"https://www.youtube.com/watch?v=BnOVufgbIzA",
"https://www.youtube.com/watch?v=wwK_Kmh0P90",
"https://www.youtube.com/watch?v=UYfh9YhUVdE"]
y = YoutubeDL({
'format': 'bestaudio',
})
url = links[0]
r = y.extract_info(url, download=False)
print(r['ext'])
print(r['url'])
I am trying to change the part of "links[0]"
so i can repeat this process but without changing the number manually, but instead doing it in python. Im still new at python.
As I understand you want to iterate over the list. You can make it with a for loop.
Like so:
for link in links:
url = link
r = y.extract_info(url, download=False)
Answer above seems okay, just to add on other ways to do it:
Shortest version:
extracted_details_list = [y.extract_info(url, download=False) for url in links] # list comprehension
A long version, could be easier to get the flow of for-loops:
for i in range(len(links)):
url = links[i]
r = y.extract_info(url, download=False)
print(r['ext'])
print(r['url']

Maya creating shader with cmds does not appear in hypershade

using maya 2014/2015 creating a shader like so:
import maya.cmds as cmds
my_shader = cmds.createNode('lambert', n='mine')
will create this result.
anybody knows how to get that shader to be reflected in the hypershade?
shaders are a slightly different node type:
cmds.shadingNode('lambert', asShader=1)
You'll also need to create a shadingEngine node, what we usually know as ShaderGroups or SG`s:
cmds.shadingNode('shadingEngine', asUtility=1)
and connect the .outColor of the shader to the .surfaceShader attribute of the SG. The SG node is actually a subclass of a Maya set, and to assign objects or faces to it use the sets command.
Adding to the answer for completeness:
In some cases (namely ShaderFx shaders) you need to connect the material to the scene's defaultShaderList1 node's next available plug.
import maya.cmds as mc
material = mc.shadingNode('lambert', asShader=True)
shading_engine = mc.sets(name="%sSG" % material, empty=True, renderable=True, noSurfaceShader=True)
mc.connectAttr('%s.outColor' % material, '%s.surfaceShader' % shading_engine)
mc.connectAttr('%s.msg'%material, ':defaultShaderList1.s', na=True)

Need to figure out how to use DeepZoomTools.dll to create DZI

I am not familiar with .NET coding.
However, I must create DZI sliced image assets on a shared server and am told that I can instantiate and use DeepZoomTools.dll.
Can someone show me a very simple DZI creation script that demonstrates the proper .NET coding technique? I can embellish as needed, I'm sure, but don't know where to start.
Assuming I have a jpg, how does a script simply slice it up and save it?
I can imagine it's only a few lines of code. The server is running IIS 7.5.
If anyone has a simple example, I'd be most appreciative.
Thanks
I don't know myself, but you might ask in the OpenSeadragon community:
https://github.com/openseadragon/openseadragon/issues
Someone there might know.
Does it have to be DeepZoomTools.dll? There are a number of other options for creating DZI files. Here are a few:
http://openseadragon.github.io/examples/creating-zooming-images/
Example of building a Seadragon Image from multiple images.
In this, the "clsCanvas" objects and collection can pretty much be ignored, it was an object internal to my code that was generating the images with GDI+, then putting them on disk. The code below just shows how to get a bunch of images from file and assemble them into a zoomable collection. Hope this helps someone :-).
CollectionCreator cc = new CollectionCreator();
// set default values that make sense for conversion options
cc.ServerFormat = ServerFormats.Default;
cc.TileFormat = ImageFormat.Jpg;
cc.TileSize = 256;
cc.ImageQuality = 0.92;
cc.TileOverlap = 0;
// the max level should always correspond to the log base 2 of the tilesize, unless otherwise specified
cc.MaxLevel = (int)Math.Log(cc.TileSize, 2);
List<Microsoft.DeepZoomTools.Image> aoImages = new List<Microsoft.DeepZoomTools.Image>();
double fLeftShift = 0;
foreach (clsCanvas oCanvas in aoCanvases)
{
//viewport width as a function of this canvas, so the width of this canvas is 1
double fThisImgWidth = oCanvas.MyImageWidth - 1; //the -1 creates a 1px overlap, hides the seam between images.
double fTotalViewportWidth = fTotalImageWidth / fThisImgWidth;
double fMyLeftEdgeInViewportUnits = -fLeftShift / fThisImgWidth; ; //please don't ask me why this is a negative numeber
double fMyTopInViewportUnits = -fTotalViewportWidth * 0.3;
fLeftShift += fThisImgWidth;
Microsoft.DeepZoomTools.Image oImg = new Microsoft.DeepZoomTools.Image(oCanvas.MyFileName.Replace("_Out_Tile",""));
oImg.ViewportWidth = fTotalViewportWidth;
oImg.ViewportOrigin = new System.Windows.Point(fMyLeftEdgeInViewportUnits, fMyTopInViewportUnits);
aoImages.Add(oImg);
}
// create a list of all the images to include in the collection
cc.Create(aoImages, sMasterOutFile);

Resources